diff --git a/google/cloud/websecurityscanner_v1/gapic_metadata.json b/google/cloud/websecurityscanner_v1/gapic_metadata.json index 2b6f23a..9f9d16e 100644 --- a/google/cloud/websecurityscanner_v1/gapic_metadata.json +++ b/google/cloud/websecurityscanner_v1/gapic_metadata.json @@ -146,6 +146,76 @@ ] } } + }, + "rest": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } } } } diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py index dbdeeb6..0a4f4d3 100644 --- a/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/client.py @@ -64,6 +64,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, WebSecurityScannerTransport from .transports.grpc import WebSecurityScannerGrpcTransport from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .transports.rest import WebSecurityScannerRestTransport class WebSecurityScannerClientMeta(type): @@ -79,6 +80,7 @@ class WebSecurityScannerClientMeta(type): ) # type: Dict[str, Type[WebSecurityScannerTransport]] _transport_registry["grpc"] = WebSecurityScannerGrpcTransport _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + _transport_registry["rest"] = WebSecurityScannerRestTransport def get_transport_class( cls, diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py index 3dd2101..33821da 100644 --- a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/__init__.py @@ -19,6 +19,7 @@ from .base import WebSecurityScannerTransport from .grpc import WebSecurityScannerGrpcTransport from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .rest import WebSecurityScannerRestInterceptor, WebSecurityScannerRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[WebSecurityScannerTransport]] _transport_registry["grpc"] = WebSecurityScannerGrpcTransport _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport +_transport_registry["rest"] = WebSecurityScannerRestTransport __all__ = ( "WebSecurityScannerTransport", "WebSecurityScannerGrpcTransport", "WebSecurityScannerGrpcAsyncIOTransport", + "WebSecurityScannerRestTransport", + "WebSecurityScannerRestInterceptor", ) diff --git a/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py new file mode 100644 index 0000000..c73ca40 --- /dev/null +++ b/google/cloud/websecurityscanner_v1/services/web_security_scanner/transports/rest.py @@ -0,0 +1,1721 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.websecurityscanner_v1.types import ( + finding, + scan_config, + scan_run, + web_security_scanner, +) + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import WebSecurityScannerTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class WebSecurityScannerRestInterceptor: + """Interceptor for WebSecurityScanner. + + 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 WebSecurityScannerRestTransport. + + .. code-block:: python + class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): + def pre_create_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crawled_urls(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crawled_urls(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_finding_type_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_finding_type_stats(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) + client = WebSecurityScannerClient(transport=transport) + + + """ + + def pre_create_scan_config( + self, + request: web_security_scanner.CreateScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_create_scan_config( + self, response: scan_config.ScanConfig + ) -> scan_config.ScanConfig: + """Post-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_delete_scan_config( + self, + request: web_security_scanner.DeleteScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def pre_get_finding( + self, + request: web_security_scanner.GetFindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_finding(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for get_finding + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_config( + self, + request: web_security_scanner.GetScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_config( + self, response: scan_config.ScanConfig + ) -> scan_config.ScanConfig: + """Post-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_run( + self, + request: web_security_scanner.GetScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_crawled_urls( + self, + request: web_security_scanner.ListCrawledUrlsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_crawled_urls( + self, response: web_security_scanner.ListCrawledUrlsResponse + ) -> web_security_scanner.ListCrawledUrlsResponse: + """Post-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_findings( + self, + request: web_security_scanner.ListFindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_findings( + self, response: web_security_scanner.ListFindingsResponse + ) -> web_security_scanner.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_finding_type_stats( + self, + request: web_security_scanner.ListFindingTypeStatsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_finding_type_stats( + self, response: web_security_scanner.ListFindingTypeStatsResponse + ) -> web_security_scanner.ListFindingTypeStatsResponse: + """Post-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_configs( + self, + request: web_security_scanner.ListScanConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_configs( + self, response: web_security_scanner.ListScanConfigsResponse + ) -> web_security_scanner.ListScanConfigsResponse: + """Post-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_runs( + self, + request: web_security_scanner.ListScanRunsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_runs( + self, response: web_security_scanner.ListScanRunsResponse + ) -> web_security_scanner.ListScanRunsResponse: + """Post-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_start_scan_run( + self, + request: web_security_scanner.StartScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_stop_scan_run( + self, + request: web_security_scanner.StopScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_update_scan_config( + self, + request: web_security_scanner.UpdateScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_update_scan_config( + self, response: scan_config.ScanConfig + ) -> scan_config.ScanConfig: + """Post-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WebSecurityScannerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WebSecurityScannerRestInterceptor + + +class WebSecurityScannerRestTransport(WebSecurityScannerTransport): + """REST backend transport for WebSecurityScanner. + + Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud. It + crawls your application, and attempts to exercise as many user + inputs and event handlers as possible. + + 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 = "websecurityscanner.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[WebSecurityScannerRestInterceptor] = 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 WebSecurityScannerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("CreateScanConfig") + + def __call__( + self, + request: web_security_scanner.CreateScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Call the create scan config method over HTTP. + + Args: + request (~.web_security_scanner.CreateScanConfigRequest): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*}/scanConfigs", + "body": "scan_config", + }, + ] + request, metadata = self._interceptor.pre_create_scan_config( + request, metadata + ) + pb_request = web_security_scanner.CreateScanConfigRequest.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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_scan_config(resp) + return resp + + class _DeleteScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("DeleteScanConfig") + + def __call__( + self, + request: web_security_scanner.DeleteScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete scan config method over HTTP. + + Args: + request (~.web_security_scanner.DeleteScanConfigRequest): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/scanConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_scan_config( + request, metadata + ) + pb_request = web_security_scanner.DeleteScanConfigRequest.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) + + class _GetFinding(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetFinding") + + def __call__( + self, + request: web_security_scanner.GetFindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Call the get finding method over HTTP. + + Args: + request (~.web_security_scanner.GetFindingRequest): + The request object. Request for the ``GetFinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}", + }, + ] + request, metadata = self._interceptor.pre_get_finding(request, metadata) + pb_request = web_security_scanner.GetFindingRequest.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 = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_finding(resp) + return resp + + class _GetScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetScanConfig") + + def __call__( + self, + request: web_security_scanner.GetScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Call the get scan config method over HTTP. + + Args: + request (~.web_security_scanner.GetScanConfigRequest): + The request object. Request for the ``GetScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/scanConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_scan_config(request, metadata) + pb_request = web_security_scanner.GetScanConfigRequest.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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_config(resp) + return resp + + class _GetScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetScanRun") + + def __call__( + self, + request: web_security_scanner.GetScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the get scan run method over HTTP. + + Args: + request (~.web_security_scanner.GetScanRunRequest): + The request object. Request for the ``GetScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/scanConfigs/*/scanRuns/*}", + }, + ] + request, metadata = self._interceptor.pre_get_scan_run(request, metadata) + pb_request = web_security_scanner.GetScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_run(resp) + return resp + + class _ListCrawledUrls(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListCrawledUrls") + + def __call__( + self, + request: web_security_scanner.ListCrawledUrlsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListCrawledUrlsResponse: + r"""Call the list crawled urls method over HTTP. + + Args: + request (~.web_security_scanner.ListCrawledUrlsRequest): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListCrawledUrlsResponse: + Response for the ``ListCrawledUrls`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls", + }, + ] + request, metadata = self._interceptor.pre_list_crawled_urls( + request, metadata + ) + pb_request = web_security_scanner.ListCrawledUrlsRequest.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 = web_security_scanner.ListCrawledUrlsResponse() + pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crawled_urls(resp) + return resp + + class _ListFindings(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListFindings") + + def __call__( + self, + request: web_security_scanner.ListFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingsRequest): + The request object. Request for the ``ListFindings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListFindingsResponse: + Response for the ``ListFindings`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings", + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = web_security_scanner.ListFindingsRequest.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 = web_security_scanner.ListFindingsResponse() + pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListFindingTypeStats(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListFindingTypeStats") + + def __call__( + self, + request: web_security_scanner.ListFindingTypeStatsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""Call the list finding type stats method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingTypeStatsRequest): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListFindingTypeStatsResponse: + Response for the ``ListFindingTypeStats`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats", + }, + ] + request, metadata = self._interceptor.pre_list_finding_type_stats( + request, metadata + ) + pb_request = web_security_scanner.ListFindingTypeStatsRequest.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 = web_security_scanner.ListFindingTypeStatsResponse() + pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_finding_type_stats(resp) + return resp + + class _ListScanConfigs(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListScanConfigs") + + def __call__( + self, + request: web_security_scanner.ListScanConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListScanConfigsResponse: + r"""Call the list scan configs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanConfigsRequest): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListScanConfigsResponse: + Response for the ``ListScanConfigs`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*}/scanConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_scan_configs( + request, metadata + ) + pb_request = web_security_scanner.ListScanConfigsRequest.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 = web_security_scanner.ListScanConfigsResponse() + pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_configs(resp) + return resp + + class _ListScanRuns(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListScanRuns") + + def __call__( + self, + request: web_security_scanner.ListScanRunsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListScanRunsResponse: + r"""Call the list scan runs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanRunsRequest): + The request object. Request for the ``ListScanRuns`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListScanRunsResponse: + Response for the ``ListScanRuns`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/scanConfigs/*}/scanRuns", + }, + ] + request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) + pb_request = web_security_scanner.ListScanRunsRequest.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 = web_security_scanner.ListScanRunsResponse() + pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_runs(resp) + return resp + + class _StartScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("StartScanRun") + + def __call__( + self, + request: web_security_scanner.StartScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the start scan run method over HTTP. + + Args: + request (~.web_security_scanner.StartScanRunRequest): + The request object. Request for the ``StartScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/scanConfigs/*}:start", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_start_scan_run(request, metadata) + pb_request = web_security_scanner.StartScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_scan_run(resp) + return resp + + class _StopScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("StopScanRun") + + def __call__( + self, + request: web_security_scanner.StopScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the stop scan run method over HTTP. + + Args: + request (~.web_security_scanner.StopScanRunRequest): + The request object. Request for the ``StopScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/scanConfigs/*/scanRuns/*}:stop", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) + pb_request = web_security_scanner.StopScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_scan_run(resp) + return resp + + class _UpdateScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("UpdateScanConfig") + + def __call__( + self, + request: web_security_scanner.UpdateScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Call the update scan config method over HTTP. + + Args: + request (~.web_security_scanner.UpdateScanConfigRequest): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{scan_config.name=projects/*/scanConfigs/*}", + "body": "scan_config", + }, + ] + request, metadata = self._interceptor.pre_update_scan_config( + request, metadata + ) + pb_request = web_security_scanner.UpdateScanConfigRequest.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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_scan_config(resp) + return resp + + @property + def create_scan_config( + self, + ) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], scan_config.ScanConfig + ]: + # 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._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scan_config( + self, + ) -> Callable[[web_security_scanner.DeleteScanConfigRequest], 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_finding( + self, + ) -> Callable[[web_security_scanner.GetFindingRequest], finding.Finding]: + # 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._GetFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_config( + self, + ) -> Callable[[web_security_scanner.GetScanConfigRequest], scan_config.ScanConfig]: + # 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._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_run( + self, + ) -> Callable[[web_security_scanner.GetScanRunRequest], scan_run.ScanRun]: + # 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._GetScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crawled_urls( + self, + ) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse, + ]: + # 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._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings( + self, + ) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse, + ]: + # 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._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_finding_type_stats( + self, + ) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse, + ]: + # 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._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_configs( + self, + ) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse, + ]: + # 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._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_runs( + self, + ) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse, + ]: + # 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._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_scan_run( + self, + ) -> Callable[[web_security_scanner.StartScanRunRequest], scan_run.ScanRun]: + # 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._StartScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_scan_run( + self, + ) -> Callable[[web_security_scanner.StopScanRunRequest], scan_run.ScanRun]: + # 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._StopScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scan_config( + self, + ) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], scan_config.ScanConfig + ]: + # 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._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("WebSecurityScannerRestTransport",) diff --git a/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json b/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json index f43f913..a7c87fd 100644 --- a/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json +++ b/google/cloud/websecurityscanner_v1alpha/gapic_metadata.json @@ -146,6 +146,76 @@ ] } } + }, + "rest": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } } } } diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py index f3de3a2..82d1a42 100644 --- a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/client.py @@ -63,6 +63,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, WebSecurityScannerTransport from .transports.grpc import WebSecurityScannerGrpcTransport from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .transports.rest import WebSecurityScannerRestTransport class WebSecurityScannerClientMeta(type): @@ -78,6 +79,7 @@ class WebSecurityScannerClientMeta(type): ) # type: Dict[str, Type[WebSecurityScannerTransport]] _transport_registry["grpc"] = WebSecurityScannerGrpcTransport _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + _transport_registry["rest"] = WebSecurityScannerRestTransport def get_transport_class( cls, diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py index 3dd2101..33821da 100644 --- a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/__init__.py @@ -19,6 +19,7 @@ from .base import WebSecurityScannerTransport from .grpc import WebSecurityScannerGrpcTransport from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .rest import WebSecurityScannerRestInterceptor, WebSecurityScannerRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[WebSecurityScannerTransport]] _transport_registry["grpc"] = WebSecurityScannerGrpcTransport _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport +_transport_registry["rest"] = WebSecurityScannerRestTransport __all__ = ( "WebSecurityScannerTransport", "WebSecurityScannerGrpcTransport", "WebSecurityScannerGrpcAsyncIOTransport", + "WebSecurityScannerRestTransport", + "WebSecurityScannerRestInterceptor", ) diff --git a/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py new file mode 100644 index 0000000..58c1fe8 --- /dev/null +++ b/google/cloud/websecurityscanner_v1alpha/services/web_security_scanner/transports/rest.py @@ -0,0 +1,1866 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.websecurityscanner_v1alpha.types import scan_run, web_security_scanner +from google.cloud.websecurityscanner_v1alpha.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1alpha.types import finding +from google.cloud.websecurityscanner_v1alpha.types import scan_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import WebSecurityScannerTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class WebSecurityScannerRestInterceptor: + """Interceptor for WebSecurityScanner. + + 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 WebSecurityScannerRestTransport. + + .. code-block:: python + class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): + def pre_create_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crawled_urls(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crawled_urls(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_finding_type_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_finding_type_stats(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) + client = WebSecurityScannerClient(transport=transport) + + + """ + + def pre_create_scan_config( + self, + request: web_security_scanner.CreateScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_create_scan_config( + self, response: gcw_scan_config.ScanConfig + ) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_delete_scan_config( + self, + request: web_security_scanner.DeleteScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def pre_get_finding( + self, + request: web_security_scanner.GetFindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_finding(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for get_finding + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_config( + self, + request: web_security_scanner.GetScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_config( + self, response: scan_config.ScanConfig + ) -> scan_config.ScanConfig: + """Post-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_run( + self, + request: web_security_scanner.GetScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_crawled_urls( + self, + request: web_security_scanner.ListCrawledUrlsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_crawled_urls( + self, response: web_security_scanner.ListCrawledUrlsResponse + ) -> web_security_scanner.ListCrawledUrlsResponse: + """Post-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_findings( + self, + request: web_security_scanner.ListFindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_findings( + self, response: web_security_scanner.ListFindingsResponse + ) -> web_security_scanner.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_finding_type_stats( + self, + request: web_security_scanner.ListFindingTypeStatsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_finding_type_stats( + self, response: web_security_scanner.ListFindingTypeStatsResponse + ) -> web_security_scanner.ListFindingTypeStatsResponse: + """Post-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_configs( + self, + request: web_security_scanner.ListScanConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_configs( + self, response: web_security_scanner.ListScanConfigsResponse + ) -> web_security_scanner.ListScanConfigsResponse: + """Post-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_runs( + self, + request: web_security_scanner.ListScanRunsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_runs( + self, response: web_security_scanner.ListScanRunsResponse + ) -> web_security_scanner.ListScanRunsResponse: + """Post-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_start_scan_run( + self, + request: web_security_scanner.StartScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_stop_scan_run( + self, + request: web_security_scanner.StopScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_update_scan_config( + self, + request: web_security_scanner.UpdateScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_update_scan_config( + self, response: gcw_scan_config.ScanConfig + ) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WebSecurityScannerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WebSecurityScannerRestInterceptor + + +class WebSecurityScannerRestTransport(WebSecurityScannerTransport): + """REST backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + 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 = "websecurityscanner.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[WebSecurityScannerRestInterceptor] = 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 WebSecurityScannerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("CreateScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.CreateScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Call the create scan config method over HTTP. + + Args: + request (~.web_security_scanner.CreateScanConfigRequest): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{parent=projects/*}/scanConfigs", + "body": "scan_config", + }, + ] + request, metadata = self._interceptor.pre_create_scan_config( + request, metadata + ) + pb_request = web_security_scanner.CreateScanConfigRequest.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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_scan_config(resp) + return resp + + class _DeleteScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("DeleteScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.DeleteScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete scan config method over HTTP. + + Args: + request (~.web_security_scanner.DeleteScanConfigRequest): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1alpha/{name=projects/*/scanConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_scan_config( + request, metadata + ) + pb_request = web_security_scanner.DeleteScanConfigRequest.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 _GetFinding(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.GetFindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Call the get finding method over HTTP. + + Args: + request (~.web_security_scanner.GetFindingRequest): + The request object. Request for the ``GetFinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}", + }, + ] + request, metadata = self._interceptor.pre_get_finding(request, metadata) + pb_request = web_security_scanner.GetFindingRequest.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 = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_finding(resp) + return resp + + class _GetScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.GetScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Call the get scan config method over HTTP. + + Args: + request (~.web_security_scanner.GetScanConfigRequest): + The request object. Request for the ``GetScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/scanConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_scan_config(request, metadata) + pb_request = web_security_scanner.GetScanConfigRequest.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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_config(resp) + return resp + + class _GetScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetScanRun") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.GetScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the get scan run method over HTTP. + + Args: + request (~.web_security_scanner.GetScanRunRequest): + The request object. Request for the ``GetScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}", + }, + ] + request, metadata = self._interceptor.pre_get_scan_run(request, metadata) + pb_request = web_security_scanner.GetScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_run(resp) + return resp + + class _ListCrawledUrls(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListCrawledUrls") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListCrawledUrlsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListCrawledUrlsResponse: + r"""Call the list crawled urls method over HTTP. + + Args: + request (~.web_security_scanner.ListCrawledUrlsRequest): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListCrawledUrlsResponse: + Response for the ``ListCrawledUrls`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls", + }, + ] + request, metadata = self._interceptor.pre_list_crawled_urls( + request, metadata + ) + pb_request = web_security_scanner.ListCrawledUrlsRequest.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 = web_security_scanner.ListCrawledUrlsResponse() + pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crawled_urls(resp) + return resp + + class _ListFindings(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "filter": "", + } + + @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: web_security_scanner.ListFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingsRequest): + The request object. Request for the ``ListFindings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListFindingsResponse: + Response for the ``ListFindings`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings", + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = web_security_scanner.ListFindingsRequest.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 = web_security_scanner.ListFindingsResponse() + pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListFindingTypeStats(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListFindingTypeStats") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListFindingTypeStatsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""Call the list finding type stats method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingTypeStatsRequest): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListFindingTypeStatsResponse: + Response for the ``ListFindingTypeStats`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats", + }, + ] + request, metadata = self._interceptor.pre_list_finding_type_stats( + request, metadata + ) + pb_request = web_security_scanner.ListFindingTypeStatsRequest.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 = web_security_scanner.ListFindingTypeStatsResponse() + pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_finding_type_stats(resp) + return resp + + class _ListScanConfigs(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListScanConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListScanConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListScanConfigsResponse: + r"""Call the list scan configs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanConfigsRequest): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListScanConfigsResponse: + Response for the ``ListScanConfigs`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*}/scanConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_scan_configs( + request, metadata + ) + pb_request = web_security_scanner.ListScanConfigsRequest.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 = web_security_scanner.ListScanConfigsResponse() + pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_configs(resp) + return resp + + class _ListScanRuns(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListScanRuns") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListScanRunsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListScanRunsResponse: + r"""Call the list scan runs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanRunsRequest): + The request object. Request for the ``ListScanRuns`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListScanRunsResponse: + Response for the ``ListScanRuns`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1alpha/{parent=projects/*/scanConfigs/*}/scanRuns", + }, + ] + request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) + pb_request = web_security_scanner.ListScanRunsRequest.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 = web_security_scanner.ListScanRunsResponse() + pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_runs(resp) + return resp + + class _StartScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("StartScanRun") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.StartScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the start scan run method over HTTP. + + Args: + request (~.web_security_scanner.StartScanRunRequest): + The request object. Request for the ``StartScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/scanConfigs/*}:start", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_start_scan_run(request, metadata) + pb_request = web_security_scanner.StartScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_scan_run(resp) + return resp + + class _StopScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("StopScanRun") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.StopScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the stop scan run method over HTTP. + + Args: + request (~.web_security_scanner.StopScanRunRequest): + The request object. Request for the ``StopScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}:stop", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) + pb_request = web_security_scanner.StopScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_scan_run(resp) + return resp + + class _UpdateScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("UpdateScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.UpdateScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Call the update scan config method over HTTP. + + Args: + request (~.web_security_scanner.UpdateScanConfigRequest): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. next + id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1alpha/{scan_config.name=projects/*/scanConfigs/*}", + "body": "scan_config", + }, + ] + request, metadata = self._interceptor.pre_update_scan_config( + request, metadata + ) + pb_request = web_security_scanner.UpdateScanConfigRequest.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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_scan_config(resp) + return resp + + @property + def create_scan_config( + self, + ) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], gcw_scan_config.ScanConfig + ]: + # 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._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scan_config( + self, + ) -> Callable[[web_security_scanner.DeleteScanConfigRequest], 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_finding( + self, + ) -> Callable[[web_security_scanner.GetFindingRequest], finding.Finding]: + # 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._GetFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_config( + self, + ) -> Callable[[web_security_scanner.GetScanConfigRequest], scan_config.ScanConfig]: + # 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._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_run( + self, + ) -> Callable[[web_security_scanner.GetScanRunRequest], scan_run.ScanRun]: + # 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._GetScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crawled_urls( + self, + ) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse, + ]: + # 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._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings( + self, + ) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse, + ]: + # 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._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_finding_type_stats( + self, + ) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse, + ]: + # 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._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_configs( + self, + ) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse, + ]: + # 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._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_runs( + self, + ) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse, + ]: + # 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._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_scan_run( + self, + ) -> Callable[[web_security_scanner.StartScanRunRequest], scan_run.ScanRun]: + # 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._StartScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_scan_run( + self, + ) -> Callable[[web_security_scanner.StopScanRunRequest], scan_run.ScanRun]: + # 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._StopScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scan_config( + self, + ) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], gcw_scan_config.ScanConfig + ]: + # 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._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("WebSecurityScannerRestTransport",) diff --git a/google/cloud/websecurityscanner_v1beta/gapic_metadata.json b/google/cloud/websecurityscanner_v1beta/gapic_metadata.json index 114e6f0..329504a 100644 --- a/google/cloud/websecurityscanner_v1beta/gapic_metadata.json +++ b/google/cloud/websecurityscanner_v1beta/gapic_metadata.json @@ -146,6 +146,76 @@ ] } } + }, + "rest": { + "libraryClient": "WebSecurityScannerClient", + "rpcs": { + "CreateScanConfig": { + "methods": [ + "create_scan_config" + ] + }, + "DeleteScanConfig": { + "methods": [ + "delete_scan_config" + ] + }, + "GetFinding": { + "methods": [ + "get_finding" + ] + }, + "GetScanConfig": { + "methods": [ + "get_scan_config" + ] + }, + "GetScanRun": { + "methods": [ + "get_scan_run" + ] + }, + "ListCrawledUrls": { + "methods": [ + "list_crawled_urls" + ] + }, + "ListFindingTypeStats": { + "methods": [ + "list_finding_type_stats" + ] + }, + "ListFindings": { + "methods": [ + "list_findings" + ] + }, + "ListScanConfigs": { + "methods": [ + "list_scan_configs" + ] + }, + "ListScanRuns": { + "methods": [ + "list_scan_runs" + ] + }, + "StartScanRun": { + "methods": [ + "start_scan_run" + ] + }, + "StopScanRun": { + "methods": [ + "stop_scan_run" + ] + }, + "UpdateScanConfig": { + "methods": [ + "update_scan_config" + ] + } + } } } } diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py index 552e399..55c74db 100644 --- a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/client.py @@ -68,6 +68,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, WebSecurityScannerTransport from .transports.grpc import WebSecurityScannerGrpcTransport from .transports.grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .transports.rest import WebSecurityScannerRestTransport class WebSecurityScannerClientMeta(type): @@ -83,6 +84,7 @@ class WebSecurityScannerClientMeta(type): ) # type: Dict[str, Type[WebSecurityScannerTransport]] _transport_registry["grpc"] = WebSecurityScannerGrpcTransport _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport + _transport_registry["rest"] = WebSecurityScannerRestTransport def get_transport_class( cls, diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py index 3dd2101..33821da 100644 --- a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/__init__.py @@ -19,6 +19,7 @@ from .base import WebSecurityScannerTransport from .grpc import WebSecurityScannerGrpcTransport from .grpc_asyncio import WebSecurityScannerGrpcAsyncIOTransport +from .rest import WebSecurityScannerRestInterceptor, WebSecurityScannerRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[WebSecurityScannerTransport]] _transport_registry["grpc"] = WebSecurityScannerGrpcTransport _transport_registry["grpc_asyncio"] = WebSecurityScannerGrpcAsyncIOTransport +_transport_registry["rest"] = WebSecurityScannerRestTransport __all__ = ( "WebSecurityScannerTransport", "WebSecurityScannerGrpcTransport", "WebSecurityScannerGrpcAsyncIOTransport", + "WebSecurityScannerRestTransport", + "WebSecurityScannerRestInterceptor", ) diff --git a/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py new file mode 100644 index 0000000..c59e821 --- /dev/null +++ b/google/cloud/websecurityscanner_v1beta/services/web_security_scanner/transports/rest.py @@ -0,0 +1,1866 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.protobuf import empty_pb2 # type: ignore + +from google.cloud.websecurityscanner_v1beta.types import scan_run, web_security_scanner +from google.cloud.websecurityscanner_v1beta.types import scan_config as gcw_scan_config +from google.cloud.websecurityscanner_v1beta.types import finding +from google.cloud.websecurityscanner_v1beta.types import scan_config + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import WebSecurityScannerTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class WebSecurityScannerRestInterceptor: + """Interceptor for WebSecurityScanner. + + 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 WebSecurityScannerRestTransport. + + .. code-block:: python + class MyCustomWebSecurityScannerInterceptor(WebSecurityScannerRestInterceptor): + def pre_create_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_finding(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_finding(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_crawled_urls(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_crawled_urls(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_findings(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_findings(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_finding_type_stats(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_finding_type_stats(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_configs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_configs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_scan_runs(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_scan_runs(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_scan_run(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_scan_run(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_scan_config(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_scan_config(self, response): + logging.log(f"Received response: {response}") + return response + + transport = WebSecurityScannerRestTransport(interceptor=MyCustomWebSecurityScannerInterceptor()) + client = WebSecurityScannerClient(transport=transport) + + + """ + + def pre_create_scan_config( + self, + request: web_security_scanner.CreateScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.CreateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_create_scan_config( + self, response: gcw_scan_config.ScanConfig + ) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for create_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_delete_scan_config( + self, + request: web_security_scanner.DeleteScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.DeleteScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def pre_get_finding( + self, + request: web_security_scanner.GetFindingRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetFindingRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_finding + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_finding(self, response: finding.Finding) -> finding.Finding: + """Post-rpc interceptor for get_finding + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_config( + self, + request: web_security_scanner.GetScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_config( + self, response: scan_config.ScanConfig + ) -> scan_config.ScanConfig: + """Post-rpc interceptor for get_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_get_scan_run( + self, + request: web_security_scanner.GetScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.GetScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_get_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for get_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_crawled_urls( + self, + request: web_security_scanner.ListCrawledUrlsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListCrawledUrlsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_crawled_urls( + self, response: web_security_scanner.ListCrawledUrlsResponse + ) -> web_security_scanner.ListCrawledUrlsResponse: + """Post-rpc interceptor for list_crawled_urls + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_findings( + self, + request: web_security_scanner.ListFindingsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListFindingsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_findings + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_findings( + self, response: web_security_scanner.ListFindingsResponse + ) -> web_security_scanner.ListFindingsResponse: + """Post-rpc interceptor for list_findings + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_finding_type_stats( + self, + request: web_security_scanner.ListFindingTypeStatsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + web_security_scanner.ListFindingTypeStatsRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_finding_type_stats( + self, response: web_security_scanner.ListFindingTypeStatsResponse + ) -> web_security_scanner.ListFindingTypeStatsResponse: + """Post-rpc interceptor for list_finding_type_stats + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_configs( + self, + request: web_security_scanner.ListScanConfigsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListScanConfigsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_configs( + self, response: web_security_scanner.ListScanConfigsResponse + ) -> web_security_scanner.ListScanConfigsResponse: + """Post-rpc interceptor for list_scan_configs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_list_scan_runs( + self, + request: web_security_scanner.ListScanRunsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.ListScanRunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_list_scan_runs( + self, response: web_security_scanner.ListScanRunsResponse + ) -> web_security_scanner.ListScanRunsResponse: + """Post-rpc interceptor for list_scan_runs + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_start_scan_run( + self, + request: web_security_scanner.StartScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.StartScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_start_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for start_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_stop_scan_run( + self, + request: web_security_scanner.StopScanRunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.StopScanRunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_stop_scan_run(self, response: scan_run.ScanRun) -> scan_run.ScanRun: + """Post-rpc interceptor for stop_scan_run + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + def pre_update_scan_config( + self, + request: web_security_scanner.UpdateScanConfigRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[web_security_scanner.UpdateScanConfigRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the request or metadata + before they are sent to the WebSecurityScanner server. + """ + return request, metadata + + def post_update_scan_config( + self, response: gcw_scan_config.ScanConfig + ) -> gcw_scan_config.ScanConfig: + """Post-rpc interceptor for update_scan_config + + Override in a subclass to manipulate the response + after it is returned by the WebSecurityScanner server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class WebSecurityScannerRestStub: + _session: AuthorizedSession + _host: str + _interceptor: WebSecurityScannerRestInterceptor + + +class WebSecurityScannerRestTransport(WebSecurityScannerTransport): + """REST backend transport for WebSecurityScanner. + + Cloud Web Security Scanner Service identifies security + vulnerabilities in web applications hosted on Google Cloud + Platform. It crawls your application, and attempts to exercise + as many user inputs and event handlers as possible. + + 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 = "websecurityscanner.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[WebSecurityScannerRestInterceptor] = 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 WebSecurityScannerRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("CreateScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.CreateScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Call the create scan config method over HTTP. + + Args: + request (~.web_security_scanner.CreateScanConfigRequest): + The request object. Request for the ``CreateScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{parent=projects/*}/scanConfigs", + "body": "scan_config", + }, + ] + request, metadata = self._interceptor.pre_create_scan_config( + request, metadata + ) + pb_request = web_security_scanner.CreateScanConfigRequest.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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_scan_config(resp) + return resp + + class _DeleteScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("DeleteScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.DeleteScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete scan config method over HTTP. + + Args: + request (~.web_security_scanner.DeleteScanConfigRequest): + The request object. Request for the ``DeleteScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/scanConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_scan_config( + request, metadata + ) + pb_request = web_security_scanner.DeleteScanConfigRequest.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 _GetFinding(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetFinding") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.GetFindingRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Call the get finding method over HTTP. + + Args: + request (~.web_security_scanner.GetFindingRequest): + The request object. Request for the ``GetFinding`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + A Finding resource represents a + vulnerability instance identified during + a ScanRun. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}", + }, + ] + request, metadata = self._interceptor.pre_get_finding(request, metadata) + pb_request = web_security_scanner.GetFindingRequest.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 = finding.Finding() + pb_resp = finding.Finding.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_finding(resp) + return resp + + class _GetScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.GetScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_config.ScanConfig: + r"""Call the get scan config method over HTTP. + + Args: + request (~.web_security_scanner.GetScanConfigRequest): + The request object. Request for the ``GetScanConfig`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/scanConfigs/*}", + }, + ] + request, metadata = self._interceptor.pre_get_scan_config(request, metadata) + pb_request = web_security_scanner.GetScanConfigRequest.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 = scan_config.ScanConfig() + pb_resp = scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_config(resp) + return resp + + class _GetScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("GetScanRun") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.GetScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the get scan run method over HTTP. + + Args: + request (~.web_security_scanner.GetScanRunRequest): + The request object. Request for the ``GetScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}", + }, + ] + request, metadata = self._interceptor.pre_get_scan_run(request, metadata) + pb_request = web_security_scanner.GetScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_scan_run(resp) + return resp + + class _ListCrawledUrls(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListCrawledUrls") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListCrawledUrlsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListCrawledUrlsResponse: + r"""Call the list crawled urls method over HTTP. + + Args: + request (~.web_security_scanner.ListCrawledUrlsRequest): + The request object. Request for the ``ListCrawledUrls`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListCrawledUrlsResponse: + Response for the ``ListCrawledUrls`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls", + }, + ] + request, metadata = self._interceptor.pre_list_crawled_urls( + request, metadata + ) + pb_request = web_security_scanner.ListCrawledUrlsRequest.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 = web_security_scanner.ListCrawledUrlsResponse() + pb_resp = web_security_scanner.ListCrawledUrlsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_crawled_urls(resp) + return resp + + class _ListFindings(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListFindings") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "filter": "", + } + + @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: web_security_scanner.ListFindingsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingsResponse: + r"""Call the list findings method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingsRequest): + The request object. Request for the ``ListFindings`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListFindingsResponse: + Response for the ``ListFindings`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings", + }, + ] + request, metadata = self._interceptor.pre_list_findings(request, metadata) + pb_request = web_security_scanner.ListFindingsRequest.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 = web_security_scanner.ListFindingsResponse() + pb_resp = web_security_scanner.ListFindingsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_findings(resp) + return resp + + class _ListFindingTypeStats(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListFindingTypeStats") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListFindingTypeStatsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListFindingTypeStatsResponse: + r"""Call the list finding type stats method over HTTP. + + Args: + request (~.web_security_scanner.ListFindingTypeStatsRequest): + The request object. Request for the ``ListFindingTypeStats`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListFindingTypeStatsResponse: + Response for the ``ListFindingTypeStats`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats", + }, + ] + request, metadata = self._interceptor.pre_list_finding_type_stats( + request, metadata + ) + pb_request = web_security_scanner.ListFindingTypeStatsRequest.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 = web_security_scanner.ListFindingTypeStatsResponse() + pb_resp = web_security_scanner.ListFindingTypeStatsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_finding_type_stats(resp) + return resp + + class _ListScanConfigs(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListScanConfigs") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListScanConfigsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListScanConfigsResponse: + r"""Call the list scan configs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanConfigsRequest): + The request object. Request for the ``ListScanConfigs`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListScanConfigsResponse: + Response for the ``ListScanConfigs`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*}/scanConfigs", + }, + ] + request, metadata = self._interceptor.pre_list_scan_configs( + request, metadata + ) + pb_request = web_security_scanner.ListScanConfigsRequest.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 = web_security_scanner.ListScanConfigsResponse() + pb_resp = web_security_scanner.ListScanConfigsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_configs(resp) + return resp + + class _ListScanRuns(WebSecurityScannerRestStub): + def __hash__(self): + return hash("ListScanRuns") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.ListScanRunsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> web_security_scanner.ListScanRunsResponse: + r"""Call the list scan runs method over HTTP. + + Args: + request (~.web_security_scanner.ListScanRunsRequest): + The request object. Request for the ``ListScanRuns`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.web_security_scanner.ListScanRunsResponse: + Response for the ``ListScanRuns`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1beta/{parent=projects/*/scanConfigs/*}/scanRuns", + }, + ] + request, metadata = self._interceptor.pre_list_scan_runs(request, metadata) + pb_request = web_security_scanner.ListScanRunsRequest.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 = web_security_scanner.ListScanRunsResponse() + pb_resp = web_security_scanner.ListScanRunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_scan_runs(resp) + return resp + + class _StartScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("StartScanRun") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.StartScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the start scan run method over HTTP. + + Args: + request (~.web_security_scanner.StartScanRunRequest): + The request object. Request for the ``StartScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/scanConfigs/*}:start", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_start_scan_run(request, metadata) + pb_request = web_security_scanner.StartScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_scan_run(resp) + return resp + + class _StopScanRun(WebSecurityScannerRestStub): + def __hash__(self): + return hash("StopScanRun") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.StopScanRunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> scan_run.ScanRun: + r"""Call the stop scan run method over HTTP. + + Args: + request (~.web_security_scanner.StopScanRunRequest): + The request object. Request for the ``StopScanRun`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.scan_run.ScanRun: + A ScanRun is a output-only resource + representing an actual run of the scan. + Next id: 12 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}:stop", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_stop_scan_run(request, metadata) + pb_request = web_security_scanner.StopScanRunRequest.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 = scan_run.ScanRun() + pb_resp = scan_run.ScanRun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_scan_run(resp) + return resp + + class _UpdateScanConfig(WebSecurityScannerRestStub): + def __hash__(self): + return hash("UpdateScanConfig") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = { + "updateMask": {}, + } + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: web_security_scanner.UpdateScanConfigRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcw_scan_config.ScanConfig: + r"""Call the update scan config method over HTTP. + + Args: + request (~.web_security_scanner.UpdateScanConfigRequest): + The request object. Request for the ``UpdateScanConfigRequest`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcw_scan_config.ScanConfig: + A ScanConfig resource contains the + configurations to launch a scan. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1beta/{scan_config.name=projects/*/scanConfigs/*}", + "body": "scan_config", + }, + ] + request, metadata = self._interceptor.pre_update_scan_config( + request, metadata + ) + pb_request = web_security_scanner.UpdateScanConfigRequest.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 = gcw_scan_config.ScanConfig() + pb_resp = gcw_scan_config.ScanConfig.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_scan_config(resp) + return resp + + @property + def create_scan_config( + self, + ) -> Callable[ + [web_security_scanner.CreateScanConfigRequest], gcw_scan_config.ScanConfig + ]: + # 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._CreateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_scan_config( + self, + ) -> Callable[[web_security_scanner.DeleteScanConfigRequest], 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._DeleteScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_finding( + self, + ) -> Callable[[web_security_scanner.GetFindingRequest], finding.Finding]: + # 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._GetFinding(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_config( + self, + ) -> Callable[[web_security_scanner.GetScanConfigRequest], scan_config.ScanConfig]: + # 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._GetScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_scan_run( + self, + ) -> Callable[[web_security_scanner.GetScanRunRequest], scan_run.ScanRun]: + # 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._GetScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_crawled_urls( + self, + ) -> Callable[ + [web_security_scanner.ListCrawledUrlsRequest], + web_security_scanner.ListCrawledUrlsResponse, + ]: + # 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._ListCrawledUrls(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_findings( + self, + ) -> Callable[ + [web_security_scanner.ListFindingsRequest], + web_security_scanner.ListFindingsResponse, + ]: + # 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._ListFindings(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_finding_type_stats( + self, + ) -> Callable[ + [web_security_scanner.ListFindingTypeStatsRequest], + web_security_scanner.ListFindingTypeStatsResponse, + ]: + # 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._ListFindingTypeStats(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_configs( + self, + ) -> Callable[ + [web_security_scanner.ListScanConfigsRequest], + web_security_scanner.ListScanConfigsResponse, + ]: + # 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._ListScanConfigs(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_scan_runs( + self, + ) -> Callable[ + [web_security_scanner.ListScanRunsRequest], + web_security_scanner.ListScanRunsResponse, + ]: + # 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._ListScanRuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_scan_run( + self, + ) -> Callable[[web_security_scanner.StartScanRunRequest], scan_run.ScanRun]: + # 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._StartScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_scan_run( + self, + ) -> Callable[[web_security_scanner.StopScanRunRequest], scan_run.ScanRun]: + # 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._StopScanRun(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_scan_config( + self, + ) -> Callable[ + [web_security_scanner.UpdateScanConfigRequest], gcw_scan_config.ScanConfig + ]: + # 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._UpdateScanConfig(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("WebSecurityScannerRestTransport",) diff --git a/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py b/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py index 74eada1..be67357 100644 --- a/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.py +++ b/tests/unit/gapic/websecurityscanner_v1/test_web_security_scanner.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 @@ -32,12 +34,15 @@ from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.websecurityscanner_v1.services.web_security_scanner import ( WebSecurityScannerAsyncClient, @@ -108,6 +113,7 @@ def test__get_default_mtls_endpoint(): [ (WebSecurityScannerClient, "grpc"), (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), ], ) def test_web_security_scanner_client_from_service_account_info( @@ -123,7 +129,11 @@ def test_web_security_scanner_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) @pytest.mark.parametrize( @@ -131,6 +141,7 @@ def test_web_security_scanner_client_from_service_account_info( [ (transports.WebSecurityScannerGrpcTransport, "grpc"), (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WebSecurityScannerRestTransport, "rest"), ], ) def test_web_security_scanner_client_service_account_always_use_jwt( @@ -156,6 +167,7 @@ def test_web_security_scanner_client_service_account_always_use_jwt( [ (WebSecurityScannerClient, "grpc"), (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), ], ) def test_web_security_scanner_client_from_service_account_file( @@ -178,13 +190,18 @@ def test_web_security_scanner_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) def test_web_security_scanner_client_get_transport_class(): transport = WebSecurityScannerClient.get_transport_class() available_transports = [ transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerRestTransport, ] assert transport in available_transports @@ -201,6 +218,7 @@ def test_web_security_scanner_client_get_transport_class(): transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", ), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), ], ) @mock.patch.object( @@ -356,6 +374,18 @@ def test_web_security_scanner_client_client_options( "grpc_asyncio", "false", ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + "true", + ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -555,6 +585,7 @@ def test_web_security_scanner_client_get_mtls_endpoint_and_cert_source(client_cl transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", ), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), ], ) def test_web_security_scanner_client_client_options_scopes( @@ -595,6 +626,12 @@ def test_web_security_scanner_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + None, + ), ], ) def test_web_security_scanner_client_client_options_credentials_file( @@ -3722,196 +3759,2327 @@ async def test_list_finding_type_stats_field_headers_async(): ) in kw["metadata"] -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.CreateScanConfigRequest, + dict, + ], +) +def test_create_scan_config_rest(request_type): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["scan_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + "iap_credential": { + "iap_test_service_account_info": { + "target_audience_client_id": "target_audience_client_id_value" + } + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "export_to_security_command_center": 1, + "risk_level": 1, + "managed_scan": True, + "static_ip_scan": True, + "ignore_http_status_errors": True, + } + 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 = scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert ( + response.export_to_security_command_center + == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True - # It is an error to provide an api_key and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options=options, - transport=transport, + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_create_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.CreateScanConfigRequest.pb( + web_security_scanner.CreateScanConfigRequest() ) - - # 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 = WebSecurityScannerClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + 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 = scan_config.ScanConfig.to_json( + scan_config.ScanConfig() ) - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + request = web_security_scanner.CreateScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.create_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) + pre.assert_called_once() + post.assert_called_once() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + +def test_create_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.CreateScanConfigRequest +): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["scan_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + "iap_credential": { + "iap_test_service_account_info": { + "target_audience_client_id": "target_audience_client_id_value" + } + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "export_to_security_command_center": 1, + "risk_level": 1, + "managed_scan": True, + "static_ip_scan": True, + "ignore_http_status_errors": True, + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_scan_config(request) - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), + +def test_create_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - channel = transport.grpc_channel - assert channel @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, + web_security_scanner.DeleteScanConfigRequest, + 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_delete_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2"} + request = request_type(**request_init) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = WebSecurityScannerClient.get_transport_class(transport_name)( + # 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_scan_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), ) - assert transport.kind == transport_name + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "pre_delete_scan_config" + ) as pre: + pre.assert_not_called() + pb_message = web_security_scanner.DeleteScanConfigRequest.pb( + web_security_scanner.DeleteScanConfigRequest() + ) + 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 = web_security_scanner.DeleteScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + pre.assert_called_once() -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. + +def test_delete_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.DeleteScanConfigRequest +): client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) - -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_scan_config", - "delete_scan_config", - "get_scan_config", - "list_scan_configs", - "update_scan_config", - "start_scan_run", - "get_scan_run", - "list_scan_runs", - "stop_scan_run", - "list_crawled_urls", - "get_finding", - "list_findings", - "list_finding_type_stats", +def test_delete_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.GetScanConfigRequest, + dict, + ], +) +def test_get_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2"} + request = request_type(**request_init) -def test_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.WebSecurityScannerTransport( - credentials_file="credentials.json", - quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + # 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 = scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, ) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_config.ScanConfig.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_web_security_scanner_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert ( + response.export_to_security_command_center + == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + ) + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanConfigRequest.pb( + web_security_scanner.GetScanConfigRequest() + ) + 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 = scan_config.ScanConfig.to_json( + scan_config.ScanConfig() + ) + + request = web_security_scanner.GetScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.get_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + +def test_get_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListScanConfigsRequest, + dict, + ], +) +def test_list_scan_configs_rest(request_type): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse( + 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_configs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_scan_configs" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanConfigsRequest.pb( + web_security_scanner.ListScanConfigsRequest() + ) + 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 = ( + web_security_scanner.ListScanConfigsResponse.to_json( + web_security_scanner.ListScanConfigsResponse() + ) + ) + + request = web_security_scanner.ListScanConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanConfigsResponse() + + client.list_scan_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_configs_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListScanConfigsRequest +): + client = WebSecurityScannerClient( + 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_scan_configs(request) + + +def test_list_scan_configs_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token="abc", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token="def", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) for i in results) + + pages = list(client.list_scan_configs(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", + [ + web_security_scanner.UpdateScanConfigRequest, + dict, + ], +) +def test_update_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"scan_config": {"name": "projects/sample1/scanConfigs/sample2"}} + request_init["scan_config"] = { + "name": "projects/sample1/scanConfigs/sample2", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + "iap_credential": { + "iap_test_service_account_info": { + "target_audience_client_id": "target_audience_client_id_value" + } + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "export_to_security_command_center": 1, + "risk_level": 1, + "managed_scan": True, + "static_ip_scan": True, + "ignore_http_status_errors": True, + } + 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 = scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + managed_scan=True, + static_ip_scan=True, + ignore_http_status_errors=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert ( + response.export_to_security_command_center + == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + ) + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + assert response.managed_scan is True + assert response.static_ip_scan is True + assert response.ignore_http_status_errors is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_update_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.UpdateScanConfigRequest.pb( + web_security_scanner.UpdateScanConfigRequest() + ) + 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 = scan_config.ScanConfig.to_json( + scan_config.ScanConfig() + ) + + request = web_security_scanner.UpdateScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.update_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.UpdateScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"scan_config": {"name": "projects/sample1/scanConfigs/sample2"}} + request_init["scan_config"] = { + "name": "projects/sample1/scanConfigs/sample2", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + "iap_credential": { + "iap_test_service_account_info": { + "target_audience_client_id": "target_audience_client_id_value" + } + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "export_to_security_command_center": 1, + "risk_level": 1, + "managed_scan": True, + "static_ip_scan": True, + "ignore_http_status_errors": True, + } + 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_scan_config(request) + + +def test_update_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.StartScanRunRequest, + dict, + ], +) +def test_start_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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.start_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_start_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StartScanRunRequest.pb( + web_security_scanner.StartScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.StartScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.start_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.StartScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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.start_scan_run(request) + + +def test_start_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.GetScanRunRequest, + dict, + ], +) +def test_get_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanRunRequest.pb( + web_security_scanner.GetScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.GetScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.get_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_scan_run(request) + + +def test_get_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListScanRunsRequest, + dict, + ], +) +def test_list_scan_runs_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( + 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 = web_security_scanner.ListScanRunsResponse.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_scan_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_runs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_scan_runs" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanRunsRequest.pb( + web_security_scanner.ListScanRunsRequest() + ) + 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 = web_security_scanner.ListScanRunsResponse.to_json( + web_security_scanner.ListScanRunsResponse() + ) + + request = web_security_scanner.ListScanRunsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanRunsResponse() + + client.list_scan_runs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_runs_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListScanRunsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_scan_runs(request) + + +def test_list_scan_runs_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token="abc", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token="def", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2"} + + pager = client.list_scan_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) for i in results) + + pages = list(client.list_scan_runs(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", + [ + web_security_scanner.StopScanRunRequest, + dict, + ], +) +def test_stop_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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.stop_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_stop_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StopScanRunRequest.pb( + web_security_scanner.StopScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.StopScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.stop_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.StopScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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.stop_scan_run(request) + + +def test_stop_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListCrawledUrlsRequest, + dict, + ], +) +def test_list_crawled_urls_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( + 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 = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crawled_urls_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_crawled_urls" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListCrawledUrlsRequest.pb( + web_security_scanner.ListCrawledUrlsRequest() + ) + 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 = ( + web_security_scanner.ListCrawledUrlsResponse.to_json( + web_security_scanner.ListCrawledUrlsResponse() + ) + ) + + request = web_security_scanner.ListCrawledUrlsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListCrawledUrlsResponse() + + client.list_crawled_urls( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crawled_urls_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListCrawledUrlsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_crawled_urls(request) + + +def test_list_crawled_urls_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token="abc", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token="def", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3" + } + + pager = client.list_crawled_urls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) for i in results) + + pages = list(client.list_crawled_urls(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", + [ + web_security_scanner.GetFindingRequest, + dict, + ], +) +def test_get_finding_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding( + name="name_value", + finding_type="finding_type_value", + severity=finding.Finding.Severity.CRITICAL, + http_method="http_method_value", + fuzzed_url="fuzzed_url_value", + body="body_value", + description="description_value", + reproduction_url="reproduction_url_value", + frame_url="frame_url_value", + final_url="final_url_value", + tracking_id="tracking_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = finding.Finding.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_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.finding_type == "finding_type_value" + assert response.severity == finding.Finding.Severity.CRITICAL + assert response.http_method == "http_method_value" + assert response.fuzzed_url == "fuzzed_url_value" + assert response.body == "body_value" + assert response.description == "description_value" + assert response.reproduction_url == "reproduction_url_value" + assert response.frame_url == "frame_url_value" + assert response.final_url == "final_url_value" + assert response.tracking_id == "tracking_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_finding_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_finding" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_finding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetFindingRequest.pb( + web_security_scanner.GetFindingRequest() + ) + 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 = finding.Finding.to_json(finding.Finding()) + + request = web_security_scanner.GetFindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.get_finding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_finding_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetFindingRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_finding(request) + + +def test_get_finding_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListFindingsRequest, + dict, + ], +) +def test_list_findings_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( + 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 = web_security_scanner.ListFindingsResponse.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_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_findings" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_findings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingsRequest.pb( + web_security_scanner.ListFindingsRequest() + ) + 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 = web_security_scanner.ListFindingsResponse.to_json( + web_security_scanner.ListFindingsResponse() + ) + + request = web_security_scanner.ListFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingsResponse() + + client.list_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListFindingsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token="abc", + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token="def", + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3" + } + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) for i in results) + + pages = list(client.list_findings(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", + [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, + ], +) +def test_list_finding_type_stats_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_finding_type_stats_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb( + web_security_scanner.ListFindingTypeStatsRequest() + ) + 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 = ( + web_security_scanner.ListFindingTypeStatsResponse.to_json( + web_security_scanner.ListFindingTypeStatsResponse() + ) + ) + + request = web_security_scanner.ListFindingTypeStatsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + client.list_finding_type_stats( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_finding_type_stats_rest_bad_request( + transport: str = "rest", + request_type=web_security_scanner.ListFindingTypeStatsRequest, +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_finding_type_stats(request) + + +def test_list_finding_type_stats_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, + ], +) +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 = WebSecurityScannerClient.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_scan_config", + "delete_scan_config", + "get_scan_config", + "list_scan_configs", + "update_scan_config", + "start_scan_run", + "get_scan_run", + "list_scan_runs", + "stop_scan_run", + "list_crawled_urls", + "get_finding", + "list_findings", + "list_finding_type_stats", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.WebSecurityScannerTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_web_security_scanner_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.websecurityscanner_v1.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages" ) as Transport: @@ -3958,6 +6126,7 @@ def test_web_security_scanner_transport_auth_adc(transport_class): [ transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, ], ) def test_web_security_scanner_transport_auth_gdch_credentials(transport_class): @@ -4057,11 +6226,23 @@ def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( ) +def test_web_security_scanner_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.WebSecurityScannerRestTransport( + 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_web_security_scanner_host_no_port(transport_name): @@ -4072,7 +6253,11 @@ def test_web_security_scanner_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) @pytest.mark.parametrize( @@ -4080,6 +6265,7 @@ def test_web_security_scanner_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_web_security_scanner_host_with_port(transport_name): @@ -4090,7 +6276,69 @@ def test_web_security_scanner_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("websecurityscanner.googleapis.com:8000") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_web_security_scanner_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WebSecurityScannerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WebSecurityScannerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_scan_config._session + session2 = client2.transport.create_scan_config._session + assert session1 != session2 + session1 = client1.transport.delete_scan_config._session + session2 = client2.transport.delete_scan_config._session + assert session1 != session2 + session1 = client1.transport.get_scan_config._session + session2 = client2.transport.get_scan_config._session + assert session1 != session2 + session1 = client1.transport.list_scan_configs._session + session2 = client2.transport.list_scan_configs._session + assert session1 != session2 + session1 = client1.transport.update_scan_config._session + session2 = client2.transport.update_scan_config._session + assert session1 != session2 + session1 = client1.transport.start_scan_run._session + session2 = client2.transport.start_scan_run._session + assert session1 != session2 + session1 = client1.transport.get_scan_run._session + session2 = client2.transport.get_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_scan_runs._session + session2 = client2.transport.list_scan_runs._session + assert session1 != session2 + session1 = client1.transport.stop_scan_run._session + session2 = client2.transport.stop_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_crawled_urls._session + session2 = client2.transport.list_crawled_urls._session + assert session1 != session2 + session1 = client1.transport.get_finding._session + session2 = client2.transport.get_finding._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_finding_type_stats._session + session2 = client2.transport.list_finding_type_stats._session + assert session1 != session2 def test_web_security_scanner_grpc_transport_channel(): @@ -4392,6 +6640,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4409,6 +6658,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py b/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py index 76d981d..ba1a23b 100644 --- a/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.py +++ b/tests/unit/gapic/websecurityscanner_v1alpha/test_web_security_scanner.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 @@ -32,12 +34,15 @@ from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.websecurityscanner_v1alpha.services.web_security_scanner import ( WebSecurityScannerAsyncClient, @@ -106,6 +111,7 @@ def test__get_default_mtls_endpoint(): [ (WebSecurityScannerClient, "grpc"), (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), ], ) def test_web_security_scanner_client_from_service_account_info( @@ -121,7 +127,11 @@ def test_web_security_scanner_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) @pytest.mark.parametrize( @@ -129,6 +139,7 @@ def test_web_security_scanner_client_from_service_account_info( [ (transports.WebSecurityScannerGrpcTransport, "grpc"), (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WebSecurityScannerRestTransport, "rest"), ], ) def test_web_security_scanner_client_service_account_always_use_jwt( @@ -154,6 +165,7 @@ def test_web_security_scanner_client_service_account_always_use_jwt( [ (WebSecurityScannerClient, "grpc"), (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), ], ) def test_web_security_scanner_client_from_service_account_file( @@ -176,13 +188,18 @@ def test_web_security_scanner_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) def test_web_security_scanner_client_get_transport_class(): transport = WebSecurityScannerClient.get_transport_class() available_transports = [ transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerRestTransport, ] assert transport in available_transports @@ -199,6 +216,7 @@ def test_web_security_scanner_client_get_transport_class(): transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", ), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), ], ) @mock.patch.object( @@ -354,6 +372,18 @@ def test_web_security_scanner_client_client_options( "grpc_asyncio", "false", ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + "true", + ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -553,6 +583,7 @@ def test_web_security_scanner_client_get_mtls_endpoint_and_cert_source(client_cl transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", ), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), ], ) def test_web_security_scanner_client_client_options_scopes( @@ -593,6 +624,12 @@ def test_web_security_scanner_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + None, + ), ], ) def test_web_security_scanner_client_client_options_credentials_file( @@ -4772,178 +4809,4251 @@ async def test_list_finding_type_stats_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.CreateScanConfigRequest, + dict, + ], +) +def test_create_scan_config_rest(request_type): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["scan_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + }, + } + 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 = gcw_scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcw_scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert response.target_platforms == [ + gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE + ] + + +def test_create_scan_config_rest_required_fields( + request_type=web_security_scanner.CreateScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scan_config._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_scan_config._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 = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options=options, - transport=transport, + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # 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 = gcw_scan_config.ScanConfig.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_scan_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "scanConfig", + ) ) + ) - # 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 = WebSecurityScannerClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_create_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.CreateScanConfigRequest.pb( + web_security_scanner.CreateScanConfigRequest() + ) + 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 = gcw_scan_config.ScanConfig.to_json( + gcw_scan_config.ScanConfig() ) + request = web_security_scanner.CreateScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + client.create_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.CreateScanConfigRequest +): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["scan_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + }, + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + # 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_scan_config(request) + + +def test_create_scan_config_rest_flattened(): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + # 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 = gcw_scan_config.ScanConfig() + + # 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", + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{parent=projects/*}/scanConfigs" % client.transport._host, + args[1], + ) + + +def test_create_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent="parent_value", + scan_config=gcw_scan_config.ScanConfig(name="name_value"), + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -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_create_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + web_security_scanner.DeleteScanConfigRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = WebSecurityScannerClient.get_transport_class(transport_name)( +def test_delete_scan_config_rest(request_type): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_rest_required_fields( + request_type=web_security_scanner.DeleteScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) + 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 -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + response = client.delete_scan_config(request) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_scan_config", - "delete_scan_config", - "get_scan_config", - "list_scan_configs", - "update_scan_config", - "start_scan_run", - "get_scan_run", - "list_scan_runs", - "stop_scan_run", - "list_crawled_urls", - "get_finding", - "list_findings", - "list_finding_type_stats", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - with pytest.raises(NotImplementedError): - transport.close() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +def test_delete_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.delete_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(transport=transport) with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_delete_scan_config" + ) as pre: + pre.assert_not_called() + pb_message = web_security_scanner.DeleteScanConfigRequest.pb( + web_security_scanner.DeleteScanConfigRequest() + ) + 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 = web_security_scanner.DeleteScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.DeleteScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + +def test_delete_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + 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/scanConfigs/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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/scanConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_delete_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name="name_value", + ) + + +def test_delete_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.GetScanConfigRequest, + dict, + ], +) +def test_get_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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 = scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert response.target_platforms == [ + scan_config.ScanConfig.TargetPlatform.APP_ENGINE + ] + + +def test_get_scan_config_rest_required_fields( + request_type=web_security_scanner.GetScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_config.ScanConfig() + # 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 = scan_config.ScanConfig.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_scan_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanConfigRequest.pb( + web_security_scanner.GetScanConfigRequest() + ) + 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 = scan_config.ScanConfig.to_json( + scan_config.ScanConfig() + ) + + request = web_security_scanner.GetScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.get_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + +def test_get_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/scanConfigs/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 = scan_config.ScanConfig.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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{name=projects/*/scanConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_get_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name="name_value", + ) + + +def test_get_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListScanConfigsRequest, + dict, + ], +) +def test_list_scan_configs_rest(request_type): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse( + 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scan_configs_rest_required_fields( + request_type=web_security_scanner.ListScanConfigsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_configs._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_scan_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanConfigsResponse() + # 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scan_configs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scan_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_configs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_scan_configs" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanConfigsRequest.pb( + web_security_scanner.ListScanConfigsRequest() + ) + 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 = ( + web_security_scanner.ListScanConfigsResponse.to_json( + web_security_scanner.ListScanConfigsResponse() + ) + ) + + request = web_security_scanner.ListScanConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanConfigsResponse() + + client.list_scan_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_configs_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListScanConfigsRequest +): + client = WebSecurityScannerClient( + 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_scan_configs(request) + + +def test_list_scan_configs_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse() + + # 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(**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/v1alpha/{parent=projects/*}/scanConfigs" % client.transport._host, + args[1], + ) + + +def test_list_scan_configs_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent="parent_value", + ) + + +def test_list_scan_configs_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token="abc", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token="def", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) for i in results) + + pages = list(client.list_scan_configs(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", + [ + web_security_scanner.UpdateScanConfigRequest, + dict, + ], +) +def test_update_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"scan_config": {"name": "projects/sample1/scanConfigs/sample2"}} + request_init["scan_config"] = { + "name": "projects/sample1/scanConfigs/sample2", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + }, + } + 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 = gcw_scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcw_scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert response.target_platforms == [ + gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE + ] + + +def test_update_scan_config_rest_required_fields( + request_type=web_security_scanner.UpdateScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scan_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # 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 = gcw_scan_config.ScanConfig.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_scan_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "scanConfig", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_update_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.UpdateScanConfigRequest.pb( + web_security_scanner.UpdateScanConfigRequest() + ) + 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 = gcw_scan_config.ScanConfig.to_json( + gcw_scan_config.ScanConfig() + ) + + request = web_security_scanner.UpdateScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() + + client.update_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.UpdateScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"scan_config": {"name": "projects/sample1/scanConfigs/sample2"}} + request_init["scan_config"] = { + "name": "projects/sample1/scanConfigs/sample2", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + }, + } + 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_scan_config(request) + + +def test_update_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + 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 = gcw_scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "scan_config": {"name": "projects/sample1/scanConfigs/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1alpha/{scan_config.name=projects/*/scanConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.StartScanRunRequest, + dict, + ], +) +def test_start_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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.start_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_rest_required_fields( + request_type=web_security_scanner.StartScanRunRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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() + ).start_scan_run._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() + ).start_scan_run._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # 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 = scan_run.ScanRun.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.start_scan_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_start_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.start_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_start_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StartScanRunRequest.pb( + web_security_scanner.StartScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.StartScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.start_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.StartScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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.start_scan_run(request) + + +def test_start_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/scanConfigs/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 = scan_run.ScanRun.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.start_scan_run(**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/v1alpha/{name=projects/*/scanConfigs/*}:start" % client.transport._host, + args[1], + ) + + +def test_start_scan_run_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name="name_value", + ) + + +def test_start_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.GetScanRunRequest, + dict, + ], +) +def test_get_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_rest_required_fields( + request_type=web_security_scanner.GetScanRunRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_run._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_scan_run._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # 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 = scan_run.ScanRun.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_scan_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanRunRequest.pb( + web_security_scanner.GetScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.GetScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.get_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_scan_run(request) + + +def test_get_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.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_scan_run(**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/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_get_scan_run_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_run( + web_security_scanner.GetScanRunRequest(), + name="name_value", + ) + + +def test_get_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListScanRunsRequest, + dict, + ], +) +def test_list_scan_runs_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( + 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 = web_security_scanner.ListScanRunsResponse.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_scan_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scan_runs_rest_required_fields( + request_type=web_security_scanner.ListScanRunsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_runs._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_scan_runs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanRunsResponse() + # 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 = web_security_scanner.ListScanRunsResponse.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_scan_runs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scan_runs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scan_runs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_runs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_scan_runs" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanRunsRequest.pb( + web_security_scanner.ListScanRunsRequest() + ) + 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 = web_security_scanner.ListScanRunsResponse.to_json( + web_security_scanner.ListScanRunsResponse() + ) + + request = web_security_scanner.ListScanRunsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanRunsResponse() + + client.list_scan_runs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_runs_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListScanRunsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_scan_runs(request) + + +def test_list_scan_runs_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanRunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/scanConfigs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListScanRunsResponse.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_scan_runs(**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/v1alpha/{parent=projects/*/scanConfigs/*}/scanRuns" + % client.transport._host, + args[1], + ) + + +def test_list_scan_runs_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent="parent_value", + ) + + +def test_list_scan_runs_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token="abc", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token="def", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2"} + + pager = client.list_scan_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) for i in results) + + pages = list(client.list_scan_runs(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", + [ + web_security_scanner.StopScanRunRequest, + dict, + ], +) +def test_stop_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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.stop_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_rest_required_fields( + request_type=web_security_scanner.StopScanRunRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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() + ).stop_scan_run._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() + ).stop_scan_run._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # 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 = scan_run.ScanRun.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.stop_scan_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_stop_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.stop_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_stop_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StopScanRunRequest.pb( + web_security_scanner.StopScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.StopScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.stop_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.StopScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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.stop_scan_run(request) + + +def test_stop_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.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.stop_scan_run(**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/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*}:stop" + % client.transport._host, + args[1], + ) + + +def test_stop_scan_run_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name="name_value", + ) + + +def test_stop_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListCrawledUrlsRequest, + dict, + ], +) +def test_list_crawled_urls_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( + 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 = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_crawled_urls_rest_required_fields( + request_type=web_security_scanner.ListCrawledUrlsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_crawled_urls._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_crawled_urls._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListCrawledUrlsResponse() + # 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 = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_crawled_urls_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_crawled_urls._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crawled_urls_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_crawled_urls" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListCrawledUrlsRequest.pb( + web_security_scanner.ListCrawledUrlsRequest() + ) + 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 = ( + web_security_scanner.ListCrawledUrlsResponse.to_json( + web_security_scanner.ListCrawledUrlsResponse() + ) + ) + + request = web_security_scanner.ListCrawledUrlsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListCrawledUrlsResponse() + + client.list_crawled_urls( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crawled_urls_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListCrawledUrlsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_crawled_urls(request) + + +def test_list_crawled_urls_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListCrawledUrlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(**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/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls" + % client.transport._host, + args[1], + ) + + +def test_list_crawled_urls_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent="parent_value", + ) + + +def test_list_crawled_urls_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token="abc", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token="def", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3" + } + + pager = client.list_crawled_urls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) for i in results) + + pages = list(client.list_crawled_urls(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", + [ + web_security_scanner.GetFindingRequest, + dict, + ], +) +def test_get_finding_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding( + name="name_value", + finding_type=finding.Finding.FindingType.MIXED_CONTENT, + http_method="http_method_value", + fuzzed_url="fuzzed_url_value", + body="body_value", + description="description_value", + reproduction_url="reproduction_url_value", + frame_url="frame_url_value", + final_url="final_url_value", + tracking_id="tracking_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = finding.Finding.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_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.finding_type == finding.Finding.FindingType.MIXED_CONTENT + assert response.http_method == "http_method_value" + assert response.fuzzed_url == "fuzzed_url_value" + assert response.body == "body_value" + assert response.description == "description_value" + assert response.reproduction_url == "reproduction_url_value" + assert response.frame_url == "frame_url_value" + assert response.final_url == "final_url_value" + assert response.tracking_id == "tracking_id_value" + + +def test_get_finding_rest_required_fields( + request_type=web_security_scanner.GetFindingRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_finding._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_finding._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + # 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 = finding.Finding.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_finding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_finding_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_finding_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_finding" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_finding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetFindingRequest.pb( + web_security_scanner.GetFindingRequest() + ) + 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 = finding.Finding.to_json(finding.Finding()) + + request = web_security_scanner.GetFindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.get_finding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_finding_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetFindingRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_finding(request) + + +def test_get_finding_rest_flattened(): + client = WebSecurityScannerClient( + 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 = finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = finding.Finding.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_finding(**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/v1alpha/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_finding_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_finding( + web_security_scanner.GetFindingRequest(), + name="name_value", + ) + + +def test_get_finding_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListFindingsRequest, + dict, + ], +) +def test_list_findings_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( + 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 = web_security_scanner.ListFindingsResponse.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_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_findings_rest_required_fields( + request_type=web_security_scanner.ListFindingsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "filter" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["filter"] = "filter_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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" + assert "filter" in jsonified_request + assert jsonified_request["filter"] == "filter_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingsResponse() + # 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 = web_security_scanner.ListFindingsResponse.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_findings(request) + + expected_params = [ + ( + "filter", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_findings_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set( + ( + "parent", + "filter", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_findings" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_findings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingsRequest.pb( + web_security_scanner.ListFindingsRequest() + ) + 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 = web_security_scanner.ListFindingsResponse.to_json( + web_security_scanner.ListFindingsResponse() + ) + + request = web_security_scanner.ListFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingsResponse() + + client.list_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListFindingsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + filter="filter_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 = web_security_scanner.ListFindingsResponse.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_findings(**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/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings" + % client.transport._host, + args[1], + ) + + +def test_list_findings_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_findings( + web_security_scanner.ListFindingsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_findings_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token="abc", + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token="def", + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3" + } + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) for i in results) + + pages = list(client.list_findings(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", + [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, + ], +) +def test_list_finding_type_stats_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_rest_required_fields( + request_type=web_security_scanner.ListFindingTypeStatsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_finding_type_stats._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_finding_type_stats._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingTypeStatsResponse() + # 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 = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_finding_type_stats_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_finding_type_stats._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_finding_type_stats_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb( + web_security_scanner.ListFindingTypeStatsRequest() + ) + 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 = ( + web_security_scanner.ListFindingTypeStatsResponse.to_json( + web_security_scanner.ListFindingTypeStatsResponse() + ) + ) + + request = web_security_scanner.ListFindingTypeStatsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + client.list_finding_type_stats( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_finding_type_stats_rest_bad_request( + transport: str = "rest", + request_type=web_security_scanner.ListFindingTypeStatsRequest, +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_finding_type_stats(request) + + +def test_list_finding_type_stats_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListFindingTypeStatsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(**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/v1alpha/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats" + % client.transport._host, + args[1], + ) + + +def test_list_finding_type_stats_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent="parent_value", + ) + + +def test_list_finding_type_stats_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, + ], +) +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 = WebSecurityScannerClient.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_scan_config", + "delete_scan_config", + "get_scan_config", + "list_scan_configs", + "update_scan_config", + "start_scan_run", + "get_scan_run", + "list_scan_runs", + "stop_scan_run", + "list_crawled_urls", + "get_finding", + "list_findings", + "list_finding_type_stats", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( "google.cloud.websecurityscanner_v1alpha.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None @@ -5008,6 +9118,7 @@ def test_web_security_scanner_transport_auth_adc(transport_class): [ transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, ], ) def test_web_security_scanner_transport_auth_gdch_credentials(transport_class): @@ -5107,11 +9218,23 @@ def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( ) +def test_web_security_scanner_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.WebSecurityScannerRestTransport( + 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_web_security_scanner_host_no_port(transport_name): @@ -5122,7 +9245,11 @@ def test_web_security_scanner_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) @pytest.mark.parametrize( @@ -5130,6 +9257,7 @@ def test_web_security_scanner_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_web_security_scanner_host_with_port(transport_name): @@ -5140,7 +9268,69 @@ def test_web_security_scanner_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("websecurityscanner.googleapis.com:8000") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_web_security_scanner_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WebSecurityScannerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WebSecurityScannerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_scan_config._session + session2 = client2.transport.create_scan_config._session + assert session1 != session2 + session1 = client1.transport.delete_scan_config._session + session2 = client2.transport.delete_scan_config._session + assert session1 != session2 + session1 = client1.transport.get_scan_config._session + session2 = client2.transport.get_scan_config._session + assert session1 != session2 + session1 = client1.transport.list_scan_configs._session + session2 = client2.transport.list_scan_configs._session + assert session1 != session2 + session1 = client1.transport.update_scan_config._session + session2 = client2.transport.update_scan_config._session + assert session1 != session2 + session1 = client1.transport.start_scan_run._session + session2 = client2.transport.start_scan_run._session + assert session1 != session2 + session1 = client1.transport.get_scan_run._session + session2 = client2.transport.get_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_scan_runs._session + session2 = client2.transport.list_scan_runs._session + assert session1 != session2 + session1 = client1.transport.stop_scan_run._session + session2 = client2.transport.stop_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_crawled_urls._session + session2 = client2.transport.list_crawled_urls._session + assert session1 != session2 + session1 = client1.transport.get_finding._session + session2 = client2.transport.get_finding._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_finding_type_stats._session + session2 = client2.transport.list_finding_type_stats._session + assert session1 != session2 def test_web_security_scanner_grpc_transport_channel(): @@ -5493,6 +9683,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -5510,6 +9701,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py b/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py index ddf08b5..b2aadb3 100644 --- a/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.py +++ b/tests/unit/gapic/websecurityscanner_v1beta/test_web_security_scanner.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 @@ -32,12 +34,15 @@ from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.websecurityscanner_v1beta.services.web_security_scanner import ( WebSecurityScannerAsyncClient, @@ -112,6 +117,7 @@ def test__get_default_mtls_endpoint(): [ (WebSecurityScannerClient, "grpc"), (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), ], ) def test_web_security_scanner_client_from_service_account_info( @@ -127,7 +133,11 @@ def test_web_security_scanner_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) @pytest.mark.parametrize( @@ -135,6 +145,7 @@ def test_web_security_scanner_client_from_service_account_info( [ (transports.WebSecurityScannerGrpcTransport, "grpc"), (transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.WebSecurityScannerRestTransport, "rest"), ], ) def test_web_security_scanner_client_service_account_always_use_jwt( @@ -160,6 +171,7 @@ def test_web_security_scanner_client_service_account_always_use_jwt( [ (WebSecurityScannerClient, "grpc"), (WebSecurityScannerAsyncClient, "grpc_asyncio"), + (WebSecurityScannerClient, "rest"), ], ) def test_web_security_scanner_client_from_service_account_file( @@ -182,13 +194,18 @@ def test_web_security_scanner_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) def test_web_security_scanner_client_get_transport_class(): transport = WebSecurityScannerClient.get_transport_class() available_transports = [ transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerRestTransport, ] assert transport in available_transports @@ -205,6 +222,7 @@ def test_web_security_scanner_client_get_transport_class(): transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", ), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), ], ) @mock.patch.object( @@ -360,6 +378,18 @@ def test_web_security_scanner_client_client_options( "grpc_asyncio", "false", ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + "true", + ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -559,6 +589,7 @@ def test_web_security_scanner_client_get_mtls_endpoint_and_cert_source(client_cl transports.WebSecurityScannerGrpcAsyncIOTransport, "grpc_asyncio", ), + (WebSecurityScannerClient, transports.WebSecurityScannerRestTransport, "rest"), ], ) def test_web_security_scanner_client_client_options_scopes( @@ -599,6 +630,12 @@ def test_web_security_scanner_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + WebSecurityScannerClient, + transports.WebSecurityScannerRestTransport, + "rest", + None, + ), ], ) def test_web_security_scanner_client_client_options_credentials_file( @@ -4820,176 +4857,4302 @@ async def test_list_finding_type_stats_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.CreateScanConfigRequest, + dict, + ], +) +def test_create_scan_config_rest(request_type): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["scan_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "export_to_security_command_center": 1, + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + "error_trace": { + "code": 1, + "scan_config_error": {"code": 1, "field_name": "field_name_value"}, + "most_common_http_error_code": 2893, + }, + "warning_traces": [{"code": 1}], + }, + "risk_level": 1, + } + 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 = gcw_scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcw_scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert response.target_platforms == [ + gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE + ] + assert ( + response.export_to_security_command_center + == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_create_scan_config_rest_required_fields( + request_type=web_security_scanner.CreateScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_scan_config._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_scan_config._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 = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options=options, - transport=transport, + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # 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 = gcw_scan_config.ScanConfig.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_scan_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "scanConfig", + ) ) + ) - # 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 = WebSecurityScannerClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) - # It is an error to provide scopes and a transport instance. - transport = transports.WebSecurityScannerGrpcTransport( +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), ) - with pytest.raises(ValueError): - client = WebSecurityScannerClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_create_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_create_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.CreateScanConfigRequest.pb( + web_security_scanner.CreateScanConfigRequest() + ) + 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 = gcw_scan_config.ScanConfig.to_json( + gcw_scan_config.ScanConfig() ) + request = web_security_scanner.CreateScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + client.create_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.CreateScanConfigRequest +): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = WebSecurityScannerClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1"} + request_init["scan_config"] = { + "name": "name_value", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "export_to_security_command_center": 1, + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + "error_trace": { + "code": 1, + "scan_config_error": {"code": 1, "field_name": "field_name_value"}, + "most_common_http_error_code": 2893, + }, + "warning_traces": [{"code": 1}], + }, + "risk_level": 1, + } + 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_scan_config(request) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.WebSecurityScannerGrpcTransport( + +def test_create_scan_config_rest_flattened(): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + # 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 = gcw_scan_config.ScanConfig() + + # 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", + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*}/scanConfigs" % client.transport._host, + args[1], + ) + + +def test_create_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_scan_config( + web_security_scanner.CreateScanConfigRequest(), + parent="parent_value", + scan_config=gcw_scan_config.ScanConfig(name="name_value"), + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.WebSecurityScannerGrpcTransport, - transports.WebSecurityScannerGrpcAsyncIOTransport, - ], -) -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_create_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + web_security_scanner.DeleteScanConfigRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = WebSecurityScannerClient.get_transport_class(transport_name)( +def test_delete_scan_config_rest(request_type): + client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_scan_config_rest_required_fields( + request_type=web_security_scanner.DeleteScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = WebSecurityScannerClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.WebSecurityScannerGrpcTransport, - ) + 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 -def test_web_security_scanner_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value -def test_web_security_scanner_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.WebSecurityScannerTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) + response = client.delete_scan_config(request) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_scan_config", - "delete_scan_config", - "get_scan_config", - "list_scan_configs", - "update_scan_config", - "start_scan_run", - "get_scan_run", - "list_scan_runs", - "stop_scan_run", - "list_crawled_urls", - "get_finding", - "list_findings", - "list_finding_type_stats", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params - with pytest.raises(NotImplementedError): - transport.close() - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +def test_delete_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + unset_fields = transport.delete_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_web_security_scanner_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "pre_delete_scan_config" + ) as pre: + pre.assert_not_called() + pb_message = web_security_scanner.DeleteScanConfigRequest.pb( + web_security_scanner.DeleteScanConfigRequest() + ) + 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 = web_security_scanner.DeleteScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.DeleteScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + +def test_delete_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + 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/scanConfigs/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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/scanConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_delete_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_config( + web_security_scanner.DeleteScanConfigRequest(), + name="name_value", + ) + + +def test_delete_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.GetScanConfigRequest, + dict, + ], +) +def test_get_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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 = scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + target_platforms=[scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=scan_config.ScanConfig.RiskLevel.NORMAL, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert response.target_platforms == [ + scan_config.ScanConfig.TargetPlatform.APP_ENGINE + ] + assert ( + response.export_to_security_command_center + == scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + ) + assert response.risk_level == scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_get_scan_config_rest_required_fields( + request_type=web_security_scanner.GetScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_config.ScanConfig() + # 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 = scan_config.ScanConfig.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_scan_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanConfigRequest.pb( + web_security_scanner.GetScanConfigRequest() + ) + 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 = scan_config.ScanConfig.to_json( + scan_config.ScanConfig() + ) + + request = web_security_scanner.GetScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_config.ScanConfig() + + client.get_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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_scan_config(request) + + +def test_get_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/scanConfigs/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 = scan_config.ScanConfig.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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/scanConfigs/*}" % client.transport._host, + args[1], + ) + + +def test_get_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_config( + web_security_scanner.GetScanConfigRequest(), + name="name_value", + ) + + +def test_get_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListScanConfigsRequest, + dict, + ], +) +def test_list_scan_configs_rest(request_type): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse( + 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanConfigsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scan_configs_rest_required_fields( + request_type=web_security_scanner.ListScanConfigsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_configs._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_scan_configs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanConfigsResponse() + # 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scan_configs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scan_configs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_configs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_scan_configs" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_scan_configs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanConfigsRequest.pb( + web_security_scanner.ListScanConfigsRequest() + ) + 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 = ( + web_security_scanner.ListScanConfigsResponse.to_json( + web_security_scanner.ListScanConfigsResponse() + ) + ) + + request = web_security_scanner.ListScanConfigsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanConfigsResponse() + + client.list_scan_configs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_configs_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListScanConfigsRequest +): + client = WebSecurityScannerClient( + 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_scan_configs(request) + + +def test_list_scan_configs_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanConfigsResponse() + + # 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 = web_security_scanner.ListScanConfigsResponse.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_scan_configs(**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/v1beta/{parent=projects/*}/scanConfigs" % client.transport._host, + args[1], + ) + + +def test_list_scan_configs_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_configs( + web_security_scanner.ListScanConfigsRequest(), + parent="parent_value", + ) + + +def test_list_scan_configs_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + next_page_token="abc", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[], + next_page_token="def", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListScanConfigsResponse( + scan_configs=[ + scan_config.ScanConfig(), + scan_config.ScanConfig(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListScanConfigsResponse.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_scan_configs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_config.ScanConfig) for i in results) + + pages = list(client.list_scan_configs(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", + [ + web_security_scanner.UpdateScanConfigRequest, + dict, + ], +) +def test_update_scan_config_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"scan_config": {"name": "projects/sample1/scanConfigs/sample2"}} + request_init["scan_config"] = { + "name": "projects/sample1/scanConfigs/sample2", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "export_to_security_command_center": 1, + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + "error_trace": { + "code": 1, + "scan_config_error": {"code": 1, "field_name": "field_name_value"}, + "most_common_http_error_code": 2893, + }, + "warning_traces": [{"code": 1}], + }, + "risk_level": 1, + } + 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 = gcw_scan_config.ScanConfig( + name="name_value", + display_name="display_name_value", + max_qps=761, + starting_urls=["starting_urls_value"], + user_agent=gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX, + blacklist_patterns=["blacklist_patterns_value"], + target_platforms=[gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE], + export_to_security_command_center=gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED, + risk_level=gcw_scan_config.ScanConfig.RiskLevel.NORMAL, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcw_scan_config.ScanConfig.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_scan_config(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcw_scan_config.ScanConfig) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.max_qps == 761 + assert response.starting_urls == ["starting_urls_value"] + assert response.user_agent == gcw_scan_config.ScanConfig.UserAgent.CHROME_LINUX + assert response.blacklist_patterns == ["blacklist_patterns_value"] + assert response.target_platforms == [ + gcw_scan_config.ScanConfig.TargetPlatform.APP_ENGINE + ] + assert ( + response.export_to_security_command_center + == gcw_scan_config.ScanConfig.ExportToSecurityCommandCenter.ENABLED + ) + assert response.risk_level == gcw_scan_config.ScanConfig.RiskLevel.NORMAL + + +def test_update_scan_config_rest_required_fields( + request_type=web_security_scanner.UpdateScanConfigRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scan_config._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_scan_config._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = gcw_scan_config.ScanConfig() + # 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 = gcw_scan_config.ScanConfig.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_scan_config(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_scan_config_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_scan_config._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "scanConfig", + "updateMask", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_scan_config_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_update_scan_config" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_update_scan_config" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.UpdateScanConfigRequest.pb( + web_security_scanner.UpdateScanConfigRequest() + ) + 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 = gcw_scan_config.ScanConfig.to_json( + gcw_scan_config.ScanConfig() + ) + + request = web_security_scanner.UpdateScanConfigRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcw_scan_config.ScanConfig() + + client.update_scan_config( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_scan_config_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.UpdateScanConfigRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"scan_config": {"name": "projects/sample1/scanConfigs/sample2"}} + request_init["scan_config"] = { + "name": "projects/sample1/scanConfigs/sample2", + "display_name": "display_name_value", + "max_qps": 761, + "starting_urls": ["starting_urls_value1", "starting_urls_value2"], + "authentication": { + "google_account": { + "username": "username_value", + "password": "password_value", + }, + "custom_account": { + "username": "username_value", + "password": "password_value", + "login_url": "login_url_value", + }, + }, + "user_agent": 1, + "blacklist_patterns": [ + "blacklist_patterns_value1", + "blacklist_patterns_value2", + ], + "schedule": { + "schedule_time": {"seconds": 751, "nanos": 543}, + "interval_duration_days": 2362, + }, + "target_platforms": [1], + "export_to_security_command_center": 1, + "latest_run": { + "name": "name_value", + "execution_state": 1, + "result_state": 1, + "start_time": {}, + "end_time": {}, + "urls_crawled_count": 1935, + "urls_tested_count": 1846, + "has_vulnerabilities": True, + "progress_percent": 1733, + "error_trace": { + "code": 1, + "scan_config_error": {"code": 1, "field_name": "field_name_value"}, + "most_common_http_error_code": 2893, + }, + "warning_traces": [{"code": 1}], + }, + "risk_level": 1, + } + 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_scan_config(request) + + +def test_update_scan_config_rest_flattened(): + client = WebSecurityScannerClient( + 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 = gcw_scan_config.ScanConfig() + + # get arguments that satisfy an http rule for this method + sample_request = { + "scan_config": {"name": "projects/sample1/scanConfigs/sample2"} + } + + # get truthy value for each flattened field + mock_args = dict( + scan_config=gcw_scan_config.ScanConfig(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 = gcw_scan_config.ScanConfig.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_scan_config(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{scan_config.name=projects/*/scanConfigs/*}" + % client.transport._host, + args[1], + ) + + +def test_update_scan_config_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_config( + web_security_scanner.UpdateScanConfigRequest(), + scan_config=gcw_scan_config.ScanConfig(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_scan_config_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.StartScanRunRequest, + dict, + ], +) +def test_start_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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.start_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_start_scan_run_rest_required_fields( + request_type=web_security_scanner.StartScanRunRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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() + ).start_scan_run._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() + ).start_scan_run._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # 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 = scan_run.ScanRun.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.start_scan_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_start_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.start_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_start_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_start_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StartScanRunRequest.pb( + web_security_scanner.StartScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.StartScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.start_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.StartScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/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.start_scan_run(request) + + +def test_start_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/scanConfigs/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 = scan_run.ScanRun.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.start_scan_run(**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/v1beta/{name=projects/*/scanConfigs/*}:start" % client.transport._host, + args[1], + ) + + +def test_start_scan_run_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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.start_scan_run( + web_security_scanner.StartScanRunRequest(), + name="name_value", + ) + + +def test_start_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.GetScanRunRequest, + dict, + ], +) +def test_get_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_get_scan_run_rest_required_fields( + request_type=web_security_scanner.GetScanRunRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_run._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_scan_run._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # 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 = scan_run.ScanRun.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_scan_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetScanRunRequest.pb( + web_security_scanner.GetScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.GetScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.get_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_scan_run(request) + + +def test_get_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.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_scan_run(**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/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}" + % client.transport._host, + args[1], + ) + + +def test_get_scan_run_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_run( + web_security_scanner.GetScanRunRequest(), + name="name_value", + ) + + +def test_get_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListScanRunsRequest, + dict, + ], +) +def test_list_scan_runs_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/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 = web_security_scanner.ListScanRunsResponse( + 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 = web_security_scanner.ListScanRunsResponse.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_scan_runs(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListScanRunsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_scan_runs_rest_required_fields( + request_type=web_security_scanner.ListScanRunsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_scan_runs._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_scan_runs._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListScanRunsResponse() + # 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 = web_security_scanner.ListScanRunsResponse.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_scan_runs(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_scan_runs_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_scan_runs._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_scan_runs_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_scan_runs" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_scan_runs" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListScanRunsRequest.pb( + web_security_scanner.ListScanRunsRequest() + ) + 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 = web_security_scanner.ListScanRunsResponse.to_json( + web_security_scanner.ListScanRunsResponse() + ) + + request = web_security_scanner.ListScanRunsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListScanRunsResponse() + + client.list_scan_runs( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_scan_runs_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListScanRunsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_scan_runs(request) + + +def test_list_scan_runs_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListScanRunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/scanConfigs/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListScanRunsResponse.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_scan_runs(**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/v1beta/{parent=projects/*/scanConfigs/*}/scanRuns" + % client.transport._host, + args[1], + ) + + +def test_list_scan_runs_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_scan_runs( + web_security_scanner.ListScanRunsRequest(), + parent="parent_value", + ) + + +def test_list_scan_runs_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + next_page_token="abc", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[], + next_page_token="def", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListScanRunsResponse( + scan_runs=[ + scan_run.ScanRun(), + scan_run.ScanRun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListScanRunsResponse.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/scanConfigs/sample2"} + + pager = client.list_scan_runs(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, scan_run.ScanRun) for i in results) + + pages = list(client.list_scan_runs(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", + [ + web_security_scanner.StopScanRunRequest, + dict, + ], +) +def test_stop_scan_run_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun( + name="name_value", + execution_state=scan_run.ScanRun.ExecutionState.QUEUED, + result_state=scan_run.ScanRun.ResultState.SUCCESS, + urls_crawled_count=1935, + urls_tested_count=1846, + has_vulnerabilities=True, + progress_percent=1733, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = scan_run.ScanRun.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.stop_scan_run(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, scan_run.ScanRun) + assert response.name == "name_value" + assert response.execution_state == scan_run.ScanRun.ExecutionState.QUEUED + assert response.result_state == scan_run.ScanRun.ResultState.SUCCESS + assert response.urls_crawled_count == 1935 + assert response.urls_tested_count == 1846 + assert response.has_vulnerabilities is True + assert response.progress_percent == 1733 + + +def test_stop_scan_run_rest_required_fields( + request_type=web_security_scanner.StopScanRunRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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() + ).stop_scan_run._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() + ).stop_scan_run._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = scan_run.ScanRun() + # 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 = scan_run.ScanRun.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.stop_scan_run(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_stop_scan_run_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.stop_scan_run._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_scan_run_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_stop_scan_run" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_stop_scan_run" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.StopScanRunRequest.pb( + web_security_scanner.StopScanRunRequest() + ) + 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 = scan_run.ScanRun.to_json(scan_run.ScanRun()) + + request = web_security_scanner.StopScanRunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = scan_run.ScanRun() + + client.stop_scan_run( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_scan_run_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.StopScanRunRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/scanConfigs/sample2/scanRuns/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.stop_scan_run(request) + + +def test_stop_scan_run_rest_flattened(): + client = WebSecurityScannerClient( + 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 = scan_run.ScanRun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/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 = scan_run.ScanRun.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.stop_scan_run(**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/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*}:stop" + % client.transport._host, + args[1], + ) + + +def test_stop_scan_run_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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.stop_scan_run( + web_security_scanner.StopScanRunRequest(), + name="name_value", + ) + + +def test_stop_scan_run_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListCrawledUrlsRequest, + dict, + ], +) +def test_list_crawled_urls_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListCrawledUrlsResponse( + 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 = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCrawledUrlsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_crawled_urls_rest_required_fields( + request_type=web_security_scanner.ListCrawledUrlsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_crawled_urls._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_crawled_urls._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListCrawledUrlsResponse() + # 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 = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_crawled_urls_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_crawled_urls._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_crawled_urls_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_crawled_urls" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_crawled_urls" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListCrawledUrlsRequest.pb( + web_security_scanner.ListCrawledUrlsRequest() + ) + 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 = ( + web_security_scanner.ListCrawledUrlsResponse.to_json( + web_security_scanner.ListCrawledUrlsResponse() + ) + ) + + request = web_security_scanner.ListCrawledUrlsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListCrawledUrlsResponse() + + client.list_crawled_urls( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_crawled_urls_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListCrawledUrlsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_crawled_urls(request) + + +def test_list_crawled_urls_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListCrawledUrlsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListCrawledUrlsResponse.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_crawled_urls(**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/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/crawledUrls" + % client.transport._host, + args[1], + ) + + +def test_list_crawled_urls_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_crawled_urls( + web_security_scanner.ListCrawledUrlsRequest(), + parent="parent_value", + ) + + +def test_list_crawled_urls_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + next_page_token="abc", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[], + next_page_token="def", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListCrawledUrlsResponse( + crawled_urls=[ + crawled_url.CrawledUrl(), + crawled_url.CrawledUrl(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListCrawledUrlsResponse.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/scanConfigs/sample2/scanRuns/sample3" + } + + pager = client.list_crawled_urls(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, crawled_url.CrawledUrl) for i in results) + + pages = list(client.list_crawled_urls(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", + [ + web_security_scanner.GetFindingRequest, + dict, + ], +) +def test_get_finding_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = finding.Finding( + name="name_value", + finding_type="finding_type_value", + http_method="http_method_value", + fuzzed_url="fuzzed_url_value", + body="body_value", + description="description_value", + reproduction_url="reproduction_url_value", + frame_url="frame_url_value", + final_url="final_url_value", + tracking_id="tracking_id_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = finding.Finding.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_finding(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, finding.Finding) + assert response.name == "name_value" + assert response.finding_type == "finding_type_value" + assert response.http_method == "http_method_value" + assert response.fuzzed_url == "fuzzed_url_value" + assert response.body == "body_value" + assert response.description == "description_value" + assert response.reproduction_url == "reproduction_url_value" + assert response.frame_url == "frame_url_value" + assert response.final_url == "final_url_value" + assert response.tracking_id == "tracking_id_value" + + +def test_get_finding_rest_required_fields( + request_type=web_security_scanner.GetFindingRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_finding._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_finding._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = finding.Finding() + # 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 = finding.Finding.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_finding(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_finding_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_finding._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_finding_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_get_finding" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_get_finding" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.GetFindingRequest.pb( + web_security_scanner.GetFindingRequest() + ) + 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 = finding.Finding.to_json(finding.Finding()) + + request = web_security_scanner.GetFindingRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = finding.Finding() + + client.get_finding( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_finding_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.GetFindingRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_finding(request) + + +def test_get_finding_rest_flattened(): + client = WebSecurityScannerClient( + 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 = finding.Finding() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/scanConfigs/sample2/scanRuns/sample3/findings/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = finding.Finding.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_finding(**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/v1beta/{name=projects/*/scanConfigs/*/scanRuns/*/findings/*}" + % client.transport._host, + args[1], + ) + + +def test_get_finding_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_finding( + web_security_scanner.GetFindingRequest(), + name="name_value", + ) + + +def test_get_finding_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + web_security_scanner.ListFindingsRequest, + dict, + ], +) +def test_list_findings_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingsResponse( + 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 = web_security_scanner.ListFindingsResponse.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_findings(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListFindingsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_findings_rest_required_fields( + request_type=web_security_scanner.ListFindingsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["filter"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "filter" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_findings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "filter" in jsonified_request + assert jsonified_request["filter"] == request_init["filter"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["filter"] = "filter_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_findings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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" + assert "filter" in jsonified_request + assert jsonified_request["filter"] == "filter_value" + + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingsResponse() + # 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 = web_security_scanner.ListFindingsResponse.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_findings(request) + + expected_params = [ + ( + "filter", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_findings_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_findings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set( + ( + "parent", + "filter", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_findings_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_findings" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_findings" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingsRequest.pb( + web_security_scanner.ListFindingsRequest() + ) + 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 = web_security_scanner.ListFindingsResponse.to_json( + web_security_scanner.ListFindingsResponse() + ) + + request = web_security_scanner.ListFindingsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingsResponse() + + client.list_findings( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_findings_rest_bad_request( + transport: str = "rest", request_type=web_security_scanner.ListFindingsRequest +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_findings(request) + + +def test_list_findings_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListFindingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + filter="filter_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 = web_security_scanner.ListFindingsResponse.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_findings(**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/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findings" + % client.transport._host, + args[1], + ) + + +def test_list_findings_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_findings( + web_security_scanner.ListFindingsRequest(), + parent="parent_value", + filter="filter_value", + ) + + +def test_list_findings_rest_pager(transport: str = "rest"): + client = WebSecurityScannerClient( + 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 = ( + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + finding.Finding(), + ], + next_page_token="abc", + ), + web_security_scanner.ListFindingsResponse( + findings=[], + next_page_token="def", + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + ], + next_page_token="ghi", + ), + web_security_scanner.ListFindingsResponse( + findings=[ + finding.Finding(), + finding.Finding(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + web_security_scanner.ListFindingsResponse.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/scanConfigs/sample2/scanRuns/sample3" + } + + pager = client.list_findings(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, finding.Finding) for i in results) + + pages = list(client.list_findings(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", + [ + web_security_scanner.ListFindingTypeStatsRequest, + dict, + ], +) +def test_list_finding_type_stats_rest(request_type): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/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 = web_security_scanner.ListFindingTypeStatsResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, web_security_scanner.ListFindingTypeStatsResponse) + + +def test_list_finding_type_stats_rest_required_fields( + request_type=web_security_scanner.ListFindingTypeStatsRequest, +): + transport_class = transports.WebSecurityScannerRestTransport + + 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_finding_type_stats._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_finding_type_stats._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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = web_security_scanner.ListFindingTypeStatsResponse() + # 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 = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_finding_type_stats_rest_unset_required_fields(): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_finding_type_stats._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_finding_type_stats_rest_interceptors(null_interceptor): + transport = transports.WebSecurityScannerRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.WebSecurityScannerRestInterceptor(), + ) + client = WebSecurityScannerClient(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.WebSecurityScannerRestInterceptor, "post_list_finding_type_stats" + ) as post, mock.patch.object( + transports.WebSecurityScannerRestInterceptor, "pre_list_finding_type_stats" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = web_security_scanner.ListFindingTypeStatsRequest.pb( + web_security_scanner.ListFindingTypeStatsRequest() + ) + 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 = ( + web_security_scanner.ListFindingTypeStatsResponse.to_json( + web_security_scanner.ListFindingTypeStatsResponse() + ) + ) + + request = web_security_scanner.ListFindingTypeStatsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = web_security_scanner.ListFindingTypeStatsResponse() + + client.list_finding_type_stats( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_finding_type_stats_rest_bad_request( + transport: str = "rest", + request_type=web_security_scanner.ListFindingTypeStatsRequest, +): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_finding_type_stats(request) + + +def test_list_finding_type_stats_rest_flattened(): + client = WebSecurityScannerClient( + 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 = web_security_scanner.ListFindingTypeStatsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/scanConfigs/sample2/scanRuns/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = web_security_scanner.ListFindingTypeStatsResponse.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_finding_type_stats(**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/v1beta/{parent=projects/*/scanConfigs/*/scanRuns/*}/findingTypeStats" + % client.transport._host, + args[1], + ) + + +def test_list_finding_type_stats_rest_flattened_error(transport: str = "rest"): + client = WebSecurityScannerClient( + 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_finding_type_stats( + web_security_scanner.ListFindingTypeStatsRequest(), + parent="parent_value", + ) + + +def test_list_finding_type_stats_rest_error(): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + 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 = WebSecurityScannerClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = WebSecurityScannerClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = WebSecurityScannerClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.WebSecurityScannerGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.WebSecurityScannerGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.WebSecurityScannerGrpcTransport, + transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, + ], +) +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 = WebSecurityScannerClient.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 = WebSecurityScannerClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.WebSecurityScannerGrpcTransport, + ) + + +def test_web_security_scanner_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_web_security_scanner_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.WebSecurityScannerTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_scan_config", + "delete_scan_config", + "get_scan_config", + "list_scan_configs", + "update_scan_config", + "start_scan_run", + "get_scan_run", + "list_scan_runs", + "stop_scan_run", + "list_crawled_urls", + "get_finding", + "list_findings", + "list_finding_type_stats", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_web_security_scanner_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.websecurityscanner_v1beta.services.web_security_scanner.transports.WebSecurityScannerTransport._prep_wrapped_messages" @@ -5056,6 +9219,7 @@ def test_web_security_scanner_transport_auth_adc(transport_class): [ transports.WebSecurityScannerGrpcTransport, transports.WebSecurityScannerGrpcAsyncIOTransport, + transports.WebSecurityScannerRestTransport, ], ) def test_web_security_scanner_transport_auth_gdch_credentials(transport_class): @@ -5155,11 +9319,23 @@ def test_web_security_scanner_grpc_transport_client_cert_source_for_mtls( ) +def test_web_security_scanner_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.WebSecurityScannerRestTransport( + 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_web_security_scanner_host_no_port(transport_name): @@ -5170,7 +9346,11 @@ def test_web_security_scanner_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("websecurityscanner.googleapis.com:443") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com" + ) @pytest.mark.parametrize( @@ -5178,6 +9358,7 @@ def test_web_security_scanner_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_web_security_scanner_host_with_port(transport_name): @@ -5188,7 +9369,69 @@ def test_web_security_scanner_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("websecurityscanner.googleapis.com:8000") + assert client.transport._host == ( + "websecurityscanner.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://websecurityscanner.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_web_security_scanner_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = WebSecurityScannerClient( + credentials=creds1, + transport=transport_name, + ) + client2 = WebSecurityScannerClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_scan_config._session + session2 = client2.transport.create_scan_config._session + assert session1 != session2 + session1 = client1.transport.delete_scan_config._session + session2 = client2.transport.delete_scan_config._session + assert session1 != session2 + session1 = client1.transport.get_scan_config._session + session2 = client2.transport.get_scan_config._session + assert session1 != session2 + session1 = client1.transport.list_scan_configs._session + session2 = client2.transport.list_scan_configs._session + assert session1 != session2 + session1 = client1.transport.update_scan_config._session + session2 = client2.transport.update_scan_config._session + assert session1 != session2 + session1 = client1.transport.start_scan_run._session + session2 = client2.transport.start_scan_run._session + assert session1 != session2 + session1 = client1.transport.get_scan_run._session + session2 = client2.transport.get_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_scan_runs._session + session2 = client2.transport.list_scan_runs._session + assert session1 != session2 + session1 = client1.transport.stop_scan_run._session + session2 = client2.transport.stop_scan_run._session + assert session1 != session2 + session1 = client1.transport.list_crawled_urls._session + session2 = client2.transport.list_crawled_urls._session + assert session1 != session2 + session1 = client1.transport.get_finding._session + session2 = client2.transport.get_finding._session + assert session1 != session2 + session1 = client1.transport.list_findings._session + session2 = client2.transport.list_findings._session + assert session1 != session2 + session1 = client1.transport.list_finding_type_stats._session + session2 = client2.transport.list_finding_type_stats._session + assert session1 != session2 def test_web_security_scanner_grpc_transport_channel(): @@ -5541,6 +9784,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -5558,6 +9802,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: