From 4265240f00974b83a354300c49010f03ac7c8b7d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Tue, 28 Feb 2023 07:08:42 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#491) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix: Add service_yaml_parameters to py_gapic_library BUILD.bazel targets PiperOrigin-RevId: 510187992 Source-Link: https://github.com/googleapis/googleapis/commit/5edc23561778df80d5293f20132765f8757a6b2c Source-Link: https://github.com/googleapis/googleapis-gen/commit/b0bedb72e4765a3e0b674a28c50ea0f9a9b26a89 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjBiZWRiNzJlNDc2NWEzZTBiNjc0YTI4YzUwZWEwZjlhOWIyNmE4OSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * chore: Update gapic-generator-python to v1.8.5 PiperOrigin-RevId: 511892190 Source-Link: https://github.com/googleapis/googleapis/commit/a45d9c09c1287ffdf938f4e8083e791046c0b23b Source-Link: https://github.com/googleapis/googleapis-gen/commit/1907294b1d8365ea24f8c5f2e059a64124c4ed3b Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMTkwNzI5NGIxZDgzNjVlYTI0ZjhjNWYyZTA1OWE2NDEyNGM0ZWQzYiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert --------- Co-authored-by: Owl Bot Co-authored-by: Victor Chudnovsky Co-authored-by: Anthonios Partheniou --- google/cloud/dlp_v2/gapic_metadata.json | 175 + .../services/dlp_service/async_client.py | 1 + .../dlp_v2/services/dlp_service/client.py | 3 + .../dlp_service/transports/__init__.py | 4 + .../services/dlp_service/transports/base.py | 1 + .../services/dlp_service/transports/grpc.py | 1 + .../dlp_service/transports/grpc_asyncio.py | 1 + .../services/dlp_service/transports/rest.py | 4794 +++++++++ google/cloud/dlp_v2/types/dlp.py | 2 + google/cloud/dlp_v2/types/storage.py | 2 + tests/unit/gapic/dlp_v2/test_dlp_service.py | 9102 ++++++++++++++++- 11 files changed, 13978 insertions(+), 108 deletions(-) create mode 100644 google/cloud/dlp_v2/services/dlp_service/transports/rest.py diff --git a/google/cloud/dlp_v2/gapic_metadata.json b/google/cloud/dlp_v2/gapic_metadata.json index df73928b..634002d4 100644 --- a/google/cloud/dlp_v2/gapic_metadata.json +++ b/google/cloud/dlp_v2/gapic_metadata.json @@ -356,6 +356,181 @@ ] } } + }, + "rest": { + "libraryClient": "DlpServiceClient", + "rpcs": { + "ActivateJobTrigger": { + "methods": [ + "activate_job_trigger" + ] + }, + "CancelDlpJob": { + "methods": [ + "cancel_dlp_job" + ] + }, + "CreateDeidentifyTemplate": { + "methods": [ + "create_deidentify_template" + ] + }, + "CreateDlpJob": { + "methods": [ + "create_dlp_job" + ] + }, + "CreateInspectTemplate": { + "methods": [ + "create_inspect_template" + ] + }, + "CreateJobTrigger": { + "methods": [ + "create_job_trigger" + ] + }, + "CreateStoredInfoType": { + "methods": [ + "create_stored_info_type" + ] + }, + "DeidentifyContent": { + "methods": [ + "deidentify_content" + ] + }, + "DeleteDeidentifyTemplate": { + "methods": [ + "delete_deidentify_template" + ] + }, + "DeleteDlpJob": { + "methods": [ + "delete_dlp_job" + ] + }, + "DeleteInspectTemplate": { + "methods": [ + "delete_inspect_template" + ] + }, + "DeleteJobTrigger": { + "methods": [ + "delete_job_trigger" + ] + }, + "DeleteStoredInfoType": { + "methods": [ + "delete_stored_info_type" + ] + }, + "FinishDlpJob": { + "methods": [ + "finish_dlp_job" + ] + }, + "GetDeidentifyTemplate": { + "methods": [ + "get_deidentify_template" + ] + }, + "GetDlpJob": { + "methods": [ + "get_dlp_job" + ] + }, + "GetInspectTemplate": { + "methods": [ + "get_inspect_template" + ] + }, + "GetJobTrigger": { + "methods": [ + "get_job_trigger" + ] + }, + "GetStoredInfoType": { + "methods": [ + "get_stored_info_type" + ] + }, + "HybridInspectDlpJob": { + "methods": [ + "hybrid_inspect_dlp_job" + ] + }, + "HybridInspectJobTrigger": { + "methods": [ + "hybrid_inspect_job_trigger" + ] + }, + "InspectContent": { + "methods": [ + "inspect_content" + ] + }, + "ListDeidentifyTemplates": { + "methods": [ + "list_deidentify_templates" + ] + }, + "ListDlpJobs": { + "methods": [ + "list_dlp_jobs" + ] + }, + "ListInfoTypes": { + "methods": [ + "list_info_types" + ] + }, + "ListInspectTemplates": { + "methods": [ + "list_inspect_templates" + ] + }, + "ListJobTriggers": { + "methods": [ + "list_job_triggers" + ] + }, + "ListStoredInfoTypes": { + "methods": [ + "list_stored_info_types" + ] + }, + "RedactImage": { + "methods": [ + "redact_image" + ] + }, + "ReidentifyContent": { + "methods": [ + "reidentify_content" + ] + }, + "UpdateDeidentifyTemplate": { + "methods": [ + "update_deidentify_template" + ] + }, + "UpdateInspectTemplate": { + "methods": [ + "update_inspect_template" + ] + }, + "UpdateJobTrigger": { + "methods": [ + "update_job_trigger" + ] + }, + "UpdateStoredInfoType": { + "methods": [ + "update_stored_info_type" + ] + } + } } } } diff --git a/google/cloud/dlp_v2/services/dlp_service/async_client.py b/google/cloud/dlp_v2/services/dlp_service/async_client.py index 5adce2d2..7b891db2 100644 --- a/google/cloud/dlp_v2/services/dlp_service/async_client.py +++ b/google/cloud/dlp_v2/services/dlp_service/async_client.py @@ -42,6 +42,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore diff --git a/google/cloud/dlp_v2/services/dlp_service/client.py b/google/cloud/dlp_v2/services/dlp_service/client.py index d9f2f134..9afd953c 100644 --- a/google/cloud/dlp_v2/services/dlp_service/client.py +++ b/google/cloud/dlp_v2/services/dlp_service/client.py @@ -46,6 +46,7 @@ except AttributeError: # pragma: NO COVER OptionalRetry = Union[retries.Retry, object] # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore @@ -55,6 +56,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, DlpServiceTransport from .transports.grpc import DlpServiceGrpcTransport from .transports.grpc_asyncio import DlpServiceGrpcAsyncIOTransport +from .transports.rest import DlpServiceRestTransport class DlpServiceClientMeta(type): @@ -68,6 +70,7 @@ class DlpServiceClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[DlpServiceTransport]] _transport_registry["grpc"] = DlpServiceGrpcTransport _transport_registry["grpc_asyncio"] = DlpServiceGrpcAsyncIOTransport + _transport_registry["rest"] = DlpServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/dlp_v2/services/dlp_service/transports/__init__.py b/google/cloud/dlp_v2/services/dlp_service/transports/__init__.py index b781126f..a7d8161e 100644 --- a/google/cloud/dlp_v2/services/dlp_service/transports/__init__.py +++ b/google/cloud/dlp_v2/services/dlp_service/transports/__init__.py @@ -19,14 +19,18 @@ from .base import DlpServiceTransport from .grpc import DlpServiceGrpcTransport from .grpc_asyncio import DlpServiceGrpcAsyncIOTransport +from .rest import DlpServiceRestInterceptor, DlpServiceRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[DlpServiceTransport]] _transport_registry["grpc"] = DlpServiceGrpcTransport _transport_registry["grpc_asyncio"] = DlpServiceGrpcAsyncIOTransport +_transport_registry["rest"] = DlpServiceRestTransport __all__ = ( "DlpServiceTransport", "DlpServiceGrpcTransport", "DlpServiceGrpcAsyncIOTransport", + "DlpServiceRestTransport", + "DlpServiceRestInterceptor", ) diff --git a/google/cloud/dlp_v2/services/dlp_service/transports/base.py b/google/cloud/dlp_v2/services/dlp_service/transports/base.py index 7ec937f4..8d3bcc3f 100644 --- a/google/cloud/dlp_v2/services/dlp_service/transports/base.py +++ b/google/cloud/dlp_v2/services/dlp_service/transports/base.py @@ -22,6 +22,7 @@ from google.api_core import retry as retries import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.oauth2 import service_account # type: ignore from google.protobuf import empty_pb2 # type: ignore diff --git a/google/cloud/dlp_v2/services/dlp_service/transports/grpc.py b/google/cloud/dlp_v2/services/dlp_service/transports/grpc.py index 49370657..9aa76062 100644 --- a/google/cloud/dlp_v2/services/dlp_service/transports/grpc.py +++ b/google/cloud/dlp_v2/services/dlp_service/transports/grpc.py @@ -20,6 +20,7 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore import grpc # type: ignore diff --git a/google/cloud/dlp_v2/services/dlp_service/transports/grpc_asyncio.py b/google/cloud/dlp_v2/services/dlp_service/transports/grpc_asyncio.py index 602fa461..49af838a 100644 --- a/google/cloud/dlp_v2/services/dlp_service/transports/grpc_asyncio.py +++ b/google/cloud/dlp_v2/services/dlp_service/transports/grpc_asyncio.py @@ -19,6 +19,7 @@ from google.api_core import gapic_v1, grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore diff --git a/google/cloud/dlp_v2/services/dlp_service/transports/rest.py b/google/cloud/dlp_v2/services/dlp_service/transports/rest.py new file mode 100644 index 00000000..99ca1aae --- /dev/null +++ b/google/cloud/dlp_v2/services/dlp_service/transports/rest.py @@ -0,0 +1,4794 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.dlp_v2.types import dlp + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import DlpServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class DlpServiceRestInterceptor: + """Interceptor for DlpService. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the DlpServiceRestTransport. + + .. code-block:: python + class MyCustomDlpServiceInterceptor(DlpServiceRestInterceptor): + def pre_activate_job_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_activate_job_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_cancel_dlp_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_create_deidentify_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_deidentify_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_dlp_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_dlp_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_inspect_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_inspect_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_job_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_job_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_stored_info_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_stored_info_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_deidentify_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_deidentify_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_deidentify_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_dlp_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_inspect_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_job_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_stored_info_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_finish_dlp_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_deidentify_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_deidentify_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_dlp_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_dlp_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_inspect_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_inspect_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_job_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_job_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_stored_info_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_stored_info_type(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_hybrid_inspect_dlp_job(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_hybrid_inspect_dlp_job(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_hybrid_inspect_job_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_hybrid_inspect_job_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_inspect_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_inspect_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_deidentify_templates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_deidentify_templates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_dlp_jobs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_dlp_jobs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_info_types(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_info_types(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_inspect_templates(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_inspect_templates(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_job_triggers(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_job_triggers(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_stored_info_types(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_stored_info_types(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_redact_image(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_redact_image(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reidentify_content(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reidentify_content(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_deidentify_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_deidentify_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_inspect_template(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_inspect_template(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_job_trigger(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_job_trigger(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_stored_info_type(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_stored_info_type(self, response): + logging.log(f"Received response: {response}") + return response + + transport = DlpServiceRestTransport(interceptor=MyCustomDlpServiceInterceptor()) + client = DlpServiceClient(transport=transport) + + + """ + + def pre_activate_job_trigger( + self, + request: dlp.ActivateJobTriggerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.ActivateJobTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for activate_job_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_activate_job_trigger(self, response: dlp.DlpJob) -> dlp.DlpJob: + """Post-rpc interceptor for activate_job_trigger + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_cancel_dlp_job( + self, request: dlp.CancelDlpJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.CancelDlpJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for cancel_dlp_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_create_deidentify_template( + self, + request: dlp.CreateDeidentifyTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.CreateDeidentifyTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_deidentify_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_create_deidentify_template( + self, response: dlp.DeidentifyTemplate + ) -> dlp.DeidentifyTemplate: + """Post-rpc interceptor for create_deidentify_template + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_create_dlp_job( + self, request: dlp.CreateDlpJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.CreateDlpJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_dlp_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_create_dlp_job(self, response: dlp.DlpJob) -> dlp.DlpJob: + """Post-rpc interceptor for create_dlp_job + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_create_inspect_template( + self, + request: dlp.CreateInspectTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.CreateInspectTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_inspect_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_create_inspect_template( + self, response: dlp.InspectTemplate + ) -> dlp.InspectTemplate: + """Post-rpc interceptor for create_inspect_template + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_create_job_trigger( + self, request: dlp.CreateJobTriggerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.CreateJobTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_job_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_create_job_trigger(self, response: dlp.JobTrigger) -> dlp.JobTrigger: + """Post-rpc interceptor for create_job_trigger + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_create_stored_info_type( + self, + request: dlp.CreateStoredInfoTypeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.CreateStoredInfoTypeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_stored_info_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_create_stored_info_type( + self, response: dlp.StoredInfoType + ) -> dlp.StoredInfoType: + """Post-rpc interceptor for create_stored_info_type + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_deidentify_content( + self, request: dlp.DeidentifyContentRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.DeidentifyContentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for deidentify_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_deidentify_content( + self, response: dlp.DeidentifyContentResponse + ) -> dlp.DeidentifyContentResponse: + """Post-rpc interceptor for deidentify_content + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_delete_deidentify_template( + self, + request: dlp.DeleteDeidentifyTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.DeleteDeidentifyTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_deidentify_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_delete_dlp_job( + self, request: dlp.DeleteDlpJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.DeleteDlpJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_dlp_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_delete_inspect_template( + self, + request: dlp.DeleteInspectTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.DeleteInspectTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_inspect_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_delete_job_trigger( + self, request: dlp.DeleteJobTriggerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.DeleteJobTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_job_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_delete_stored_info_type( + self, + request: dlp.DeleteStoredInfoTypeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.DeleteStoredInfoTypeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_stored_info_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_finish_dlp_job( + self, request: dlp.FinishDlpJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.FinishDlpJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for finish_dlp_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def pre_get_deidentify_template( + self, + request: dlp.GetDeidentifyTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.GetDeidentifyTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_deidentify_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_get_deidentify_template( + self, response: dlp.DeidentifyTemplate + ) -> dlp.DeidentifyTemplate: + """Post-rpc interceptor for get_deidentify_template + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_get_dlp_job( + self, request: dlp.GetDlpJobRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.GetDlpJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_dlp_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_get_dlp_job(self, response: dlp.DlpJob) -> dlp.DlpJob: + """Post-rpc interceptor for get_dlp_job + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_get_inspect_template( + self, + request: dlp.GetInspectTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.GetInspectTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_inspect_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_get_inspect_template( + self, response: dlp.InspectTemplate + ) -> dlp.InspectTemplate: + """Post-rpc interceptor for get_inspect_template + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_get_job_trigger( + self, request: dlp.GetJobTriggerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.GetJobTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_job_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_get_job_trigger(self, response: dlp.JobTrigger) -> dlp.JobTrigger: + """Post-rpc interceptor for get_job_trigger + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_get_stored_info_type( + self, request: dlp.GetStoredInfoTypeRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.GetStoredInfoTypeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_stored_info_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_get_stored_info_type( + self, response: dlp.StoredInfoType + ) -> dlp.StoredInfoType: + """Post-rpc interceptor for get_stored_info_type + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_hybrid_inspect_dlp_job( + self, + request: dlp.HybridInspectDlpJobRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.HybridInspectDlpJobRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for hybrid_inspect_dlp_job + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_hybrid_inspect_dlp_job( + self, response: dlp.HybridInspectResponse + ) -> dlp.HybridInspectResponse: + """Post-rpc interceptor for hybrid_inspect_dlp_job + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_hybrid_inspect_job_trigger( + self, + request: dlp.HybridInspectJobTriggerRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.HybridInspectJobTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for hybrid_inspect_job_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_hybrid_inspect_job_trigger( + self, response: dlp.HybridInspectResponse + ) -> dlp.HybridInspectResponse: + """Post-rpc interceptor for hybrid_inspect_job_trigger + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_inspect_content( + self, request: dlp.InspectContentRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.InspectContentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for inspect_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_inspect_content( + self, response: dlp.InspectContentResponse + ) -> dlp.InspectContentResponse: + """Post-rpc interceptor for inspect_content + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_list_deidentify_templates( + self, + request: dlp.ListDeidentifyTemplatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.ListDeidentifyTemplatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_deidentify_templates + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_list_deidentify_templates( + self, response: dlp.ListDeidentifyTemplatesResponse + ) -> dlp.ListDeidentifyTemplatesResponse: + """Post-rpc interceptor for list_deidentify_templates + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_list_dlp_jobs( + self, request: dlp.ListDlpJobsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.ListDlpJobsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_dlp_jobs + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_list_dlp_jobs( + self, response: dlp.ListDlpJobsResponse + ) -> dlp.ListDlpJobsResponse: + """Post-rpc interceptor for list_dlp_jobs + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_list_info_types( + self, request: dlp.ListInfoTypesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.ListInfoTypesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_info_types + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_list_info_types( + self, response: dlp.ListInfoTypesResponse + ) -> dlp.ListInfoTypesResponse: + """Post-rpc interceptor for list_info_types + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_list_inspect_templates( + self, + request: dlp.ListInspectTemplatesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.ListInspectTemplatesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_inspect_templates + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_list_inspect_templates( + self, response: dlp.ListInspectTemplatesResponse + ) -> dlp.ListInspectTemplatesResponse: + """Post-rpc interceptor for list_inspect_templates + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_list_job_triggers( + self, request: dlp.ListJobTriggersRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.ListJobTriggersRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_job_triggers + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_list_job_triggers( + self, response: dlp.ListJobTriggersResponse + ) -> dlp.ListJobTriggersResponse: + """Post-rpc interceptor for list_job_triggers + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_list_stored_info_types( + self, + request: dlp.ListStoredInfoTypesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.ListStoredInfoTypesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_stored_info_types + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_list_stored_info_types( + self, response: dlp.ListStoredInfoTypesResponse + ) -> dlp.ListStoredInfoTypesResponse: + """Post-rpc interceptor for list_stored_info_types + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_redact_image( + self, request: dlp.RedactImageRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.RedactImageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for redact_image + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_redact_image( + self, response: dlp.RedactImageResponse + ) -> dlp.RedactImageResponse: + """Post-rpc interceptor for redact_image + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_reidentify_content( + self, request: dlp.ReidentifyContentRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.ReidentifyContentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for reidentify_content + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_reidentify_content( + self, response: dlp.ReidentifyContentResponse + ) -> dlp.ReidentifyContentResponse: + """Post-rpc interceptor for reidentify_content + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_update_deidentify_template( + self, + request: dlp.UpdateDeidentifyTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.UpdateDeidentifyTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_deidentify_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_update_deidentify_template( + self, response: dlp.DeidentifyTemplate + ) -> dlp.DeidentifyTemplate: + """Post-rpc interceptor for update_deidentify_template + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_update_inspect_template( + self, + request: dlp.UpdateInspectTemplateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.UpdateInspectTemplateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_inspect_template + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_update_inspect_template( + self, response: dlp.InspectTemplate + ) -> dlp.InspectTemplate: + """Post-rpc interceptor for update_inspect_template + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_update_job_trigger( + self, request: dlp.UpdateJobTriggerRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[dlp.UpdateJobTriggerRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_job_trigger + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_update_job_trigger(self, response: dlp.JobTrigger) -> dlp.JobTrigger: + """Post-rpc interceptor for update_job_trigger + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + def pre_update_stored_info_type( + self, + request: dlp.UpdateStoredInfoTypeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[dlp.UpdateStoredInfoTypeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_stored_info_type + + Override in a subclass to manipulate the request or metadata + before they are sent to the DlpService server. + """ + return request, metadata + + def post_update_stored_info_type( + self, response: dlp.StoredInfoType + ) -> dlp.StoredInfoType: + """Post-rpc interceptor for update_stored_info_type + + Override in a subclass to manipulate the response + after it is returned by the DlpService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class DlpServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: DlpServiceRestInterceptor + + +class DlpServiceRestTransport(DlpServiceTransport): + """REST backend transport for DlpService. + + The Cloud Data Loss Prevention (DLP) API is a service that + allows clients to detect the presence of Personally Identifiable + Information (PII) and other privacy-sensitive data in + user-supplied, unstructured data streams, like text blocks or + images. + The service also includes methods for sensitive data redaction + and scheduling of data scans on Google Cloud Platform based data + sets. + To learn more about concepts and find how-to guides see + https://cloud.google.com/dlp/docs/. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "dlp.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[DlpServiceRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or DlpServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ActivateJobTrigger(DlpServiceRestStub): + def __hash__(self): + return hash("ActivateJobTrigger") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ActivateJobTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DlpJob: + r"""Call the activate job trigger method over HTTP. + + Args: + request (~.dlp.ActivateJobTriggerRequest): + The request object. Request message for + ActivateJobTrigger. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DlpJob: + Combines all of the information about + a DLP job. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/jobTriggers/*}:activate", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/jobTriggers/*}:activate", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_activate_job_trigger( + request, metadata + ) + pb_request = dlp.ActivateJobTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DlpJob() + pb_resp = dlp.DlpJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_activate_job_trigger(resp) + return resp + + class _CancelDlpJob(DlpServiceRestStub): + def __hash__(self): + return hash("CancelDlpJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.CancelDlpJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the cancel dlp job method over HTTP. + + Args: + request (~.dlp.CancelDlpJobRequest): + The request object. The request message for canceling a + DLP job. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/dlpJobs/*}:cancel", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/dlpJobs/*}:cancel", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_cancel_dlp_job(request, metadata) + pb_request = dlp.CancelDlpJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _CreateDeidentifyTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("CreateDeidentifyTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.CreateDeidentifyTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DeidentifyTemplate: + r"""Call the create deidentify + template method over HTTP. + + Args: + request (~.dlp.CreateDeidentifyTemplateRequest): + The request object. Request message for + CreateDeidentifyTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DeidentifyTemplate: + DeidentifyTemplates contains + instructions on how to de-identify + content. See + https://cloud.google.com/dlp/docs/concepts-templates + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/deidentifyTemplates", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/deidentifyTemplates", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*}/deidentifyTemplates", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/deidentifyTemplates", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_deidentify_template( + request, metadata + ) + pb_request = dlp.CreateDeidentifyTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DeidentifyTemplate() + pb_resp = dlp.DeidentifyTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_deidentify_template(resp) + return resp + + class _CreateDlpJob(DlpServiceRestStub): + def __hash__(self): + return hash("CreateDlpJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.CreateDlpJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DlpJob: + r"""Call the create dlp job method over HTTP. + + Args: + request (~.dlp.CreateDlpJobRequest): + The request object. Request message for + CreateDlpJobRequest. Used to initiate + long running jobs such as calculating + risk metrics or inspecting Google Cloud + Storage. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DlpJob: + Combines all of the information about + a DLP job. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/dlpJobs", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/dlpJobs", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_dlp_job(request, metadata) + pb_request = dlp.CreateDlpJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DlpJob() + pb_resp = dlp.DlpJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_dlp_job(resp) + return resp + + class _CreateInspectTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("CreateInspectTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.CreateInspectTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.InspectTemplate: + r"""Call the create inspect template method over HTTP. + + Args: + request (~.dlp.CreateInspectTemplateRequest): + The request object. Request message for + CreateInspectTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.InspectTemplate: + The inspectTemplate contains a + configuration (set of types of sensitive + data to be detected) to be used anywhere + you otherwise would normally specify + InspectConfig. See + https://cloud.google.com/dlp/docs/concepts-templates + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/inspectTemplates", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/inspectTemplates", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*}/inspectTemplates", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/inspectTemplates", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_inspect_template( + request, metadata + ) + pb_request = dlp.CreateInspectTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.InspectTemplate() + pb_resp = dlp.InspectTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_inspect_template(resp) + return resp + + class _CreateJobTrigger(DlpServiceRestStub): + def __hash__(self): + return hash("CreateJobTrigger") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.CreateJobTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.JobTrigger: + r"""Call the create job trigger method over HTTP. + + Args: + request (~.dlp.CreateJobTriggerRequest): + The request object. Request message for CreateJobTrigger. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.JobTrigger: + Contains a configuration to make dlp + api calls on a repeating basis. See + https://cloud.google.com/dlp/docs/concepts-job-triggers + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/jobTriggers", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/jobTriggers", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/jobTriggers", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_job_trigger( + request, metadata + ) + pb_request = dlp.CreateJobTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.JobTrigger() + pb_resp = dlp.JobTrigger.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_job_trigger(resp) + return resp + + class _CreateStoredInfoType(DlpServiceRestStub): + def __hash__(self): + return hash("CreateStoredInfoType") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.CreateStoredInfoTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.StoredInfoType: + r"""Call the create stored info type method over HTTP. + + Args: + request (~.dlp.CreateStoredInfoTypeRequest): + The request object. Request message for + CreateStoredInfoType. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.StoredInfoType: + StoredInfoType resource message that + contains information about the current + version and any pending updates. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=organizations/*}/storedInfoTypes", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=organizations/*/locations/*}/storedInfoTypes", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*}/storedInfoTypes", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/storedInfoTypes", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_create_stored_info_type( + request, metadata + ) + pb_request = dlp.CreateStoredInfoTypeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.StoredInfoType() + pb_resp = dlp.StoredInfoType.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_stored_info_type(resp) + return resp + + class _DeidentifyContent(DlpServiceRestStub): + def __hash__(self): + return hash("DeidentifyContent") + + def __call__( + self, + request: dlp.DeidentifyContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DeidentifyContentResponse: + r"""Call the deidentify content method over HTTP. + + Args: + request (~.dlp.DeidentifyContentRequest): + The request object. Request to de-identify a ContentItem. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DeidentifyContentResponse: + Results of de-identifying a + ContentItem. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/content:deidentify", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/content:deidentify", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_deidentify_content( + request, metadata + ) + pb_request = dlp.DeidentifyContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DeidentifyContentResponse() + pb_resp = dlp.DeidentifyContentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_deidentify_content(resp) + return resp + + class _DeleteDeidentifyTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("DeleteDeidentifyTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.DeleteDeidentifyTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete deidentify + template method over HTTP. + + Args: + request (~.dlp.DeleteDeidentifyTemplateRequest): + The request object. Request message for + DeleteDeidentifyTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/deidentifyTemplates/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/deidentifyTemplates/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/deidentifyTemplates/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/deidentifyTemplates/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_deidentify_template( + request, metadata + ) + pb_request = dlp.DeleteDeidentifyTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteDlpJob(DlpServiceRestStub): + def __hash__(self): + return hash("DeleteDlpJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.DeleteDlpJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete dlp job method over HTTP. + + Args: + request (~.dlp.DeleteDlpJobRequest): + The request object. The request message for deleting a + DLP job. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/dlpJobs/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/dlpJobs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_dlp_job(request, metadata) + pb_request = dlp.DeleteDlpJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteInspectTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("DeleteInspectTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.DeleteInspectTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete inspect template method over HTTP. + + Args: + request (~.dlp.DeleteInspectTemplateRequest): + The request object. Request message for + DeleteInspectTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/inspectTemplates/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/inspectTemplates/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/inspectTemplates/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/inspectTemplates/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_inspect_template( + request, metadata + ) + pb_request = dlp.DeleteInspectTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteJobTrigger(DlpServiceRestStub): + def __hash__(self): + return hash("DeleteJobTrigger") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.DeleteJobTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete job trigger method over HTTP. + + Args: + request (~.dlp.DeleteJobTriggerRequest): + The request object. Request message for DeleteJobTrigger. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=projects/*/jobTriggers/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/jobTriggers/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/jobTriggers/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_job_trigger( + request, metadata + ) + pb_request = dlp.DeleteJobTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _DeleteStoredInfoType(DlpServiceRestStub): + def __hash__(self): + return hash("DeleteStoredInfoType") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.DeleteStoredInfoTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete stored info type method over HTTP. + + Args: + request (~.dlp.DeleteStoredInfoTypeRequest): + The request object. Request message for + DeleteStoredInfoType. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v2/{name=organizations/*/storedInfoTypes/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=organizations/*/locations/*/storedInfoTypes/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/storedInfoTypes/*}", + }, + { + "method": "delete", + "uri": "/v2/{name=projects/*/locations/*/storedInfoTypes/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_stored_info_type( + request, metadata + ) + pb_request = dlp.DeleteStoredInfoTypeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _FinishDlpJob(DlpServiceRestStub): + def __hash__(self): + return hash("FinishDlpJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.FinishDlpJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the finish dlp job method over HTTP. + + Args: + request (~.dlp.FinishDlpJobRequest): + The request object. The request message for finishing a + DLP hybrid job. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/dlpJobs/*}:finish", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_finish_dlp_job(request, metadata) + pb_request = dlp.FinishDlpJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + class _GetDeidentifyTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("GetDeidentifyTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.GetDeidentifyTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DeidentifyTemplate: + r"""Call the get deidentify template method over HTTP. + + Args: + request (~.dlp.GetDeidentifyTemplateRequest): + The request object. Request message for + GetDeidentifyTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DeidentifyTemplate: + DeidentifyTemplates contains + instructions on how to de-identify + content. See + https://cloud.google.com/dlp/docs/concepts-templates + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/deidentifyTemplates/*}", + }, + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/deidentifyTemplates/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/deidentifyTemplates/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/deidentifyTemplates/*}", + }, + ] + request, metadata = self._interceptor.pre_get_deidentify_template( + request, metadata + ) + pb_request = dlp.GetDeidentifyTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DeidentifyTemplate() + pb_resp = dlp.DeidentifyTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_deidentify_template(resp) + return resp + + class _GetDlpJob(DlpServiceRestStub): + def __hash__(self): + return hash("GetDlpJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.GetDlpJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DlpJob: + r"""Call the get dlp job method over HTTP. + + Args: + request (~.dlp.GetDlpJobRequest): + The request object. The request message for [DlpJobs.GetDlpJob][]. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DlpJob: + Combines all of the information about + a DLP job. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/dlpJobs/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/dlpJobs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_dlp_job(request, metadata) + pb_request = dlp.GetDlpJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DlpJob() + pb_resp = dlp.DlpJob.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_dlp_job(resp) + return resp + + class _GetInspectTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("GetInspectTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.GetInspectTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.InspectTemplate: + r"""Call the get inspect template method over HTTP. + + Args: + request (~.dlp.GetInspectTemplateRequest): + The request object. Request message for + GetInspectTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.InspectTemplate: + The inspectTemplate contains a + configuration (set of types of sensitive + data to be detected) to be used anywhere + you otherwise would normally specify + InspectConfig. See + https://cloud.google.com/dlp/docs/concepts-templates + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/inspectTemplates/*}", + }, + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/inspectTemplates/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/inspectTemplates/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/inspectTemplates/*}", + }, + ] + request, metadata = self._interceptor.pre_get_inspect_template( + request, metadata + ) + pb_request = dlp.GetInspectTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.InspectTemplate() + pb_resp = dlp.InspectTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_inspect_template(resp) + return resp + + class _GetJobTrigger(DlpServiceRestStub): + def __hash__(self): + return hash("GetJobTrigger") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.GetJobTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.JobTrigger: + r"""Call the get job trigger method over HTTP. + + Args: + request (~.dlp.GetJobTriggerRequest): + The request object. Request message for GetJobTrigger. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.JobTrigger: + Contains a configuration to make dlp + api calls on a repeating basis. See + https://cloud.google.com/dlp/docs/concepts-job-triggers + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/jobTriggers/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/jobTriggers/*}", + }, + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/jobTriggers/*}", + }, + ] + request, metadata = self._interceptor.pre_get_job_trigger(request, metadata) + pb_request = dlp.GetJobTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.JobTrigger() + pb_resp = dlp.JobTrigger.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_job_trigger(resp) + return resp + + class _GetStoredInfoType(DlpServiceRestStub): + def __hash__(self): + return hash("GetStoredInfoType") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.GetStoredInfoTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.StoredInfoType: + r"""Call the get stored info type method over HTTP. + + Args: + request (~.dlp.GetStoredInfoTypeRequest): + The request object. Request message for + GetStoredInfoType. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.StoredInfoType: + StoredInfoType resource message that + contains information about the current + version and any pending updates. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=organizations/*/storedInfoTypes/*}", + }, + { + "method": "get", + "uri": "/v2/{name=organizations/*/locations/*/storedInfoTypes/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/storedInfoTypes/*}", + }, + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/storedInfoTypes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_stored_info_type( + request, metadata + ) + pb_request = dlp.GetStoredInfoTypeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.StoredInfoType() + pb_resp = dlp.StoredInfoType.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_stored_info_type(resp) + return resp + + class _HybridInspectDlpJob(DlpServiceRestStub): + def __hash__(self): + return hash("HybridInspectDlpJob") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.HybridInspectDlpJobRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.HybridInspectResponse: + r"""Call the hybrid inspect dlp job method over HTTP. + + Args: + request (~.dlp.HybridInspectDlpJobRequest): + The request object. Request to search for potentially + sensitive info in a custom location. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.HybridInspectResponse: + Quota exceeded errors will be thrown + once quota has been met. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/dlpJobs/*}:hybridInspect", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_hybrid_inspect_dlp_job( + request, metadata + ) + pb_request = dlp.HybridInspectDlpJobRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.HybridInspectResponse() + pb_resp = dlp.HybridInspectResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_hybrid_inspect_dlp_job(resp) + return resp + + class _HybridInspectJobTrigger(DlpServiceRestStub): + def __hash__(self): + return hash("HybridInspectJobTrigger") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.HybridInspectJobTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.HybridInspectResponse: + r"""Call the hybrid inspect job + trigger method over HTTP. + + Args: + request (~.dlp.HybridInspectJobTriggerRequest): + The request object. Request to search for potentially + sensitive info in a custom location. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.HybridInspectResponse: + Quota exceeded errors will be thrown + once quota has been met. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/jobTriggers/*}:hybridInspect", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_hybrid_inspect_job_trigger( + request, metadata + ) + pb_request = dlp.HybridInspectJobTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.HybridInspectResponse() + pb_resp = dlp.HybridInspectResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_hybrid_inspect_job_trigger(resp) + return resp + + class _InspectContent(DlpServiceRestStub): + def __hash__(self): + return hash("InspectContent") + + def __call__( + self, + request: dlp.InspectContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.InspectContentResponse: + r"""Call the inspect content method over HTTP. + + Args: + request (~.dlp.InspectContentRequest): + The request object. Request to search for potentially + sensitive info in a ContentItem. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.InspectContentResponse: + Results of inspecting an item. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/content:inspect", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/content:inspect", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_inspect_content(request, metadata) + pb_request = dlp.InspectContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.InspectContentResponse() + pb_resp = dlp.InspectContentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_inspect_content(resp) + return resp + + class _ListDeidentifyTemplates(DlpServiceRestStub): + def __hash__(self): + return hash("ListDeidentifyTemplates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ListDeidentifyTemplatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ListDeidentifyTemplatesResponse: + r"""Call the list deidentify templates method over HTTP. + + Args: + request (~.dlp.ListDeidentifyTemplatesRequest): + The request object. Request message for + ListDeidentifyTemplates. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ListDeidentifyTemplatesResponse: + Response message for + ListDeidentifyTemplates. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/deidentifyTemplates", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/deidentifyTemplates", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*}/deidentifyTemplates", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/deidentifyTemplates", + }, + ] + request, metadata = self._interceptor.pre_list_deidentify_templates( + request, metadata + ) + pb_request = dlp.ListDeidentifyTemplatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ListDeidentifyTemplatesResponse() + pb_resp = dlp.ListDeidentifyTemplatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_deidentify_templates(resp) + return resp + + class _ListDlpJobs(DlpServiceRestStub): + def __hash__(self): + return hash("ListDlpJobs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ListDlpJobsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ListDlpJobsResponse: + r"""Call the list dlp jobs method over HTTP. + + Args: + request (~.dlp.ListDlpJobsRequest): + The request object. The request message for listing DLP + jobs. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ListDlpJobsResponse: + The response message for listing DLP + jobs. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*}/dlpJobs", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/dlpJobs", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/dlpJobs", + }, + ] + request, metadata = self._interceptor.pre_list_dlp_jobs(request, metadata) + pb_request = dlp.ListDlpJobsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ListDlpJobsResponse() + pb_resp = dlp.ListDlpJobsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_dlp_jobs(resp) + return resp + + class _ListInfoTypes(DlpServiceRestStub): + def __hash__(self): + return hash("ListInfoTypes") + + def __call__( + self, + request: dlp.ListInfoTypesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ListInfoTypesResponse: + r"""Call the list info types method over HTTP. + + Args: + request (~.dlp.ListInfoTypesRequest): + The request object. Request for the list of infoTypes. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ListInfoTypesResponse: + Response to the ListInfoTypes + request. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/infoTypes", + }, + { + "method": "get", + "uri": "/v2/{parent=locations/*}/infoTypes", + }, + ] + request, metadata = self._interceptor.pre_list_info_types(request, metadata) + pb_request = dlp.ListInfoTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ListInfoTypesResponse() + pb_resp = dlp.ListInfoTypesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_info_types(resp) + return resp + + class _ListInspectTemplates(DlpServiceRestStub): + def __hash__(self): + return hash("ListInspectTemplates") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ListInspectTemplatesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ListInspectTemplatesResponse: + r"""Call the list inspect templates method over HTTP. + + Args: + request (~.dlp.ListInspectTemplatesRequest): + The request object. Request message for + ListInspectTemplates. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ListInspectTemplatesResponse: + Response message for + ListInspectTemplates. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/inspectTemplates", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/inspectTemplates", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*}/inspectTemplates", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/inspectTemplates", + }, + ] + request, metadata = self._interceptor.pre_list_inspect_templates( + request, metadata + ) + pb_request = dlp.ListInspectTemplatesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ListInspectTemplatesResponse() + pb_resp = dlp.ListInspectTemplatesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_inspect_templates(resp) + return resp + + class _ListJobTriggers(DlpServiceRestStub): + def __hash__(self): + return hash("ListJobTriggers") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ListJobTriggersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ListJobTriggersResponse: + r"""Call the list job triggers method over HTTP. + + Args: + request (~.dlp.ListJobTriggersRequest): + The request object. Request message for ListJobTriggers. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ListJobTriggersResponse: + Response message for ListJobTriggers. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*}/jobTriggers", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/jobTriggers", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/jobTriggers", + }, + ] + request, metadata = self._interceptor.pre_list_job_triggers( + request, metadata + ) + pb_request = dlp.ListJobTriggersRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ListJobTriggersResponse() + pb_resp = dlp.ListJobTriggersResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_job_triggers(resp) + return resp + + class _ListStoredInfoTypes(DlpServiceRestStub): + def __hash__(self): + return hash("ListStoredInfoTypes") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ListStoredInfoTypesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ListStoredInfoTypesResponse: + r"""Call the list stored info types method over HTTP. + + Args: + request (~.dlp.ListStoredInfoTypesRequest): + The request object. Request message for + ListStoredInfoTypes. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ListStoredInfoTypesResponse: + Response message for + ListStoredInfoTypes. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=organizations/*}/storedInfoTypes", + }, + { + "method": "get", + "uri": "/v2/{parent=organizations/*/locations/*}/storedInfoTypes", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*}/storedInfoTypes", + }, + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/storedInfoTypes", + }, + ] + request, metadata = self._interceptor.pre_list_stored_info_types( + request, metadata + ) + pb_request = dlp.ListStoredInfoTypesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ListStoredInfoTypesResponse() + pb_resp = dlp.ListStoredInfoTypesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_stored_info_types(resp) + return resp + + class _RedactImage(DlpServiceRestStub): + def __hash__(self): + return hash("RedactImage") + + def __call__( + self, + request: dlp.RedactImageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.RedactImageResponse: + r"""Call the redact image method over HTTP. + + Args: + request (~.dlp.RedactImageRequest): + The request object. Request to search for potentially + sensitive info in an image and redact it + by covering it with a colored rectangle. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.RedactImageResponse: + Results of redacting an image. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/image:redact", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/image:redact", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_redact_image(request, metadata) + pb_request = dlp.RedactImageRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.RedactImageResponse() + pb_resp = dlp.RedactImageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_redact_image(resp) + return resp + + class _ReidentifyContent(DlpServiceRestStub): + def __hash__(self): + return hash("ReidentifyContent") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.ReidentifyContentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.ReidentifyContentResponse: + r"""Call the reidentify content method over HTTP. + + Args: + request (~.dlp.ReidentifyContentRequest): + The request object. Request to re-identify an item. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.ReidentifyContentResponse: + Results of re-identifying an item. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{parent=projects/*}/content:reidentify", + "body": "*", + }, + { + "method": "post", + "uri": "/v2/{parent=projects/*/locations/*}/content:reidentify", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_reidentify_content( + request, metadata + ) + pb_request = dlp.ReidentifyContentRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.ReidentifyContentResponse() + pb_resp = dlp.ReidentifyContentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_reidentify_content(resp) + return resp + + class _UpdateDeidentifyTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("UpdateDeidentifyTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.UpdateDeidentifyTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.DeidentifyTemplate: + r"""Call the update deidentify + template method over HTTP. + + Args: + request (~.dlp.UpdateDeidentifyTemplateRequest): + The request object. Request message for + UpdateDeidentifyTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.DeidentifyTemplate: + DeidentifyTemplates contains + instructions on how to de-identify + content. See + https://cloud.google.com/dlp/docs/concepts-templates + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{name=organizations/*/deidentifyTemplates/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=organizations/*/locations/*/deidentifyTemplates/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/deidentifyTemplates/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/locations/*/deidentifyTemplates/*}", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_update_deidentify_template( + request, metadata + ) + pb_request = dlp.UpdateDeidentifyTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.DeidentifyTemplate() + pb_resp = dlp.DeidentifyTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_deidentify_template(resp) + return resp + + class _UpdateInspectTemplate(DlpServiceRestStub): + def __hash__(self): + return hash("UpdateInspectTemplate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.UpdateInspectTemplateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.InspectTemplate: + r"""Call the update inspect template method over HTTP. + + Args: + request (~.dlp.UpdateInspectTemplateRequest): + The request object. Request message for + UpdateInspectTemplate. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.InspectTemplate: + The inspectTemplate contains a + configuration (set of types of sensitive + data to be detected) to be used anywhere + you otherwise would normally specify + InspectConfig. See + https://cloud.google.com/dlp/docs/concepts-templates + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{name=organizations/*/inspectTemplates/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=organizations/*/locations/*/inspectTemplates/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/inspectTemplates/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/locations/*/inspectTemplates/*}", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_update_inspect_template( + request, metadata + ) + pb_request = dlp.UpdateInspectTemplateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.InspectTemplate() + pb_resp = dlp.InspectTemplate.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_inspect_template(resp) + return resp + + class _UpdateJobTrigger(DlpServiceRestStub): + def __hash__(self): + return hash("UpdateJobTrigger") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.UpdateJobTriggerRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.JobTrigger: + r"""Call the update job trigger method over HTTP. + + Args: + request (~.dlp.UpdateJobTriggerRequest): + The request object. Request message for UpdateJobTrigger. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.JobTrigger: + Contains a configuration to make dlp + api calls on a repeating basis. See + https://cloud.google.com/dlp/docs/concepts-job-triggers + to learn more. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{name=projects/*/jobTriggers/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/locations/*/jobTriggers/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=organizations/*/locations/*/jobTriggers/*}", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_update_job_trigger( + request, metadata + ) + pb_request = dlp.UpdateJobTriggerRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.JobTrigger() + pb_resp = dlp.JobTrigger.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_job_trigger(resp) + return resp + + class _UpdateStoredInfoType(DlpServiceRestStub): + def __hash__(self): + return hash("UpdateStoredInfoType") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: dlp.UpdateStoredInfoTypeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> dlp.StoredInfoType: + r"""Call the update stored info type method over HTTP. + + Args: + request (~.dlp.UpdateStoredInfoTypeRequest): + The request object. Request message for + UpdateStoredInfoType. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.dlp.StoredInfoType: + StoredInfoType resource message that + contains information about the current + version and any pending updates. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{name=organizations/*/storedInfoTypes/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=organizations/*/locations/*/storedInfoTypes/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/storedInfoTypes/*}", + "body": "*", + }, + { + "method": "patch", + "uri": "/v2/{name=projects/*/locations/*/storedInfoTypes/*}", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_update_stored_info_type( + request, metadata + ) + pb_request = dlp.UpdateStoredInfoTypeRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = dlp.StoredInfoType() + pb_resp = dlp.StoredInfoType.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_stored_info_type(resp) + return resp + + @property + def activate_job_trigger( + self, + ) -> Callable[[dlp.ActivateJobTriggerRequest], dlp.DlpJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ActivateJobTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel_dlp_job(self) -> Callable[[dlp.CancelDlpJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CancelDlpJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_deidentify_template( + self, + ) -> Callable[[dlp.CreateDeidentifyTemplateRequest], dlp.DeidentifyTemplate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDeidentifyTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_dlp_job(self) -> Callable[[dlp.CreateDlpJobRequest], dlp.DlpJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateDlpJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_inspect_template( + self, + ) -> Callable[[dlp.CreateInspectTemplateRequest], dlp.InspectTemplate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateInspectTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_job_trigger( + self, + ) -> Callable[[dlp.CreateJobTriggerRequest], dlp.JobTrigger]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateJobTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_stored_info_type( + self, + ) -> Callable[[dlp.CreateStoredInfoTypeRequest], dlp.StoredInfoType]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateStoredInfoType(self._session, self._host, self._interceptor) # type: ignore + + @property + def deidentify_content( + self, + ) -> Callable[[dlp.DeidentifyContentRequest], dlp.DeidentifyContentResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeidentifyContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_deidentify_template( + self, + ) -> Callable[[dlp.DeleteDeidentifyTemplateRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDeidentifyTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_dlp_job(self) -> Callable[[dlp.DeleteDlpJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteDlpJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_inspect_template( + self, + ) -> Callable[[dlp.DeleteInspectTemplateRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteInspectTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_job_trigger( + self, + ) -> Callable[[dlp.DeleteJobTriggerRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteJobTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_stored_info_type( + self, + ) -> Callable[[dlp.DeleteStoredInfoTypeRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteStoredInfoType(self._session, self._host, self._interceptor) # type: ignore + + @property + def finish_dlp_job(self) -> Callable[[dlp.FinishDlpJobRequest], empty_pb2.Empty]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FinishDlpJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_deidentify_template( + self, + ) -> Callable[[dlp.GetDeidentifyTemplateRequest], dlp.DeidentifyTemplate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDeidentifyTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_dlp_job(self) -> Callable[[dlp.GetDlpJobRequest], dlp.DlpJob]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetDlpJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_inspect_template( + self, + ) -> Callable[[dlp.GetInspectTemplateRequest], dlp.InspectTemplate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetInspectTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_job_trigger(self) -> Callable[[dlp.GetJobTriggerRequest], dlp.JobTrigger]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetJobTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_stored_info_type( + self, + ) -> Callable[[dlp.GetStoredInfoTypeRequest], dlp.StoredInfoType]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetStoredInfoType(self._session, self._host, self._interceptor) # type: ignore + + @property + def hybrid_inspect_dlp_job( + self, + ) -> Callable[[dlp.HybridInspectDlpJobRequest], dlp.HybridInspectResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._HybridInspectDlpJob(self._session, self._host, self._interceptor) # type: ignore + + @property + def hybrid_inspect_job_trigger( + self, + ) -> Callable[[dlp.HybridInspectJobTriggerRequest], dlp.HybridInspectResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._HybridInspectJobTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def inspect_content( + self, + ) -> Callable[[dlp.InspectContentRequest], dlp.InspectContentResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._InspectContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_deidentify_templates( + self, + ) -> Callable[ + [dlp.ListDeidentifyTemplatesRequest], dlp.ListDeidentifyTemplatesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDeidentifyTemplates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_dlp_jobs( + self, + ) -> Callable[[dlp.ListDlpJobsRequest], dlp.ListDlpJobsResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListDlpJobs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_info_types( + self, + ) -> Callable[[dlp.ListInfoTypesRequest], dlp.ListInfoTypesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInfoTypes(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_inspect_templates( + self, + ) -> Callable[[dlp.ListInspectTemplatesRequest], dlp.ListInspectTemplatesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListInspectTemplates(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_job_triggers( + self, + ) -> Callable[[dlp.ListJobTriggersRequest], dlp.ListJobTriggersResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListJobTriggers(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_stored_info_types( + self, + ) -> Callable[[dlp.ListStoredInfoTypesRequest], dlp.ListStoredInfoTypesResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListStoredInfoTypes(self._session, self._host, self._interceptor) # type: ignore + + @property + def redact_image( + self, + ) -> Callable[[dlp.RedactImageRequest], dlp.RedactImageResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RedactImage(self._session, self._host, self._interceptor) # type: ignore + + @property + def reidentify_content( + self, + ) -> Callable[[dlp.ReidentifyContentRequest], dlp.ReidentifyContentResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ReidentifyContent(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_deidentify_template( + self, + ) -> Callable[[dlp.UpdateDeidentifyTemplateRequest], dlp.DeidentifyTemplate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateDeidentifyTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_inspect_template( + self, + ) -> Callable[[dlp.UpdateInspectTemplateRequest], dlp.InspectTemplate]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateInspectTemplate(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_job_trigger( + self, + ) -> Callable[[dlp.UpdateJobTriggerRequest], dlp.JobTrigger]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateJobTrigger(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_stored_info_type( + self, + ) -> Callable[[dlp.UpdateStoredInfoTypeRequest], dlp.StoredInfoType]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateStoredInfoType(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("DlpServiceRestTransport",) diff --git a/google/cloud/dlp_v2/types/dlp.py b/google/cloud/dlp_v2/types/dlp.py index 0a85ce76..ebf542ec 100644 --- a/google/cloud/dlp_v2/types/dlp.py +++ b/google/cloud/dlp_v2/types/dlp.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import duration_pb2 # type: ignore diff --git a/google/cloud/dlp_v2/types/storage.py b/google/cloud/dlp_v2/types/storage.py index e0517089..1d8ac35d 100644 --- a/google/cloud/dlp_v2/types/storage.py +++ b/google/cloud/dlp_v2/types/storage.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from __future__ import annotations + from typing import MutableMapping, MutableSequence from google.protobuf import timestamp_pb2 # type: ignore diff --git a/tests/unit/gapic/dlp_v2/test_dlp_service.py b/tests/unit/gapic/dlp_v2/test_dlp_service.py index 834c65e8..062e0fe9 100644 --- a/tests/unit/gapic/dlp_v2/test_dlp_service.py +++ b/tests/unit/gapic/dlp_v2/test_dlp_service.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -30,11 +32,13 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.type import date_pb2 # type: ignore @@ -45,6 +49,8 @@ from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.dlp_v2.services.dlp_service import ( DlpServiceAsyncClient, @@ -101,6 +107,7 @@ def test__get_default_mtls_endpoint(): [ (DlpServiceClient, "grpc"), (DlpServiceAsyncClient, "grpc_asyncio"), + (DlpServiceClient, "rest"), ], ) def test_dlp_service_client_from_service_account_info(client_class, transport_name): @@ -114,7 +121,11 @@ def test_dlp_service_client_from_service_account_info(client_class, transport_na assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("dlp.googleapis.com:443") + assert client.transport._host == ( + "dlp.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dlp.googleapis.com" + ) @pytest.mark.parametrize( @@ -122,6 +133,7 @@ def test_dlp_service_client_from_service_account_info(client_class, transport_na [ (transports.DlpServiceGrpcTransport, "grpc"), (transports.DlpServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.DlpServiceRestTransport, "rest"), ], ) def test_dlp_service_client_service_account_always_use_jwt( @@ -147,6 +159,7 @@ def test_dlp_service_client_service_account_always_use_jwt( [ (DlpServiceClient, "grpc"), (DlpServiceAsyncClient, "grpc_asyncio"), + (DlpServiceClient, "rest"), ], ) def test_dlp_service_client_from_service_account_file(client_class, transport_name): @@ -167,13 +180,18 @@ def test_dlp_service_client_from_service_account_file(client_class, transport_na assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("dlp.googleapis.com:443") + assert client.transport._host == ( + "dlp.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dlp.googleapis.com" + ) def test_dlp_service_client_get_transport_class(): transport = DlpServiceClient.get_transport_class() available_transports = [ transports.DlpServiceGrpcTransport, + transports.DlpServiceRestTransport, ] assert transport in available_transports @@ -190,6 +208,7 @@ def test_dlp_service_client_get_transport_class(): transports.DlpServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (DlpServiceClient, transports.DlpServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -333,6 +352,8 @@ def test_dlp_service_client_client_options( "grpc_asyncio", "false", ), + (DlpServiceClient, transports.DlpServiceRestTransport, "rest", "true"), + (DlpServiceClient, transports.DlpServiceRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -526,6 +547,7 @@ def test_dlp_service_client_get_mtls_endpoint_and_cert_source(client_class): transports.DlpServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (DlpServiceClient, transports.DlpServiceRestTransport, "rest"), ], ) def test_dlp_service_client_client_options_scopes( @@ -561,6 +583,7 @@ def test_dlp_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (DlpServiceClient, transports.DlpServiceRestTransport, "rest", None), ], ) def test_dlp_service_client_client_options_credentials_file( @@ -9409,161 +9432,8879 @@ async def test_finish_dlp_job_field_headers_async(): ) in kw["metadata"] -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.DlpServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + dlp.InspectContentRequest, + dict, + ], +) +def test_inspect_content_rest(request_type): + client = DlpServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = DlpServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.DlpServiceGrpcTransport( + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.InspectContentResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.InspectContentResponse.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.inspect_content(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.InspectContentResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_inspect_content_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = DlpServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_inspect_content" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_inspect_content" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.InspectContentRequest.pb(dlp.InspectContentRequest()) + 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 = dlp.InspectContentResponse.to_json( + dlp.InspectContentResponse() ) - # It is an error to provide an api_key and a transport instance. - transport = transports.DlpServiceGrpcTransport( + request = dlp.InspectContentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.InspectContentResponse() + + client.inspect_content( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_inspect_content_rest_bad_request( + transport: str = "rest", request_type=dlp.InspectContentRequest +): + client = DlpServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = DlpServiceClient( - 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 = DlpServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) - # It is an error to provide scopes and a transport instance. - transport = transports.DlpServiceGrpcTransport( + # 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.inspect_content(request) + + +def test_inspect_content_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.RedactImageRequest, + dict, + ], +) +def test_redact_image_rest(request_type): + client = DlpServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = DlpServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.RedactImageResponse( + redacted_image=b"redacted_image_blob", + extracted_text="extracted_text_value", ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.RedactImageResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.DlpServiceGrpcTransport( + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.redact_image(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.RedactImageResponse) + assert response.redacted_image == b"redacted_image_blob" + assert response.extracted_text == "extracted_text_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_redact_image_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), ) client = DlpServiceClient(transport=transport) - assert client.transport is transport + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.DlpServiceRestInterceptor, "post_redact_image" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_redact_image" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.RedactImageRequest.pb(dlp.RedactImageRequest()) + 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 = dlp.RedactImageResponse.to_json( + dlp.RedactImageResponse() + ) + request = dlp.RedactImageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.RedactImageResponse() + + client.redact_image( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.DlpServiceGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_redact_image_rest_bad_request( + transport: str = "rest", request_type=dlp.RedactImageRequest +): + client = DlpServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.DlpServiceGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.redact_image(request) + + +def test_redact_image_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - channel = transport.grpc_channel - assert channel @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.DlpServiceGrpcTransport, - transports.DlpServiceGrpcAsyncIOTransport, + dlp.DeidentifyContentRequest, + dict, ], ) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() +def test_deidentify_content_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.DeidentifyContentResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DeidentifyContentResponse.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.deidentify_content(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DeidentifyContentResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_deidentify_content_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_deidentify_content" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_deidentify_content" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.DeidentifyContentRequest.pb(dlp.DeidentifyContentRequest()) + 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 = dlp.DeidentifyContentResponse.to_json( + dlp.DeidentifyContentResponse() + ) + + request = dlp.DeidentifyContentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DeidentifyContentResponse() + + client.deidentify_content( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_deidentify_content_rest_bad_request( + transport: str = "rest", request_type=dlp.DeidentifyContentRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.deidentify_content(request) + + +def test_deidentify_content_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + dlp.ReidentifyContentRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = DlpServiceClient.get_transport_class(transport_name)( +def test_reidentify_content_rest(request_type): + client = DlpServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.ReidentifyContentResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ReidentifyContentResponse.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.reidentify_content(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.ReidentifyContentResponse) + + +def test_reidentify_content_rest_required_fields( + request_type=dlp.ReidentifyContentRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).reidentify_content._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() + ).reidentify_content._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = DlpServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.DlpServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.ReidentifyContentResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.ReidentifyContentResponse.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.reidentify_content(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_reidentify_content_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.reidentify_content._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) -def test_dlp_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.DlpServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reidentify_content_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_reidentify_content" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_reidentify_content" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ReidentifyContentRequest.pb(dlp.ReidentifyContentRequest()) + 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 = dlp.ReidentifyContentResponse.to_json( + dlp.ReidentifyContentResponse() + ) -def test_dlp_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.dlp_v2.services.dlp_service.transports.DlpServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.DlpServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + request = dlp.ReidentifyContentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ReidentifyContentResponse() + + client.reidentify_content( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "inspect_content", - "redact_image", - "deidentify_content", - "reidentify_content", - "list_info_types", - "create_inspect_template", - "update_inspect_template", - "get_inspect_template", - "list_inspect_templates", - "delete_inspect_template", - "create_deidentify_template", - "update_deidentify_template", - "get_deidentify_template", - "list_deidentify_templates", - "delete_deidentify_template", - "create_job_trigger", - "update_job_trigger", - "hybrid_inspect_job_trigger", + pre.assert_called_once() + post.assert_called_once() + + +def test_reidentify_content_rest_bad_request( + transport: str = "rest", request_type=dlp.ReidentifyContentRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.reidentify_content(request) + + +def test_reidentify_content_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ListInfoTypesRequest, + dict, + ], +) +def test_list_info_types_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = dlp.ListInfoTypesResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ListInfoTypesResponse.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_info_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.ListInfoTypesResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_info_types_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_list_info_types" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_list_info_types" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ListInfoTypesRequest.pb(dlp.ListInfoTypesRequest()) + 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 = dlp.ListInfoTypesResponse.to_json( + dlp.ListInfoTypesResponse() + ) + + request = dlp.ListInfoTypesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ListInfoTypesResponse() + + client.list_info_types( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_info_types_rest_bad_request( + transport: str = "rest", request_type=dlp.ListInfoTypesRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_info_types(request) + + +def test_list_info_types_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.ListInfoTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # 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 = dlp.ListInfoTypesResponse.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_info_types(**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/v2/infoTypes" % client.transport._host, args[1] + ) + + +def test_list_info_types_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_info_types( + dlp.ListInfoTypesRequest(), + parent="parent_value", + ) + + +def test_list_info_types_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.CreateInspectTemplateRequest, + dict, + ], +) +def test_create_inspect_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = dlp.InspectTemplate( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.InspectTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_inspect_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.InspectTemplate) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_inspect_template_rest_required_fields( + request_type=dlp.CreateInspectTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_inspect_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_inspect_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.InspectTemplate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.InspectTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_inspect_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_inspect_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_inspect_template._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "inspectTemplate", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_inspect_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_create_inspect_template" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_create_inspect_template" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.CreateInspectTemplateRequest.pb( + dlp.CreateInspectTemplateRequest() + ) + 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 = dlp.InspectTemplate.to_json(dlp.InspectTemplate()) + + request = dlp.CreateInspectTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.InspectTemplate() + + client.create_inspect_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_inspect_template_rest_bad_request( + transport: str = "rest", request_type=dlp.CreateInspectTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_inspect_template(request) + + +def test_create_inspect_template_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.InspectTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + inspect_template=dlp.InspectTemplate(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 = dlp.InspectTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_inspect_template(**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/v2/{parent=organizations/*}/inspectTemplates" % client.transport._host, + args[1], + ) + + +def test_create_inspect_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_inspect_template( + dlp.CreateInspectTemplateRequest(), + parent="parent_value", + inspect_template=dlp.InspectTemplate(name="name_value"), + ) + + +def test_create_inspect_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.UpdateInspectTemplateRequest, + dict, + ], +) +def test_update_inspect_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/inspectTemplates/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 = dlp.InspectTemplate( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.InspectTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_inspect_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.InspectTemplate) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_inspect_template_rest_required_fields( + request_type=dlp.UpdateInspectTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).update_inspect_template._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() + ).update_inspect_template._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.InspectTemplate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.InspectTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_inspect_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_inspect_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_inspect_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_inspect_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_update_inspect_template" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_update_inspect_template" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.UpdateInspectTemplateRequest.pb( + dlp.UpdateInspectTemplateRequest() + ) + 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 = dlp.InspectTemplate.to_json(dlp.InspectTemplate()) + + request = dlp.UpdateInspectTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.InspectTemplate() + + client.update_inspect_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_inspect_template_rest_bad_request( + transport: str = "rest", request_type=dlp.UpdateInspectTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/inspectTemplates/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_inspect_template(request) + + +def test_update_inspect_template_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.InspectTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/inspectTemplates/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + inspect_template=dlp.InspectTemplate(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 + pb_return_value = dlp.InspectTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_inspect_template(**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/v2/{name=organizations/*/inspectTemplates/*}" % client.transport._host, + args[1], + ) + + +def test_update_inspect_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_inspect_template( + dlp.UpdateInspectTemplateRequest(), + name="name_value", + inspect_template=dlp.InspectTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_inspect_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.GetInspectTemplateRequest, + dict, + ], +) +def test_get_inspect_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/inspectTemplates/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 = dlp.InspectTemplate( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.InspectTemplate.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_inspect_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.InspectTemplate) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_inspect_template_rest_required_fields( + request_type=dlp.GetInspectTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_inspect_template._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_inspect_template._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.InspectTemplate() + # 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 = dlp.InspectTemplate.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_inspect_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_inspect_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_inspect_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_inspect_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_get_inspect_template" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_get_inspect_template" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.GetInspectTemplateRequest.pb(dlp.GetInspectTemplateRequest()) + 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 = dlp.InspectTemplate.to_json(dlp.InspectTemplate()) + + request = dlp.GetInspectTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.InspectTemplate() + + client.get_inspect_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_inspect_template_rest_bad_request( + transport: str = "rest", request_type=dlp.GetInspectTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/inspectTemplates/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_inspect_template(request) + + +def test_get_inspect_template_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.InspectTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/inspectTemplates/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.InspectTemplate.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_inspect_template(**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/v2/{name=organizations/*/inspectTemplates/*}" % client.transport._host, + args[1], + ) + + +def test_get_inspect_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_inspect_template( + dlp.GetInspectTemplateRequest(), + name="name_value", + ) + + +def test_get_inspect_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ListInspectTemplatesRequest, + dict, + ], +) +def test_list_inspect_templates_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = dlp.ListInspectTemplatesResponse( + 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 = dlp.ListInspectTemplatesResponse.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_inspect_templates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInspectTemplatesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_inspect_templates_rest_required_fields( + request_type=dlp.ListInspectTemplatesRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_inspect_templates._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_inspect_templates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "location_id", + "order_by", + "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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.ListInspectTemplatesResponse() + # 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 = dlp.ListInspectTemplatesResponse.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_inspect_templates(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_inspect_templates_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_inspect_templates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "locationId", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_inspect_templates_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_list_inspect_templates" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_list_inspect_templates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ListInspectTemplatesRequest.pb( + dlp.ListInspectTemplatesRequest() + ) + 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 = dlp.ListInspectTemplatesResponse.to_json( + dlp.ListInspectTemplatesResponse() + ) + + request = dlp.ListInspectTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ListInspectTemplatesResponse() + + client.list_inspect_templates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_inspect_templates_rest_bad_request( + transport: str = "rest", request_type=dlp.ListInspectTemplatesRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_inspect_templates(request) + + +def test_list_inspect_templates_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.ListInspectTemplatesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ListInspectTemplatesResponse.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_inspect_templates(**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/v2/{parent=organizations/*}/inspectTemplates" % client.transport._host, + args[1], + ) + + +def test_list_inspect_templates_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_inspect_templates( + dlp.ListInspectTemplatesRequest(), + parent="parent_value", + ) + + +def test_list_inspect_templates_rest_pager(transport: str = "rest"): + client = DlpServiceClient( + 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 = ( + dlp.ListInspectTemplatesResponse( + inspect_templates=[ + dlp.InspectTemplate(), + dlp.InspectTemplate(), + dlp.InspectTemplate(), + ], + next_page_token="abc", + ), + dlp.ListInspectTemplatesResponse( + inspect_templates=[], + next_page_token="def", + ), + dlp.ListInspectTemplatesResponse( + inspect_templates=[ + dlp.InspectTemplate(), + ], + next_page_token="ghi", + ), + dlp.ListInspectTemplatesResponse( + inspect_templates=[ + dlp.InspectTemplate(), + dlp.InspectTemplate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dlp.ListInspectTemplatesResponse.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": "organizations/sample1"} + + pager = client.list_inspect_templates(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dlp.InspectTemplate) for i in results) + + pages = list(client.list_inspect_templates(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", + [ + dlp.DeleteInspectTemplateRequest, + dict, + ], +) +def test_delete_inspect_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/inspectTemplates/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_inspect_template(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_inspect_template_rest_required_fields( + request_type=dlp.DeleteInspectTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_inspect_template._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_inspect_template._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_inspect_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_inspect_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_inspect_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_inspect_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_delete_inspect_template" + ) as pre: + pre.assert_not_called() + pb_message = dlp.DeleteInspectTemplateRequest.pb( + dlp.DeleteInspectTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.DeleteInspectTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_inspect_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_inspect_template_rest_bad_request( + transport: str = "rest", request_type=dlp.DeleteInspectTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/inspectTemplates/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_inspect_template(request) + + +def test_delete_inspect_template_rest_flattened(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/inspectTemplates/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_inspect_template(**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/v2/{name=organizations/*/inspectTemplates/*}" % client.transport._host, + args[1], + ) + + +def test_delete_inspect_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_inspect_template( + dlp.DeleteInspectTemplateRequest(), + name="name_value", + ) + + +def test_delete_inspect_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.CreateDeidentifyTemplateRequest, + dict, + ], +) +def test_create_deidentify_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = dlp.DeidentifyTemplate( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DeidentifyTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_deidentify_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DeidentifyTemplate) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_create_deidentify_template_rest_required_fields( + request_type=dlp.CreateDeidentifyTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_deidentify_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_deidentify_template._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.DeidentifyTemplate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.DeidentifyTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_deidentify_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_deidentify_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_deidentify_template._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "deidentifyTemplate", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_deidentify_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_create_deidentify_template" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_create_deidentify_template" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.CreateDeidentifyTemplateRequest.pb( + dlp.CreateDeidentifyTemplateRequest() + ) + 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 = dlp.DeidentifyTemplate.to_json( + dlp.DeidentifyTemplate() + ) + + request = dlp.CreateDeidentifyTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DeidentifyTemplate() + + client.create_deidentify_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_deidentify_template_rest_bad_request( + transport: str = "rest", request_type=dlp.CreateDeidentifyTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_deidentify_template(request) + + +def test_create_deidentify_template_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.DeidentifyTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + deidentify_template=dlp.DeidentifyTemplate(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 = dlp.DeidentifyTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_deidentify_template(**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/v2/{parent=organizations/*}/deidentifyTemplates" + % client.transport._host, + args[1], + ) + + +def test_create_deidentify_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_deidentify_template( + dlp.CreateDeidentifyTemplateRequest(), + parent="parent_value", + deidentify_template=dlp.DeidentifyTemplate(name="name_value"), + ) + + +def test_create_deidentify_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.UpdateDeidentifyTemplateRequest, + dict, + ], +) +def test_update_deidentify_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/deidentifyTemplates/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 = dlp.DeidentifyTemplate( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DeidentifyTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_deidentify_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DeidentifyTemplate) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_update_deidentify_template_rest_required_fields( + request_type=dlp.UpdateDeidentifyTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).update_deidentify_template._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() + ).update_deidentify_template._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.DeidentifyTemplate() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.DeidentifyTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_deidentify_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_deidentify_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_deidentify_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_deidentify_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_update_deidentify_template" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_update_deidentify_template" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.UpdateDeidentifyTemplateRequest.pb( + dlp.UpdateDeidentifyTemplateRequest() + ) + 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 = dlp.DeidentifyTemplate.to_json( + dlp.DeidentifyTemplate() + ) + + request = dlp.UpdateDeidentifyTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DeidentifyTemplate() + + client.update_deidentify_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_deidentify_template_rest_bad_request( + transport: str = "rest", request_type=dlp.UpdateDeidentifyTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/deidentifyTemplates/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_deidentify_template(request) + + +def test_update_deidentify_template_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.DeidentifyTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/deidentifyTemplates/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + deidentify_template=dlp.DeidentifyTemplate(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 + pb_return_value = dlp.DeidentifyTemplate.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_deidentify_template(**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/v2/{name=organizations/*/deidentifyTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_update_deidentify_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_deidentify_template( + dlp.UpdateDeidentifyTemplateRequest(), + name="name_value", + deidentify_template=dlp.DeidentifyTemplate(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_deidentify_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.GetDeidentifyTemplateRequest, + dict, + ], +) +def test_get_deidentify_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/deidentifyTemplates/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 = dlp.DeidentifyTemplate( + name="name_value", + display_name="display_name_value", + description="description_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DeidentifyTemplate.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_deidentify_template(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DeidentifyTemplate) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + + +def test_get_deidentify_template_rest_required_fields( + request_type=dlp.GetDeidentifyTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_deidentify_template._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_deidentify_template._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.DeidentifyTemplate() + # 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 = dlp.DeidentifyTemplate.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_deidentify_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_deidentify_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_deidentify_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_deidentify_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_get_deidentify_template" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_get_deidentify_template" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.GetDeidentifyTemplateRequest.pb( + dlp.GetDeidentifyTemplateRequest() + ) + 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 = dlp.DeidentifyTemplate.to_json( + dlp.DeidentifyTemplate() + ) + + request = dlp.GetDeidentifyTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DeidentifyTemplate() + + client.get_deidentify_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_deidentify_template_rest_bad_request( + transport: str = "rest", request_type=dlp.GetDeidentifyTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/deidentifyTemplates/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_deidentify_template(request) + + +def test_get_deidentify_template_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.DeidentifyTemplate() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/deidentifyTemplates/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DeidentifyTemplate.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_deidentify_template(**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/v2/{name=organizations/*/deidentifyTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_get_deidentify_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_deidentify_template( + dlp.GetDeidentifyTemplateRequest(), + name="name_value", + ) + + +def test_get_deidentify_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ListDeidentifyTemplatesRequest, + dict, + ], +) +def test_list_deidentify_templates_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = dlp.ListDeidentifyTemplatesResponse( + 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 = dlp.ListDeidentifyTemplatesResponse.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_deidentify_templates(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDeidentifyTemplatesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_deidentify_templates_rest_required_fields( + request_type=dlp.ListDeidentifyTemplatesRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_deidentify_templates._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_deidentify_templates._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "location_id", + "order_by", + "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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.ListDeidentifyTemplatesResponse() + # 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 = dlp.ListDeidentifyTemplatesResponse.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_deidentify_templates(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_deidentify_templates_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_deidentify_templates._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "locationId", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_deidentify_templates_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_list_deidentify_templates" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_list_deidentify_templates" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ListDeidentifyTemplatesRequest.pb( + dlp.ListDeidentifyTemplatesRequest() + ) + 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 = dlp.ListDeidentifyTemplatesResponse.to_json( + dlp.ListDeidentifyTemplatesResponse() + ) + + request = dlp.ListDeidentifyTemplatesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ListDeidentifyTemplatesResponse() + + client.list_deidentify_templates( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_deidentify_templates_rest_bad_request( + transport: str = "rest", request_type=dlp.ListDeidentifyTemplatesRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_deidentify_templates(request) + + +def test_list_deidentify_templates_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.ListDeidentifyTemplatesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ListDeidentifyTemplatesResponse.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_deidentify_templates(**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/v2/{parent=organizations/*}/deidentifyTemplates" + % client.transport._host, + args[1], + ) + + +def test_list_deidentify_templates_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_deidentify_templates( + dlp.ListDeidentifyTemplatesRequest(), + parent="parent_value", + ) + + +def test_list_deidentify_templates_rest_pager(transport: str = "rest"): + client = DlpServiceClient( + 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 = ( + dlp.ListDeidentifyTemplatesResponse( + deidentify_templates=[ + dlp.DeidentifyTemplate(), + dlp.DeidentifyTemplate(), + dlp.DeidentifyTemplate(), + ], + next_page_token="abc", + ), + dlp.ListDeidentifyTemplatesResponse( + deidentify_templates=[], + next_page_token="def", + ), + dlp.ListDeidentifyTemplatesResponse( + deidentify_templates=[ + dlp.DeidentifyTemplate(), + ], + next_page_token="ghi", + ), + dlp.ListDeidentifyTemplatesResponse( + deidentify_templates=[ + dlp.DeidentifyTemplate(), + dlp.DeidentifyTemplate(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + dlp.ListDeidentifyTemplatesResponse.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": "organizations/sample1"} + + pager = client.list_deidentify_templates(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dlp.DeidentifyTemplate) for i in results) + + pages = list(client.list_deidentify_templates(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", + [ + dlp.DeleteDeidentifyTemplateRequest, + dict, + ], +) +def test_delete_deidentify_template_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/deidentifyTemplates/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_deidentify_template(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_deidentify_template_rest_required_fields( + request_type=dlp.DeleteDeidentifyTemplateRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_deidentify_template._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_deidentify_template._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_deidentify_template(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_deidentify_template_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_deidentify_template._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_deidentify_template_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_delete_deidentify_template" + ) as pre: + pre.assert_not_called() + pb_message = dlp.DeleteDeidentifyTemplateRequest.pb( + dlp.DeleteDeidentifyTemplateRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.DeleteDeidentifyTemplateRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_deidentify_template( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_deidentify_template_rest_bad_request( + transport: str = "rest", request_type=dlp.DeleteDeidentifyTemplateRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/deidentifyTemplates/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_deidentify_template(request) + + +def test_delete_deidentify_template_rest_flattened(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/deidentifyTemplates/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_deidentify_template(**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/v2/{name=organizations/*/deidentifyTemplates/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_deidentify_template_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_deidentify_template( + dlp.DeleteDeidentifyTemplateRequest(), + name="name_value", + ) + + +def test_delete_deidentify_template_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.CreateJobTriggerRequest, + dict, + ], +) +def test_create_job_trigger_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.JobTrigger( + name="name_value", + display_name="display_name_value", + description="description_value", + status=dlp.JobTrigger.Status.HEALTHY, + inspect_job=dlp.InspectJobConfig( + storage_config=storage.StorageConfig( + datastore_options=storage.DatastoreOptions( + partition_id=storage.PartitionId(project_id="project_id_value") + ) + ) + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.JobTrigger.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_job_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.JobTrigger) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.status == dlp.JobTrigger.Status.HEALTHY + + +def test_create_job_trigger_rest_required_fields( + request_type=dlp.CreateJobTriggerRequest, +): + transport_class = transports.DlpServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_job_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_job_trigger._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.JobTrigger() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.JobTrigger.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_job_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_job_trigger_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_job_trigger._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "jobTrigger", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_job_trigger_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_create_job_trigger" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_create_job_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.CreateJobTriggerRequest.pb(dlp.CreateJobTriggerRequest()) + 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 = dlp.JobTrigger.to_json(dlp.JobTrigger()) + + request = dlp.CreateJobTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.JobTrigger() + + client.create_job_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_job_trigger_rest_bad_request( + transport: str = "rest", request_type=dlp.CreateJobTriggerRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_job_trigger(request) + + +def test_create_job_trigger_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.JobTrigger() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + job_trigger=dlp.JobTrigger(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 = dlp.JobTrigger.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_job_trigger(**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/v2/{parent=projects/*}/jobTriggers" % client.transport._host, args[1] + ) + + +def test_create_job_trigger_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_job_trigger( + dlp.CreateJobTriggerRequest(), + parent="parent_value", + job_trigger=dlp.JobTrigger(name="name_value"), + ) + + +def test_create_job_trigger_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.UpdateJobTriggerRequest, + dict, + ], +) +def test_update_job_trigger_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/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 = dlp.JobTrigger( + name="name_value", + display_name="display_name_value", + description="description_value", + status=dlp.JobTrigger.Status.HEALTHY, + inspect_job=dlp.InspectJobConfig( + storage_config=storage.StorageConfig( + datastore_options=storage.DatastoreOptions( + partition_id=storage.PartitionId(project_id="project_id_value") + ) + ) + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.JobTrigger.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_job_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.JobTrigger) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.status == dlp.JobTrigger.Status.HEALTHY + + +def test_update_job_trigger_rest_required_fields( + request_type=dlp.UpdateJobTriggerRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).update_job_trigger._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() + ).update_job_trigger._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.JobTrigger() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.JobTrigger.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_job_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_job_trigger_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_job_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_job_trigger_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_update_job_trigger" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_update_job_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.UpdateJobTriggerRequest.pb(dlp.UpdateJobTriggerRequest()) + 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 = dlp.JobTrigger.to_json(dlp.JobTrigger()) + + request = dlp.UpdateJobTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.JobTrigger() + + client.update_job_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_job_trigger_rest_bad_request( + transport: str = "rest", request_type=dlp.UpdateJobTriggerRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_job_trigger(request) + + +def test_update_job_trigger_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.JobTrigger() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/jobTriggers/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + job_trigger=dlp.JobTrigger(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 + pb_return_value = dlp.JobTrigger.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_job_trigger(**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/v2/{name=projects/*/jobTriggers/*}" % client.transport._host, args[1] + ) + + +def test_update_job_trigger_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_job_trigger( + dlp.UpdateJobTriggerRequest(), + name="name_value", + job_trigger=dlp.JobTrigger(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_job_trigger_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.HybridInspectJobTriggerRequest, + dict, + ], +) +def test_hybrid_inspect_job_trigger_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobTriggers/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 = dlp.HybridInspectResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.HybridInspectResponse.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.hybrid_inspect_job_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.HybridInspectResponse) + + +def test_hybrid_inspect_job_trigger_rest_required_fields( + request_type=dlp.HybridInspectJobTriggerRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).hybrid_inspect_job_trigger._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() + ).hybrid_inspect_job_trigger._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.HybridInspectResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.HybridInspectResponse.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.hybrid_inspect_job_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_hybrid_inspect_job_trigger_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.hybrid_inspect_job_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_hybrid_inspect_job_trigger_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_hybrid_inspect_job_trigger" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_hybrid_inspect_job_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.HybridInspectJobTriggerRequest.pb( + dlp.HybridInspectJobTriggerRequest() + ) + 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 = dlp.HybridInspectResponse.to_json( + dlp.HybridInspectResponse() + ) + + request = dlp.HybridInspectJobTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.HybridInspectResponse() + + client.hybrid_inspect_job_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_hybrid_inspect_job_trigger_rest_bad_request( + transport: str = "rest", request_type=dlp.HybridInspectJobTriggerRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/jobTriggers/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.hybrid_inspect_job_trigger(request) + + +def test_hybrid_inspect_job_trigger_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.HybridInspectResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/jobTriggers/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 = dlp.HybridInspectResponse.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.hybrid_inspect_job_trigger(**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/v2/{name=projects/*/locations/*/jobTriggers/*}:hybridInspect" + % client.transport._host, + args[1], + ) + + +def test_hybrid_inspect_job_trigger_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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.hybrid_inspect_job_trigger( + dlp.HybridInspectJobTriggerRequest(), + name="name_value", + ) + + +def test_hybrid_inspect_job_trigger_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.GetJobTriggerRequest, + dict, + ], +) +def test_get_job_trigger_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/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 = dlp.JobTrigger( + name="name_value", + display_name="display_name_value", + description="description_value", + status=dlp.JobTrigger.Status.HEALTHY, + inspect_job=dlp.InspectJobConfig( + storage_config=storage.StorageConfig( + datastore_options=storage.DatastoreOptions( + partition_id=storage.PartitionId(project_id="project_id_value") + ) + ) + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.JobTrigger.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_job_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.JobTrigger) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.description == "description_value" + assert response.status == dlp.JobTrigger.Status.HEALTHY + + +def test_get_job_trigger_rest_required_fields(request_type=dlp.GetJobTriggerRequest): + transport_class = transports.DlpServiceRestTransport + + 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_job_trigger._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_job_trigger._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.JobTrigger() + # 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 = dlp.JobTrigger.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_job_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_job_trigger_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_job_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_job_trigger_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_get_job_trigger" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_get_job_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.GetJobTriggerRequest.pb(dlp.GetJobTriggerRequest()) + 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 = dlp.JobTrigger.to_json(dlp.JobTrigger()) + + request = dlp.GetJobTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.JobTrigger() + + client.get_job_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_job_trigger_rest_bad_request( + transport: str = "rest", request_type=dlp.GetJobTriggerRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_job_trigger(request) + + +def test_get_job_trigger_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.JobTrigger() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/jobTriggers/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.JobTrigger.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_job_trigger(**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/v2/{name=projects/*/jobTriggers/*}" % client.transport._host, args[1] + ) + + +def test_get_job_trigger_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_job_trigger( + dlp.GetJobTriggerRequest(), + name="name_value", + ) + + +def test_get_job_trigger_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ListJobTriggersRequest, + dict, + ], +) +def test_list_job_triggers_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.ListJobTriggersResponse( + 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 = dlp.ListJobTriggersResponse.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_job_triggers(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListJobTriggersPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_job_triggers_rest_required_fields( + request_type=dlp.ListJobTriggersRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_job_triggers._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_job_triggers._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "location_id", + "order_by", + "page_size", + "page_token", + "type_", + ) + ) + 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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.ListJobTriggersResponse() + # 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 = dlp.ListJobTriggersResponse.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_job_triggers(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_job_triggers_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_job_triggers._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "locationId", + "orderBy", + "pageSize", + "pageToken", + "type", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_job_triggers_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_list_job_triggers" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_list_job_triggers" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ListJobTriggersRequest.pb(dlp.ListJobTriggersRequest()) + 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 = dlp.ListJobTriggersResponse.to_json( + dlp.ListJobTriggersResponse() + ) + + request = dlp.ListJobTriggersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ListJobTriggersResponse() + + client.list_job_triggers( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_job_triggers_rest_bad_request( + transport: str = "rest", request_type=dlp.ListJobTriggersRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_job_triggers(request) + + +def test_list_job_triggers_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.ListJobTriggersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ListJobTriggersResponse.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_job_triggers(**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/v2/{parent=projects/*}/jobTriggers" % client.transport._host, args[1] + ) + + +def test_list_job_triggers_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_job_triggers( + dlp.ListJobTriggersRequest(), + parent="parent_value", + ) + + +def test_list_job_triggers_rest_pager(transport: str = "rest"): + client = DlpServiceClient( + 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 = ( + dlp.ListJobTriggersResponse( + job_triggers=[ + dlp.JobTrigger(), + dlp.JobTrigger(), + dlp.JobTrigger(), + ], + next_page_token="abc", + ), + dlp.ListJobTriggersResponse( + job_triggers=[], + next_page_token="def", + ), + dlp.ListJobTriggersResponse( + job_triggers=[ + dlp.JobTrigger(), + ], + next_page_token="ghi", + ), + dlp.ListJobTriggersResponse( + job_triggers=[ + dlp.JobTrigger(), + dlp.JobTrigger(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dlp.ListJobTriggersResponse.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"} + + pager = client.list_job_triggers(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dlp.JobTrigger) for i in results) + + pages = list(client.list_job_triggers(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", + [ + dlp.DeleteJobTriggerRequest, + dict, + ], +) +def test_delete_job_trigger_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_job_trigger(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_job_trigger_rest_required_fields( + request_type=dlp.DeleteJobTriggerRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_job_trigger._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_job_trigger._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_job_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_job_trigger_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_job_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_job_trigger_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_delete_job_trigger" + ) as pre: + pre.assert_not_called() + pb_message = dlp.DeleteJobTriggerRequest.pb(dlp.DeleteJobTriggerRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.DeleteJobTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_job_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_job_trigger_rest_bad_request( + transport: str = "rest", request_type=dlp.DeleteJobTriggerRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_job_trigger(request) + + +def test_delete_job_trigger_rest_flattened(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/jobTriggers/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_job_trigger(**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/v2/{name=projects/*/jobTriggers/*}" % client.transport._host, args[1] + ) + + +def test_delete_job_trigger_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_job_trigger( + dlp.DeleteJobTriggerRequest(), + name="name_value", + ) + + +def test_delete_job_trigger_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ActivateJobTriggerRequest, + dict, + ], +) +def test_activate_job_trigger_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/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 = dlp.DlpJob( + name="name_value", + type_=dlp.DlpJobType.INSPECT_JOB, + state=dlp.DlpJob.JobState.PENDING, + job_trigger_name="job_trigger_name_value", + risk_details=dlp.AnalyzeDataSourceRiskDetails( + requested_privacy_metric=dlp.PrivacyMetric( + numerical_stats_config=dlp.PrivacyMetric.NumericalStatsConfig( + field=storage.FieldId(name="name_value") + ) + ) + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DlpJob.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.activate_job_trigger(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DlpJob) + assert response.name == "name_value" + assert response.type_ == dlp.DlpJobType.INSPECT_JOB + assert response.state == dlp.DlpJob.JobState.PENDING + assert response.job_trigger_name == "job_trigger_name_value" + + +def test_activate_job_trigger_rest_required_fields( + request_type=dlp.ActivateJobTriggerRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).activate_job_trigger._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() + ).activate_job_trigger._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.DlpJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.DlpJob.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.activate_job_trigger(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_activate_job_trigger_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.activate_job_trigger._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_activate_job_trigger_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_activate_job_trigger" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_activate_job_trigger" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ActivateJobTriggerRequest.pb(dlp.ActivateJobTriggerRequest()) + 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 = dlp.DlpJob.to_json(dlp.DlpJob()) + + request = dlp.ActivateJobTriggerRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DlpJob() + + client.activate_job_trigger( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_activate_job_trigger_rest_bad_request( + transport: str = "rest", request_type=dlp.ActivateJobTriggerRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/jobTriggers/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.activate_job_trigger(request) + + +def test_activate_job_trigger_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.CreateDlpJobRequest, + dict, + ], +) +def test_create_dlp_job_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.DlpJob( + name="name_value", + type_=dlp.DlpJobType.INSPECT_JOB, + state=dlp.DlpJob.JobState.PENDING, + job_trigger_name="job_trigger_name_value", + risk_details=dlp.AnalyzeDataSourceRiskDetails( + requested_privacy_metric=dlp.PrivacyMetric( + numerical_stats_config=dlp.PrivacyMetric.NumericalStatsConfig( + field=storage.FieldId(name="name_value") + ) + ) + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DlpJob.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_dlp_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DlpJob) + assert response.name == "name_value" + assert response.type_ == dlp.DlpJobType.INSPECT_JOB + assert response.state == dlp.DlpJob.JobState.PENDING + assert response.job_trigger_name == "job_trigger_name_value" + + +def test_create_dlp_job_rest_required_fields(request_type=dlp.CreateDlpJobRequest): + transport_class = transports.DlpServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dlp_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_dlp_job._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.DlpJob() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.DlpJob.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_dlp_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_dlp_job_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_dlp_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_dlp_job_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_create_dlp_job" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_create_dlp_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.CreateDlpJobRequest.pb(dlp.CreateDlpJobRequest()) + 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 = dlp.DlpJob.to_json(dlp.DlpJob()) + + request = dlp.CreateDlpJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DlpJob() + + client.create_dlp_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_dlp_job_rest_bad_request( + transport: str = "rest", request_type=dlp.CreateDlpJobRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_dlp_job(request) + + +def test_create_dlp_job_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.DlpJob() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DlpJob.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_dlp_job(**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/v2/{parent=projects/*}/dlpJobs" % client.transport._host, args[1] + ) + + +def test_create_dlp_job_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_dlp_job( + dlp.CreateDlpJobRequest(), + parent="parent_value", + inspect_job=dlp.InspectJobConfig( + storage_config=storage.StorageConfig( + datastore_options=storage.DatastoreOptions( + partition_id=storage.PartitionId(project_id="project_id_value") + ) + ) + ), + risk_job=dlp.RiskAnalysisJobConfig( + privacy_metric=dlp.PrivacyMetric( + numerical_stats_config=dlp.PrivacyMetric.NumericalStatsConfig( + field=storage.FieldId(name="name_value") + ) + ) + ), + ) + + +def test_create_dlp_job_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ListDlpJobsRequest, + dict, + ], +) +def test_list_dlp_jobs_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "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 = dlp.ListDlpJobsResponse( + 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 = dlp.ListDlpJobsResponse.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_dlp_jobs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDlpJobsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_dlp_jobs_rest_required_fields(request_type=dlp.ListDlpJobsRequest): + transport_class = transports.DlpServiceRestTransport + + 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_dlp_jobs._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_dlp_jobs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "location_id", + "order_by", + "page_size", + "page_token", + "type_", + ) + ) + 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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.ListDlpJobsResponse() + # 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 = dlp.ListDlpJobsResponse.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_dlp_jobs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_dlp_jobs_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_dlp_jobs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "locationId", + "orderBy", + "pageSize", + "pageToken", + "type", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_dlp_jobs_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_list_dlp_jobs" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_list_dlp_jobs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ListDlpJobsRequest.pb(dlp.ListDlpJobsRequest()) + 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 = dlp.ListDlpJobsResponse.to_json( + dlp.ListDlpJobsResponse() + ) + + request = dlp.ListDlpJobsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ListDlpJobsResponse() + + client.list_dlp_jobs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_dlp_jobs_rest_bad_request( + transport: str = "rest", request_type=dlp.ListDlpJobsRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_dlp_jobs(request) + + +def test_list_dlp_jobs_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.ListDlpJobsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ListDlpJobsResponse.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_dlp_jobs(**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/v2/{parent=projects/*}/dlpJobs" % client.transport._host, args[1] + ) + + +def test_list_dlp_jobs_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_dlp_jobs( + dlp.ListDlpJobsRequest(), + parent="parent_value", + ) + + +def test_list_dlp_jobs_rest_pager(transport: str = "rest"): + client = DlpServiceClient( + 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 = ( + dlp.ListDlpJobsResponse( + jobs=[ + dlp.DlpJob(), + dlp.DlpJob(), + dlp.DlpJob(), + ], + next_page_token="abc", + ), + dlp.ListDlpJobsResponse( + jobs=[], + next_page_token="def", + ), + dlp.ListDlpJobsResponse( + jobs=[ + dlp.DlpJob(), + ], + next_page_token="ghi", + ), + dlp.ListDlpJobsResponse( + jobs=[ + dlp.DlpJob(), + dlp.DlpJob(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dlp.ListDlpJobsResponse.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"} + + pager = client.list_dlp_jobs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dlp.DlpJob) for i in results) + + pages = list(client.list_dlp_jobs(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", + [ + dlp.GetDlpJobRequest, + dict, + ], +) +def test_get_dlp_job_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dlpJobs/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 = dlp.DlpJob( + name="name_value", + type_=dlp.DlpJobType.INSPECT_JOB, + state=dlp.DlpJob.JobState.PENDING, + job_trigger_name="job_trigger_name_value", + risk_details=dlp.AnalyzeDataSourceRiskDetails( + requested_privacy_metric=dlp.PrivacyMetric( + numerical_stats_config=dlp.PrivacyMetric.NumericalStatsConfig( + field=storage.FieldId(name="name_value") + ) + ) + ), + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DlpJob.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_dlp_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.DlpJob) + assert response.name == "name_value" + assert response.type_ == dlp.DlpJobType.INSPECT_JOB + assert response.state == dlp.DlpJob.JobState.PENDING + assert response.job_trigger_name == "job_trigger_name_value" + + +def test_get_dlp_job_rest_required_fields(request_type=dlp.GetDlpJobRequest): + transport_class = transports.DlpServiceRestTransport + + 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_dlp_job._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_dlp_job._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.DlpJob() + # 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 = dlp.DlpJob.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_dlp_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_dlp_job_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_dlp_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_dlp_job_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_get_dlp_job" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_get_dlp_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.GetDlpJobRequest.pb(dlp.GetDlpJobRequest()) + 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 = dlp.DlpJob.to_json(dlp.DlpJob()) + + request = dlp.GetDlpJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.DlpJob() + + client.get_dlp_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_dlp_job_rest_bad_request( + transport: str = "rest", request_type=dlp.GetDlpJobRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dlpJobs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_dlp_job(request) + + +def test_get_dlp_job_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.DlpJob() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/dlpJobs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.DlpJob.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_dlp_job(**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/v2/{name=projects/*/dlpJobs/*}" % client.transport._host, args[1] + ) + + +def test_get_dlp_job_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_dlp_job( + dlp.GetDlpJobRequest(), + name="name_value", + ) + + +def test_get_dlp_job_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.DeleteDlpJobRequest, + dict, + ], +) +def test_delete_dlp_job_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dlpJobs/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_dlp_job(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_dlp_job_rest_required_fields(request_type=dlp.DeleteDlpJobRequest): + transport_class = transports.DlpServiceRestTransport + + 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_dlp_job._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_dlp_job._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_dlp_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_dlp_job_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_dlp_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_dlp_job_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_delete_dlp_job" + ) as pre: + pre.assert_not_called() + pb_message = dlp.DeleteDlpJobRequest.pb(dlp.DeleteDlpJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.DeleteDlpJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_dlp_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_dlp_job_rest_bad_request( + transport: str = "rest", request_type=dlp.DeleteDlpJobRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dlpJobs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_dlp_job(request) + + +def test_delete_dlp_job_rest_flattened(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/dlpJobs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_dlp_job(**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/v2/{name=projects/*/dlpJobs/*}" % client.transport._host, args[1] + ) + + +def test_delete_dlp_job_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_dlp_job( + dlp.DeleteDlpJobRequest(), + name="name_value", + ) + + +def test_delete_dlp_job_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.CancelDlpJobRequest, + dict, + ], +) +def test_cancel_dlp_job_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dlpJobs/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.cancel_dlp_job(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_dlp_job_rest_required_fields(request_type=dlp.CancelDlpJobRequest): + transport_class = transports.DlpServiceRestTransport + + 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() + ).cancel_dlp_job._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() + ).cancel_dlp_job._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.cancel_dlp_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_cancel_dlp_job_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel_dlp_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_dlp_job_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_cancel_dlp_job" + ) as pre: + pre.assert_not_called() + pb_message = dlp.CancelDlpJobRequest.pb(dlp.CancelDlpJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.CancelDlpJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.cancel_dlp_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_cancel_dlp_job_rest_bad_request( + transport: str = "rest", request_type=dlp.CancelDlpJobRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/dlpJobs/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.cancel_dlp_job(request) + + +def test_cancel_dlp_job_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.CreateStoredInfoTypeRequest, + dict, + ], +) +def test_create_stored_info_type_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = dlp.StoredInfoType( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.StoredInfoType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_stored_info_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.StoredInfoType) + assert response.name == "name_value" + + +def test_create_stored_info_type_rest_required_fields( + request_type=dlp.CreateStoredInfoTypeRequest, +): + transport_class = transports.DlpServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_stored_info_type._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_stored_info_type._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.StoredInfoType() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.StoredInfoType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_stored_info_type(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_stored_info_type_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_stored_info_type._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "config", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_stored_info_type_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_create_stored_info_type" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_create_stored_info_type" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.CreateStoredInfoTypeRequest.pb( + dlp.CreateStoredInfoTypeRequest() + ) + 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 = dlp.StoredInfoType.to_json(dlp.StoredInfoType()) + + request = dlp.CreateStoredInfoTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.StoredInfoType() + + client.create_stored_info_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_stored_info_type_rest_bad_request( + transport: str = "rest", request_type=dlp.CreateStoredInfoTypeRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_stored_info_type(request) + + +def test_create_stored_info_type_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.StoredInfoType() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + config=dlp.StoredInfoTypeConfig(display_name="display_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 = dlp.StoredInfoType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_stored_info_type(**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/v2/{parent=organizations/*}/storedInfoTypes" % client.transport._host, + args[1], + ) + + +def test_create_stored_info_type_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_stored_info_type( + dlp.CreateStoredInfoTypeRequest(), + parent="parent_value", + config=dlp.StoredInfoTypeConfig(display_name="display_name_value"), + ) + + +def test_create_stored_info_type_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.UpdateStoredInfoTypeRequest, + dict, + ], +) +def test_update_stored_info_type_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/storedInfoTypes/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 = dlp.StoredInfoType( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.StoredInfoType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_stored_info_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.StoredInfoType) + assert response.name == "name_value" + + +def test_update_stored_info_type_rest_required_fields( + request_type=dlp.UpdateStoredInfoTypeRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).update_stored_info_type._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() + ).update_stored_info_type._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.StoredInfoType() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.StoredInfoType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_stored_info_type(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_stored_info_type_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_stored_info_type._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_stored_info_type_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_update_stored_info_type" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_update_stored_info_type" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.UpdateStoredInfoTypeRequest.pb( + dlp.UpdateStoredInfoTypeRequest() + ) + 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 = dlp.StoredInfoType.to_json(dlp.StoredInfoType()) + + request = dlp.UpdateStoredInfoTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.StoredInfoType() + + client.update_stored_info_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_stored_info_type_rest_bad_request( + transport: str = "rest", request_type=dlp.UpdateStoredInfoTypeRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/storedInfoTypes/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_stored_info_type(request) + + +def test_update_stored_info_type_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.StoredInfoType() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/storedInfoTypes/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + config=dlp.StoredInfoTypeConfig(display_name="display_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 + pb_return_value = dlp.StoredInfoType.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_stored_info_type(**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/v2/{name=organizations/*/storedInfoTypes/*}" % client.transport._host, + args[1], + ) + + +def test_update_stored_info_type_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_stored_info_type( + dlp.UpdateStoredInfoTypeRequest(), + name="name_value", + config=dlp.StoredInfoTypeConfig(display_name="display_name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_stored_info_type_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.GetStoredInfoTypeRequest, + dict, + ], +) +def test_get_stored_info_type_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/storedInfoTypes/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 = dlp.StoredInfoType( + name="name_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.StoredInfoType.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_stored_info_type(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.StoredInfoType) + assert response.name == "name_value" + + +def test_get_stored_info_type_rest_required_fields( + request_type=dlp.GetStoredInfoTypeRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_stored_info_type._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_stored_info_type._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.StoredInfoType() + # 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 = dlp.StoredInfoType.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_stored_info_type(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_stored_info_type_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_stored_info_type._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_stored_info_type_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_get_stored_info_type" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_get_stored_info_type" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.GetStoredInfoTypeRequest.pb(dlp.GetStoredInfoTypeRequest()) + 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 = dlp.StoredInfoType.to_json(dlp.StoredInfoType()) + + request = dlp.GetStoredInfoTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.StoredInfoType() + + client.get_stored_info_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_stored_info_type_rest_bad_request( + transport: str = "rest", request_type=dlp.GetStoredInfoTypeRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/storedInfoTypes/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_stored_info_type(request) + + +def test_get_stored_info_type_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.StoredInfoType() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/storedInfoTypes/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.StoredInfoType.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_stored_info_type(**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/v2/{name=organizations/*/storedInfoTypes/*}" % client.transport._host, + args[1], + ) + + +def test_get_stored_info_type_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_stored_info_type( + dlp.GetStoredInfoTypeRequest(), + name="name_value", + ) + + +def test_get_stored_info_type_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.ListStoredInfoTypesRequest, + dict, + ], +) +def test_list_stored_info_types_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/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 = dlp.ListStoredInfoTypesResponse( + 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 = dlp.ListStoredInfoTypesResponse.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_stored_info_types(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListStoredInfoTypesPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_stored_info_types_rest_required_fields( + request_type=dlp.ListStoredInfoTypesRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_stored_info_types._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_stored_info_types._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "location_id", + "order_by", + "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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.ListStoredInfoTypesResponse() + # 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 = dlp.ListStoredInfoTypesResponse.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_stored_info_types(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_stored_info_types_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_stored_info_types._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "locationId", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_stored_info_types_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_list_stored_info_types" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_list_stored_info_types" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.ListStoredInfoTypesRequest.pb(dlp.ListStoredInfoTypesRequest()) + 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 = dlp.ListStoredInfoTypesResponse.to_json( + dlp.ListStoredInfoTypesResponse() + ) + + request = dlp.ListStoredInfoTypesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.ListStoredInfoTypesResponse() + + client.list_stored_info_types( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_stored_info_types_rest_bad_request( + transport: str = "rest", request_type=dlp.ListStoredInfoTypesRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_stored_info_types(request) + + +def test_list_stored_info_types_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.ListStoredInfoTypesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.ListStoredInfoTypesResponse.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_stored_info_types(**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/v2/{parent=organizations/*}/storedInfoTypes" % client.transport._host, + args[1], + ) + + +def test_list_stored_info_types_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_stored_info_types( + dlp.ListStoredInfoTypesRequest(), + parent="parent_value", + ) + + +def test_list_stored_info_types_rest_pager(transport: str = "rest"): + client = DlpServiceClient( + 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 = ( + dlp.ListStoredInfoTypesResponse( + stored_info_types=[ + dlp.StoredInfoType(), + dlp.StoredInfoType(), + dlp.StoredInfoType(), + ], + next_page_token="abc", + ), + dlp.ListStoredInfoTypesResponse( + stored_info_types=[], + next_page_token="def", + ), + dlp.ListStoredInfoTypesResponse( + stored_info_types=[ + dlp.StoredInfoType(), + ], + next_page_token="ghi", + ), + dlp.ListStoredInfoTypesResponse( + stored_info_types=[ + dlp.StoredInfoType(), + dlp.StoredInfoType(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(dlp.ListStoredInfoTypesResponse.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": "organizations/sample1"} + + pager = client.list_stored_info_types(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, dlp.StoredInfoType) for i in results) + + pages = list(client.list_stored_info_types(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", + [ + dlp.DeleteStoredInfoTypeRequest, + dict, + ], +) +def test_delete_stored_info_type_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/storedInfoTypes/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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_stored_info_type(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_stored_info_type_rest_required_fields( + request_type=dlp.DeleteStoredInfoTypeRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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_stored_info_type._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_stored_info_type._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_stored_info_type(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_stored_info_type_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_stored_info_type._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_stored_info_type_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_delete_stored_info_type" + ) as pre: + pre.assert_not_called() + pb_message = dlp.DeleteStoredInfoTypeRequest.pb( + dlp.DeleteStoredInfoTypeRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.DeleteStoredInfoTypeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_stored_info_type( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_stored_info_type_rest_bad_request( + transport: str = "rest", request_type=dlp.DeleteStoredInfoTypeRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "organizations/sample1/storedInfoTypes/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.delete_stored_info_type(request) + + +def test_delete_stored_info_type_rest_flattened(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "organizations/sample1/storedInfoTypes/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_stored_info_type(**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/v2/{name=organizations/*/storedInfoTypes/*}" % client.transport._host, + args[1], + ) + + +def test_delete_stored_info_type_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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_stored_info_type( + dlp.DeleteStoredInfoTypeRequest(), + name="name_value", + ) + + +def test_delete_stored_info_type_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.HybridInspectDlpJobRequest, + dict, + ], +) +def test_hybrid_inspect_dlp_job_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dlpJobs/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 = dlp.HybridInspectResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = dlp.HybridInspectResponse.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.hybrid_inspect_dlp_job(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, dlp.HybridInspectResponse) + + +def test_hybrid_inspect_dlp_job_rest_required_fields( + request_type=dlp.HybridInspectDlpJobRequest, +): + transport_class = transports.DlpServiceRestTransport + + 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() + ).hybrid_inspect_dlp_job._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() + ).hybrid_inspect_dlp_job._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = dlp.HybridInspectResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = dlp.HybridInspectResponse.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.hybrid_inspect_dlp_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_hybrid_inspect_dlp_job_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.hybrid_inspect_dlp_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_hybrid_inspect_dlp_job_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "post_hybrid_inspect_dlp_job" + ) as post, mock.patch.object( + transports.DlpServiceRestInterceptor, "pre_hybrid_inspect_dlp_job" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = dlp.HybridInspectDlpJobRequest.pb(dlp.HybridInspectDlpJobRequest()) + 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 = dlp.HybridInspectResponse.to_json( + dlp.HybridInspectResponse() + ) + + request = dlp.HybridInspectDlpJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = dlp.HybridInspectResponse() + + client.hybrid_inspect_dlp_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_hybrid_inspect_dlp_job_rest_bad_request( + transport: str = "rest", request_type=dlp.HybridInspectDlpJobRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dlpJobs/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.hybrid_inspect_dlp_job(request) + + +def test_hybrid_inspect_dlp_job_rest_flattened(): + client = DlpServiceClient( + 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 = dlp.HybridInspectResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/dlpJobs/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 = dlp.HybridInspectResponse.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.hybrid_inspect_dlp_job(**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/v2/{name=projects/*/locations/*/dlpJobs/*}:hybridInspect" + % client.transport._host, + args[1], + ) + + +def test_hybrid_inspect_dlp_job_rest_flattened_error(transport: str = "rest"): + client = DlpServiceClient( + 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.hybrid_inspect_dlp_job( + dlp.HybridInspectDlpJobRequest(), + name="name_value", + ) + + +def test_hybrid_inspect_dlp_job_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + dlp.FinishDlpJobRequest, + dict, + ], +) +def test_finish_dlp_job_rest(request_type): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dlpJobs/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.finish_dlp_job(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_finish_dlp_job_rest_required_fields(request_type=dlp.FinishDlpJobRequest): + transport_class = transports.DlpServiceRestTransport + + 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() + ).finish_dlp_job._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() + ).finish_dlp_job._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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "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 = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.finish_dlp_job(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_finish_dlp_job_rest_unset_required_fields(): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.finish_dlp_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_finish_dlp_job_rest_interceptors(null_interceptor): + transport = transports.DlpServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.DlpServiceRestInterceptor(), + ) + client = DlpServiceClient(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.DlpServiceRestInterceptor, "pre_finish_dlp_job" + ) as pre: + pre.assert_not_called() + pb_message = dlp.FinishDlpJobRequest.pb(dlp.FinishDlpJobRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + + request = dlp.FinishDlpJobRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.finish_dlp_job( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_finish_dlp_job_rest_bad_request( + transport: str = "rest", request_type=dlp.FinishDlpJobRequest +): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/dlpJobs/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.finish_dlp_job(request) + + +def test_finish_dlp_job_rest_error(): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.DlpServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.DlpServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DlpServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.DlpServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = DlpServiceClient( + 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 = DlpServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.DlpServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = DlpServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.DlpServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = DlpServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.DlpServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.DlpServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.DlpServiceGrpcTransport, + transports.DlpServiceGrpcAsyncIOTransport, + transports.DlpServiceRestTransport, + ], +) +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 = DlpServiceClient.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 = DlpServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.DlpServiceGrpcTransport, + ) + + +def test_dlp_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.DlpServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_dlp_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.dlp_v2.services.dlp_service.transports.DlpServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.DlpServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "inspect_content", + "redact_image", + "deidentify_content", + "reidentify_content", + "list_info_types", + "create_inspect_template", + "update_inspect_template", + "get_inspect_template", + "list_inspect_templates", + "delete_inspect_template", + "create_deidentify_template", + "update_deidentify_template", + "get_deidentify_template", + "list_deidentify_templates", + "delete_deidentify_template", + "create_job_trigger", + "update_job_trigger", + "hybrid_inspect_job_trigger", "get_job_trigger", "list_job_triggers", "delete_job_trigger", @@ -9666,6 +18407,7 @@ def test_dlp_service_transport_auth_adc(transport_class): [ transports.DlpServiceGrpcTransport, transports.DlpServiceGrpcAsyncIOTransport, + transports.DlpServiceRestTransport, ], ) def test_dlp_service_transport_auth_gdch_credentials(transport_class): @@ -9760,11 +18502,23 @@ def test_dlp_service_grpc_transport_client_cert_source_for_mtls(transport_class) ) +def test_dlp_service_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.DlpServiceRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_dlp_service_host_no_port(transport_name): @@ -9773,7 +18527,11 @@ def test_dlp_service_host_no_port(transport_name): client_options=client_options.ClientOptions(api_endpoint="dlp.googleapis.com"), transport=transport_name, ) - assert client.transport._host == ("dlp.googleapis.com:443") + assert client.transport._host == ( + "dlp.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dlp.googleapis.com" + ) @pytest.mark.parametrize( @@ -9781,6 +18539,7 @@ def test_dlp_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_dlp_service_host_with_port(transport_name): @@ -9791,7 +18550,132 @@ def test_dlp_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("dlp.googleapis.com:8000") + assert client.transport._host == ( + "dlp.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://dlp.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_dlp_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = DlpServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = DlpServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.inspect_content._session + session2 = client2.transport.inspect_content._session + assert session1 != session2 + session1 = client1.transport.redact_image._session + session2 = client2.transport.redact_image._session + assert session1 != session2 + session1 = client1.transport.deidentify_content._session + session2 = client2.transport.deidentify_content._session + assert session1 != session2 + session1 = client1.transport.reidentify_content._session + session2 = client2.transport.reidentify_content._session + assert session1 != session2 + session1 = client1.transport.list_info_types._session + session2 = client2.transport.list_info_types._session + assert session1 != session2 + session1 = client1.transport.create_inspect_template._session + session2 = client2.transport.create_inspect_template._session + assert session1 != session2 + session1 = client1.transport.update_inspect_template._session + session2 = client2.transport.update_inspect_template._session + assert session1 != session2 + session1 = client1.transport.get_inspect_template._session + session2 = client2.transport.get_inspect_template._session + assert session1 != session2 + session1 = client1.transport.list_inspect_templates._session + session2 = client2.transport.list_inspect_templates._session + assert session1 != session2 + session1 = client1.transport.delete_inspect_template._session + session2 = client2.transport.delete_inspect_template._session + assert session1 != session2 + session1 = client1.transport.create_deidentify_template._session + session2 = client2.transport.create_deidentify_template._session + assert session1 != session2 + session1 = client1.transport.update_deidentify_template._session + session2 = client2.transport.update_deidentify_template._session + assert session1 != session2 + session1 = client1.transport.get_deidentify_template._session + session2 = client2.transport.get_deidentify_template._session + assert session1 != session2 + session1 = client1.transport.list_deidentify_templates._session + session2 = client2.transport.list_deidentify_templates._session + assert session1 != session2 + session1 = client1.transport.delete_deidentify_template._session + session2 = client2.transport.delete_deidentify_template._session + assert session1 != session2 + session1 = client1.transport.create_job_trigger._session + session2 = client2.transport.create_job_trigger._session + assert session1 != session2 + session1 = client1.transport.update_job_trigger._session + session2 = client2.transport.update_job_trigger._session + assert session1 != session2 + session1 = client1.transport.hybrid_inspect_job_trigger._session + session2 = client2.transport.hybrid_inspect_job_trigger._session + assert session1 != session2 + session1 = client1.transport.get_job_trigger._session + session2 = client2.transport.get_job_trigger._session + assert session1 != session2 + session1 = client1.transport.list_job_triggers._session + session2 = client2.transport.list_job_triggers._session + assert session1 != session2 + session1 = client1.transport.delete_job_trigger._session + session2 = client2.transport.delete_job_trigger._session + assert session1 != session2 + session1 = client1.transport.activate_job_trigger._session + session2 = client2.transport.activate_job_trigger._session + assert session1 != session2 + session1 = client1.transport.create_dlp_job._session + session2 = client2.transport.create_dlp_job._session + assert session1 != session2 + session1 = client1.transport.list_dlp_jobs._session + session2 = client2.transport.list_dlp_jobs._session + assert session1 != session2 + session1 = client1.transport.get_dlp_job._session + session2 = client2.transport.get_dlp_job._session + assert session1 != session2 + session1 = client1.transport.delete_dlp_job._session + session2 = client2.transport.delete_dlp_job._session + assert session1 != session2 + session1 = client1.transport.cancel_dlp_job._session + session2 = client2.transport.cancel_dlp_job._session + assert session1 != session2 + session1 = client1.transport.create_stored_info_type._session + session2 = client2.transport.create_stored_info_type._session + assert session1 != session2 + session1 = client1.transport.update_stored_info_type._session + session2 = client2.transport.update_stored_info_type._session + assert session1 != session2 + session1 = client1.transport.get_stored_info_type._session + session2 = client2.transport.get_stored_info_type._session + assert session1 != session2 + session1 = client1.transport.list_stored_info_types._session + session2 = client2.transport.list_stored_info_types._session + assert session1 != session2 + session1 = client1.transport.delete_stored_info_type._session + session2 = client2.transport.delete_stored_info_type._session + assert session1 != session2 + session1 = client1.transport.hybrid_inspect_dlp_job._session + session2 = client2.transport.hybrid_inspect_dlp_job._session + assert session1 != session2 + session1 = client1.transport.finish_dlp_job._session + session2 = client2.transport.finish_dlp_job._session + assert session1 != session2 def test_dlp_service_grpc_transport_channel(): @@ -10221,6 +19105,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -10238,6 +19123,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: