diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index 108063d..b668c04 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,3 +1,17 @@ +# 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. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:4ee57a76a176ede9087c14330c625a71553cf9c72828b2c0ca12f5338171ba60 + digest: sha256:ed1f9983d5a935a89fe8085e8bb97d94e41015252c5b6c9771257cf8624367e6 + diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 30c3973..e446644 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,9 +3,10 @@ # # For syntax help see: # https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners#codeowners-syntax +# Note: This file is autogenerated. To make changes to the codeowner team, please update .repo-metadata.json. -# The @googleapis/yoshi-python is the default owner for changes in this repo -* @googleapis/yoshi-python +# @googleapis/yoshi-python is the default owner for changes in this repo +* @googleapis/yoshi-python -# The python-samples-reviewers team is the default owner for samples changes -/samples/ @googleapis/python-samples-owners \ No newline at end of file +# @googleapis/python-samples-reviewers is the default owner for samples changes +/samples/ @googleapis/python-samples-reviewers diff --git a/.github/release-please.yml b/.github/release-please.yml index 4507ad0..466597e 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1 +1,2 @@ releaseType: python +handleGHRelease: true diff --git a/.github/release-trigger.yml b/.github/release-trigger.yml new file mode 100644 index 0000000..d4ca941 --- /dev/null +++ b/.github/release-trigger.yml @@ -0,0 +1 @@ +enabled: true diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..f7b8344 --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,38 @@ +on: + pull_request: + branches: + - main +name: docs +jobs: + docs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docs + run: | + nox -s docs + docfx: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run docfx + run: | + nox -s docfx diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..1e8b05c --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,25 @@ +on: + pull_request: + branches: + - main +name: lint +jobs: + lint: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run lint + run: | + nox -s lint + - name: Run lint_setup_py + run: | + nox -s lint_setup_py diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml new file mode 100644 index 0000000..074ee25 --- /dev/null +++ b/.github/workflows/unittest.yml @@ -0,0 +1,57 @@ +on: + pull_request: + branches: + - main +name: unittest +jobs: + unit: + runs-on: ubuntu-latest + strategy: + matrix: + python: ['3.6', '3.7', '3.8', '3.9', '3.10'] + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python }} + - name: Install nox + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install nox + - name: Run unit tests + env: + COVERAGE_FILE: .coverage-${{ matrix.python }} + run: | + nox -s unit-${{ matrix.python }} + - name: Upload coverage results + uses: actions/upload-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-${{ matrix.python }} + + cover: + runs-on: ubuntu-latest + needs: + - unit + steps: + - name: Checkout + uses: actions/checkout@v2 + - name: Setup Python + uses: actions/setup-python@v2 + with: + python-version: "3.10" + - name: Install coverage + run: | + python -m pip install --upgrade setuptools pip wheel + python -m pip install coverage + - name: Download coverage results + uses: actions/download-artifact@v2 + with: + name: coverage-artifacts + path: .coverage-results/ + - name: Report coverage results + run: | + coverage combine .coverage-results/.coverage* + coverage report --show-missing --fail-under=100 diff --git a/.kokoro/release.sh b/.kokoro/release.sh index 5d00ace..71dcdb9 100755 --- a/.kokoro/release.sh +++ b/.kokoro/release.sh @@ -26,7 +26,7 @@ python3 -m pip install --upgrade twine wheel setuptools export PYTHONUNBUFFERED=1 # Move into the package, build the distribution and upload. -TWINE_PASSWORD=$(cat "${KOKORO_GFILE_DIR}/secret_manager/google-cloud-pypi-token") +TWINE_PASSWORD=$(cat "${KOKORO_KEYSTORE_DIR}/73713_google-cloud-pypi-token-keystore-1") cd github/python-webrisk python3 setup.py sdist bdist_wheel twine upload --username __token__ --password "${TWINE_PASSWORD}" dist/* diff --git a/.kokoro/release/common.cfg b/.kokoro/release/common.cfg index 2bb8de1..5cb3f88 100644 --- a/.kokoro/release/common.cfg +++ b/.kokoro/release/common.cfg @@ -23,8 +23,18 @@ env_vars: { value: "github/python-webrisk/.kokoro/release.sh" } +# Fetch PyPI password +before_action { + fetch_keystore { + keystore_resource { + keystore_config_id: 73713 + keyname: "google-cloud-pypi-token-keystore-1" + } + } +} + # Tokens needed to report release status back to GitHub env_vars: { key: "SECRET_MANAGER_KEYS" - value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem,google-cloud-pypi-token" + value: "releasetool-publish-reporter-app,releasetool-publish-reporter-googleapis-installation,releasetool-publish-reporter-pem" } diff --git a/.repo-metadata.json b/.repo-metadata.json index 6cef66e..77533ca 100644 --- a/.repo-metadata.json +++ b/.repo-metadata.json @@ -2,9 +2,9 @@ "name": "webrisk", "name_pretty": "Web Risk", "product_documentation": "https://cloud.google.com/web-risk/docs/", - "client_documentation": "https://googleapis.dev/python/webrisk/latest", + "client_documentation": "https://cloud.google.com/python/docs/reference/webrisk/latest", "issue_tracker": "", - "release_level": "ga", + "release_level": "stable", "language": "python", "library_type": "GAPIC_AUTO", "repo": "googleapis/python-webrisk", @@ -12,5 +12,6 @@ "api_id": "webrisk.googleapis.com", "requires_billing": true, "default_version": "v1", - "codeowner_team": "" + "codeowner_team": "", + "api_shortname": "webrisk" } diff --git a/CHANGELOG.md b/CHANGELOG.md index ff8c088..0931124 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,23 @@ [PyPI History][1] [1]: https://pypi.org/project/google-cloud-webrisk/#history +## [1.7.0](https://github.com/googleapis/python-webrisk/compare/v1.6.1...v1.7.0) (2022-02-11) + + +### Features + +* add api key support ([#156](https://github.com/googleapis/python-webrisk/issues/156)) ([0a5ebb7](https://github.com/googleapis/python-webrisk/commit/0a5ebb7be318622f018e52cee88079bcd67de2de)) + + +### Bug Fixes + +* resolve DuplicateCredentialArgs error when using credentials_file ([35d62de](https://github.com/googleapis/python-webrisk/commit/35d62deb0689bc286051d7d1ce1c2297317f40ac)) + + +### Documentation + +* add generated snippets ([#161](https://github.com/googleapis/python-webrisk/issues/161)) ([101d3fd](https://github.com/googleapis/python-webrisk/commit/101d3fdeb735aecc4aa6a21502ede35ee4b2d3f2)) + ### [1.6.1](https://www.github.com/googleapis/python-webrisk/compare/v1.6.0...v1.6.1) (2021-11-01) diff --git a/README.rst b/README.rst index 3cb23cd..57352cd 100644 --- a/README.rst +++ b/README.rst @@ -15,7 +15,7 @@ Python Client for Web Risk API .. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-webrisk.svg :target: https://pypi.org/project/google-cloud-webrisk/ -.. _Client Library Documentation: https://googleapis.dev/python/webrisk/latest +.. _Client Library Documentation: https://cloud.google.com/python/docs/reference/webrisk/latest .. _Product Documentation: https://cloud.google.com/web-risk Quick Start diff --git a/google/cloud/webrisk_v1/services/web_risk_service/async_client.py b/google/cloud/webrisk_v1/services/web_risk_service/async_client.py index ded42ff..0cafa27 100644 --- a/google/cloud/webrisk_v1/services/web_risk_service/async_client.py +++ b/google/cloud/webrisk_v1/services/web_risk_service/async_client.py @@ -16,17 +16,20 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.webrisk_v1.types import webrisk from google.protobuf import timestamp_pb2 # type: ignore @@ -103,6 +106,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return WebRiskServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> WebRiskServiceTransport: """Returns the transport used by the client instance. @@ -183,6 +222,26 @@ async def compute_threat_list_diff( ThreatList databases, this method needs to be called once for each list. + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.ComputeThreatListDiffRequest, dict]): The request object. Describes an API diff request. @@ -226,7 +285,7 @@ async def compute_threat_list_diff( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([threat_type, version_token, constraints]) if request is not None and has_flattened_params: @@ -287,6 +346,27 @@ async def search_uris( not found on any of the requested ThreatList an empty response will be returned. + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_search_uris(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_uris(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.SearchUrisRequest, dict]): The request object. Request to check URI entries against @@ -317,7 +397,7 @@ async def search_uris( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([uri, threat_types]) if request is not None and has_flattened_params: @@ -376,6 +456,26 @@ async def search_hashes( query this method to determine if there is a full hash match of a threat. + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_search_hashes(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_hashes(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.SearchHashesRequest, dict]): The request object. Request to return full hashes @@ -408,7 +508,7 @@ async def search_hashes( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([hash_prefix, threat_types]) if request is not None and has_flattened_params: @@ -469,6 +569,30 @@ async def create_submission( in the future. Only projects with CREATE_SUBMISSION_USERS visibility can use this method. + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_create_submission(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.CreateSubmissionRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + response = client.create_submission(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.CreateSubmissionRequest, dict]): The request object. Request to send a potentially phishy @@ -502,7 +626,7 @@ async def create_submission( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, submission]) if request is not None and has_flattened_params: diff --git a/google/cloud/webrisk_v1/services/web_risk_service/client.py b/google/cloud/webrisk_v1/services/web_risk_service/client.py index f93474a..b2d4667 100644 --- a/google/cloud/webrisk_v1/services/web_risk_service/client.py +++ b/google/cloud/webrisk_v1/services/web_risk_service/client.py @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.webrisk_v1.types import webrisk from google.protobuf import timestamp_pb2 # type: ignore @@ -218,6 +220,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -268,50 +337,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, WebRiskServiceTransport): # transport is a WebRiskServiceTransport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -323,6 +364,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, @@ -355,6 +405,27 @@ def compute_threat_list_diff( ThreatList databases, this method needs to be called once for each list. + + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.ComputeThreatListDiffRequest, dict]): The request object. Describes an API diff request. @@ -398,7 +469,7 @@ def compute_threat_list_diff( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([threat_type, version_token, constraints]) if request is not None and has_flattened_params: @@ -449,6 +520,28 @@ def search_uris( not found on any of the requested ThreatList an empty response will be returned. + + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_search_uris(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_uris(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.SearchUrisRequest, dict]): The request object. Request to check URI entries against @@ -479,7 +572,7 @@ def search_uris( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([uri, threat_types]) if request is not None and has_flattened_params: @@ -528,6 +621,27 @@ def search_hashes( query this method to determine if there is a full hash match of a threat. + + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_search_hashes(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_hashes(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.SearchHashesRequest, dict]): The request object. Request to return full hashes @@ -560,7 +674,7 @@ def search_hashes( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([hash_prefix, threat_types]) if request is not None and has_flattened_params: @@ -611,6 +725,31 @@ def create_submission( in the future. Only projects with CREATE_SUBMISSION_USERS visibility can use this method. + + + .. code-block:: + + from google.cloud import webrisk_v1 + + def sample_create_submission(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.CreateSubmissionRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + response = client.create_submission(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1.types.CreateSubmissionRequest, dict]): The request object. Request to send a potentially phishy @@ -644,7 +783,7 @@ def create_submission( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, submission]) if request is not None and has_flattened_params: diff --git a/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py b/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py index f10584f..a1dc7bc 100644 --- a/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py +++ b/google/cloud/webrisk_v1/services/web_risk_service/transports/base.py @@ -18,10 +18,10 @@ import pkg_resources import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore @@ -99,7 +99,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id diff --git a/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py b/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py index 9ec741a..872279e 100644 --- a/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py +++ b/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc.py @@ -16,8 +16,8 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -159,8 +159,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py b/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py index aea7da4..d2e4d4c 100644 --- a/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py +++ b/google/cloud/webrisk_v1/services/web_risk_service/transports/grpc_asyncio.py @@ -16,8 +16,8 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -204,8 +204,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/async_client.py b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/async_client.py index 80f0bd3..4e96ebc 100644 --- a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/async_client.py +++ b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/async_client.py @@ -16,17 +16,20 @@ from collections import OrderedDict import functools import re -from typing import Dict, Sequence, Tuple, Type, Union +from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core.client_options import ClientOptions # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +from google.api_core.client_options import ClientOptions +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.webrisk_v1beta1.types import webrisk from google.protobuf import timestamp_pb2 # type: ignore @@ -105,6 +108,42 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return WebRiskServiceV1Beta1Client.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + @property def transport(self) -> WebRiskServiceV1Beta1Transport: """Returns the transport used by the client instance. @@ -179,6 +218,25 @@ async def compute_threat_list_diff( ) -> webrisk.ComputeThreatListDiffResponse: r"""Gets the most recent threat list diffs. + .. code-block:: + + from google.cloud import webrisk_v1beta1 + + def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1beta1.types.ComputeThreatListDiffRequest, dict]): The request object. Describes an API diff request. @@ -214,7 +272,7 @@ async def compute_threat_list_diff( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([threat_type, version_token, constraints]) if request is not None and has_flattened_params: @@ -271,6 +329,27 @@ async def search_uris( r"""This method is used to check whether a URI is on a given threatList. + + .. code-block:: + + from google.cloud import webrisk_v1beta1 + + def sample_search_uris(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_uris(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1beta1.types.SearchUrisRequest, dict]): The request object. Request to check URI entries against @@ -300,7 +379,7 @@ async def search_uris( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([uri, threat_types]) if request is not None and has_flattened_params: @@ -359,6 +438,26 @@ async def search_hashes( query this method to determine if there is a full hash match of a threat. + + .. code-block:: + + from google.cloud import webrisk_v1beta1 + + def sample_search_hashes(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_hashes(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1beta1.types.SearchHashesRequest, dict]): The request object. Request to return full hashes @@ -390,7 +489,7 @@ async def search_hashes( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([hash_prefix, threat_types]) if request is not None and has_flattened_params: diff --git a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/client.py b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/client.py index 6c2b0e7..5b0a851 100644 --- a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/client.py +++ b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/client.py @@ -14,23 +14,25 @@ # limitations under the License. # from collections import OrderedDict -from distutils import util import os import re from typing import Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -from google.api_core import client_options as client_options_lib # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore -OptionalRetry = Union[retries.Retry, object] +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore from google.cloud.webrisk_v1beta1.types import webrisk from google.protobuf import timestamp_pb2 # type: ignore @@ -220,6 +222,73 @@ def parse_common_location_path(path: str) -> Dict[str, str]: m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) return m.groupdict() if m else {} + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variabel is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + def __init__( self, *, @@ -270,50 +339,22 @@ def __init__( if client_options is None: client_options = client_options_lib.ClientOptions() - # Create SSL credentials for mutual TLS if needed. - use_client_cert = bool( - util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options ) - client_cert_source_func = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - is_mtls = True - client_cert_source_func = client_options.client_cert_source - else: - is_mtls = mtls.has_default_client_cert_source() - if is_mtls: - client_cert_source_func = mtls.default_client_cert_source() - else: - client_cert_source_func = None - - # Figure out which api endpoint to use. - if client_options.api_endpoint is not None: - api_endpoint = client_options.api_endpoint - else: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") - if use_mtls_env == "never": - api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - if is_mtls: - api_endpoint = self.DEFAULT_MTLS_ENDPOINT - else: - api_endpoint = self.DEFAULT_ENDPOINT - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " - "values: never, auto, always" - ) + api_key_value = getattr(client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) # Save or instantiate the transport. # Ordinarily, we provide the transport, but allowing a custom transport # instance provides an extensibility point for unusual situations. if isinstance(transport, WebRiskServiceV1Beta1Transport): # transport is a WebRiskServiceV1Beta1Transport instance. - if credentials or client_options.credentials_file: + if credentials or client_options.credentials_file or api_key_value: raise ValueError( "When providing a transport instance, " "provide its credentials directly." @@ -325,6 +366,15 @@ def __init__( ) self._transport = transport else: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + Transport = type(self).get_transport_class(transport) self._transport = Transport( credentials=credentials, @@ -350,6 +400,26 @@ def compute_threat_list_diff( ) -> webrisk.ComputeThreatListDiffResponse: r"""Gets the most recent threat list diffs. + + .. code-block:: + + from google.cloud import webrisk_v1beta1 + + def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1beta1.types.ComputeThreatListDiffRequest, dict]): The request object. Describes an API diff request. @@ -385,7 +455,7 @@ def compute_threat_list_diff( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([threat_type, version_token, constraints]) if request is not None and has_flattened_params: @@ -432,6 +502,28 @@ def search_uris( r"""This method is used to check whether a URI is on a given threatList. + + + .. code-block:: + + from google.cloud import webrisk_v1beta1 + + def sample_search_uris(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_uris(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1beta1.types.SearchUrisRequest, dict]): The request object. Request to check URI entries against @@ -461,7 +553,7 @@ def search_uris( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([uri, threat_types]) if request is not None and has_flattened_params: @@ -510,6 +602,27 @@ def search_hashes( query this method to determine if there is a full hash match of a threat. + + + .. code-block:: + + from google.cloud import webrisk_v1beta1 + + def sample_search_hashes(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_hashes(request=request) + + # Handle the response + print(response) + Args: request (Union[google.cloud.webrisk_v1beta1.types.SearchHashesRequest, dict]): The request object. Request to return full hashes @@ -541,7 +654,7 @@ def search_hashes( """ # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have + # Quick check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. has_flattened_params = any([hash_prefix, threat_types]) if request is not None and has_flattened_params: diff --git a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/base.py b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/base.py index 5db2edb..27bd439 100644 --- a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/base.py +++ b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/base.py @@ -18,10 +18,10 @@ import pkg_resources import google.auth # type: ignore -import google.api_core # type: ignore -from google.api_core import exceptions as core_exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore @@ -99,7 +99,6 @@ def __init__( credentials, _ = google.auth.load_credentials_from_file( credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) - elif credentials is None: credentials, _ = google.auth.default( **scopes_kwargs, quota_project_id=quota_project_id diff --git a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc.py b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc.py index cca44c0..147dd1a 100644 --- a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc.py +++ b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc.py @@ -16,8 +16,8 @@ import warnings from typing import Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import grpc_helpers # type: ignore -from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers +from google.api_core import gapic_v1 import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -159,8 +159,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc_asyncio.py b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc_asyncio.py index eb6dea7..1ba81f9 100644 --- a/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc_asyncio.py +++ b/google/cloud/webrisk_v1beta1/services/web_risk_service_v1_beta1/transports/grpc_asyncio.py @@ -16,8 +16,8 @@ import warnings from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers_async from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore @@ -204,8 +204,11 @@ def __init__( if not self._grpc_channel: self._grpc_channel = type(self).create_channel( self._host, + # use the credentials which are saved credentials=self._credentials, - credentials_file=credentials_file, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, scopes=self._scopes, ssl_credentials=self._ssl_channel_credentials, quota_project_id=quota_project_id, diff --git a/samples/generated_samples/snippet_metadata_webrisk_v1.json b/samples/generated_samples/snippet_metadata_webrisk_v1.json new file mode 100644 index 0000000..7568f36 --- /dev/null +++ b/samples/generated_samples/snippet_metadata_webrisk_v1.json @@ -0,0 +1,360 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "ComputeThreatListDiff" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_async.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_ComputeThreatListDiff_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "ComputeThreatListDiff" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_sync.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_ComputeThreatListDiff_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "CreateSubmission" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_create_submission_async.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_CreateSubmission_async", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "CreateSubmission" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_create_submission_sync.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_CreateSubmission_sync", + "segments": [ + { + "end": 48, + "start": 27, + "type": "FULL" + }, + { + "end": 48, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 42, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 45, + "start": 43, + "type": "REQUEST_EXECUTION" + }, + { + "end": 49, + "start": 46, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "SearchHashes" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_search_hashes_async.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_SearchHashes_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "SearchHashes" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_search_hashes_sync.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_SearchHashes_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "SearchUris" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_search_uris_async.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_SearchUris_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskService" + }, + "shortName": "SearchUris" + } + }, + "file": "webrisk_generated_webrisk_v1_web_risk_service_search_uris_sync.py", + "regionTag": "webrisk_generated_webrisk_v1_WebRiskService_SearchUris_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} diff --git a/samples/generated_samples/snippet_metadata_webrisk_v1beta1.json b/samples/generated_samples/snippet_metadata_webrisk_v1beta1.json new file mode 100644 index 0000000..240dde4 --- /dev/null +++ b/samples/generated_samples/snippet_metadata_webrisk_v1beta1.json @@ -0,0 +1,271 @@ +{ + "snippets": [ + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskServiceV1Beta1" + }, + "shortName": "ComputeThreatListDiff" + } + }, + "file": "webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_async.py", + "regionTag": "webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_ComputeThreatListDiff_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskServiceV1Beta1" + }, + "shortName": "ComputeThreatListDiff" + } + }, + "file": "webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_sync.py", + "regionTag": "webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_ComputeThreatListDiff_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskServiceV1Beta1" + }, + "shortName": "SearchHashes" + } + }, + "file": "webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_async.py", + "regionTag": "webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchHashes_async", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskServiceV1Beta1" + }, + "shortName": "SearchHashes" + } + }, + "file": "webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_sync.py", + "regionTag": "webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchHashes_sync", + "segments": [ + { + "end": 44, + "start": 27, + "type": "FULL" + }, + { + "end": 44, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 38, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 41, + "start": 39, + "type": "REQUEST_EXECUTION" + }, + { + "end": 45, + "start": 42, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "async": true, + "method": { + "service": { + "shortName": "WebRiskServiceV1Beta1" + }, + "shortName": "SearchUris" + } + }, + "file": "webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_async.py", + "regionTag": "webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchUris_async", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + }, + { + "clientMethod": { + "method": { + "service": { + "shortName": "WebRiskServiceV1Beta1" + }, + "shortName": "SearchUris" + } + }, + "file": "webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_sync.py", + "regionTag": "webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchUris_sync", + "segments": [ + { + "end": 45, + "start": 27, + "type": "FULL" + }, + { + "end": 45, + "start": 27, + "type": "SHORT" + }, + { + "end": 33, + "start": 31, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 39, + "start": 34, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 42, + "start": 40, + "type": "REQUEST_EXECUTION" + }, + { + "end": 46, + "start": 43, + "type": "RESPONSE_HANDLING" + } + ] + } + ] +} diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_async.py new file mode 100644 index 0000000..3f29f85 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeThreatListDiff +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_ComputeThreatListDiff_async] +from google.cloud import webrisk_v1 + + +async def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1.WebRiskServiceAsyncClient() + + # Initialize request argument(s) + request = webrisk_v1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = await client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_ComputeThreatListDiff_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_sync.py new file mode 100644 index 0000000..74b6057 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_compute_threat_list_diff_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeThreatListDiff +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_ComputeThreatListDiff_sync] +from google.cloud import webrisk_v1 + + +def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_ComputeThreatListDiff_sync] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_create_submission_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_create_submission_async.py new file mode 100644 index 0000000..ef89b64 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_create_submission_async.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSubmission +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_CreateSubmission_async] +from google.cloud import webrisk_v1 + + +async def sample_create_submission(): + # Create a client + client = webrisk_v1.WebRiskServiceAsyncClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.CreateSubmissionRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + response = await client.create_submission(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_CreateSubmission_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_create_submission_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_create_submission_sync.py new file mode 100644 index 0000000..3cc1d59 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_create_submission_sync.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreateSubmission +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_CreateSubmission_sync] +from google.cloud import webrisk_v1 + + +def sample_create_submission(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + submission = webrisk_v1.Submission() + submission.uri = "uri_value" + + request = webrisk_v1.CreateSubmissionRequest( + parent="parent_value", + submission=submission, + ) + + # Make the request + response = client.create_submission(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_CreateSubmission_sync] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_hashes_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_hashes_async.py new file mode 100644 index 0000000..99b5ff2 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_hashes_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchHashes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_SearchHashes_async] +from google.cloud import webrisk_v1 + + +async def sample_search_hashes(): + # Create a client + client = webrisk_v1.WebRiskServiceAsyncClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = await client.search_hashes(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_SearchHashes_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_hashes_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_hashes_sync.py new file mode 100644 index 0000000..afe4913 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_hashes_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchHashes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_SearchHashes_sync] +from google.cloud import webrisk_v1 + + +def sample_search_hashes(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_hashes(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_SearchHashes_sync] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_uris_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_uris_async.py new file mode 100644 index 0000000..562fdd1 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_uris_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchUris +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_SearchUris_async] +from google.cloud import webrisk_v1 + + +async def sample_search_uris(): + # Create a client + client = webrisk_v1.WebRiskServiceAsyncClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = await client.search_uris(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_SearchUris_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_uris_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_uris_sync.py new file mode 100644 index 0000000..4f2df97 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1_web_risk_service_search_uris_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchUris +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1_WebRiskService_SearchUris_sync] +from google.cloud import webrisk_v1 + + +def sample_search_uris(): + # Create a client + client = webrisk_v1.WebRiskServiceClient() + + # Initialize request argument(s) + request = webrisk_v1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_uris(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1_WebRiskService_SearchUris_sync] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_async.py new file mode 100644 index 0000000..8c50092 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeThreatListDiff +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_ComputeThreatListDiff_async] +from google.cloud import webrisk_v1beta1 + + +async def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1AsyncClient() + + # Initialize request argument(s) + request = webrisk_v1beta1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = await client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_ComputeThreatListDiff_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_sync.py new file mode 100644 index 0000000..58a542b --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_compute_threat_list_diff_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ComputeThreatListDiff +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_ComputeThreatListDiff_sync] +from google.cloud import webrisk_v1beta1 + + +def sample_compute_threat_list_diff(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.ComputeThreatListDiffRequest( + threat_type="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.compute_threat_list_diff(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_ComputeThreatListDiff_sync] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_async.py new file mode 100644 index 0000000..2e0e908 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_async.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchHashes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchHashes_async] +from google.cloud import webrisk_v1beta1 + + +async def sample_search_hashes(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1AsyncClient() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = await client.search_hashes(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchHashes_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_sync.py new file mode 100644 index 0000000..66b5666 --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_hashes_sync.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchHashes +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchHashes_sync] +from google.cloud import webrisk_v1beta1 + + +def sample_search_hashes(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchHashesRequest( + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_hashes(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchHashes_sync] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_async.py b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_async.py new file mode 100644 index 0000000..4d640ad --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_async.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchUris +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchUris_async] +from google.cloud import webrisk_v1beta1 + + +async def sample_search_uris(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1AsyncClient() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = await client.search_uris(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchUris_async] diff --git a/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_sync.py b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_sync.py new file mode 100644 index 0000000..37c523f --- /dev/null +++ b/samples/generated_samples/webrisk_generated_webrisk_v1beta1_web_risk_service_v1_beta1_search_uris_sync.py @@ -0,0 +1,46 @@ +# -*- coding: utf-8 -*- +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SearchUris +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-webrisk + + +# [START webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchUris_sync] +from google.cloud import webrisk_v1beta1 + + +def sample_search_uris(): + # Create a client + client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() + + # Initialize request argument(s) + request = webrisk_v1beta1.SearchUrisRequest( + uri="uri_value", + threat_types="UNWANTED_SOFTWARE", + ) + + # Make the request + response = client.search_uris(request=request) + + # Handle the response + print(response) + +# [END webrisk_generated_webrisk_v1beta1_WebRiskServiceV1Beta1_SearchUris_sync] diff --git a/setup.py b/setup.py index 6250aa6..e17e575 100644 --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ name = "google-cloud-webrisk" description = "Google Cloud Web Risk API client library" -version = "1.6.1" +version = "1.7.0" # Should be one of: # 'Development Status :: 3 - Alpha' # 'Development Status :: 4 - Beta' diff --git a/tests/unit/gapic/webrisk_v1/test_web_risk_service.py b/tests/unit/gapic/webrisk_v1/test_web_risk_service.py index ee4a483..e938a90 100644 --- a/tests/unit/gapic/webrisk_v1/test_web_risk_service.py +++ b/tests/unit/gapic/webrisk_v1/test_web_risk_service.py @@ -246,20 +246,20 @@ def test_web_risk_service_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -318,7 +318,7 @@ def test_web_risk_service_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -395,6 +395,87 @@ def test_web_risk_service_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [WebRiskServiceClient, WebRiskServiceAsyncClient] +) +@mock.patch.object( + WebRiskServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(WebRiskServiceClient), +) +@mock.patch.object( + WebRiskServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(WebRiskServiceAsyncClient), +) +def test_web_risk_service_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -413,7 +494,7 @@ def test_web_risk_service_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -427,24 +508,31 @@ def test_web_risk_service_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ - (WebRiskServiceClient, transports.WebRiskServiceGrpcTransport, "grpc"), + ( + WebRiskServiceClient, + transports.WebRiskServiceGrpcTransport, + "grpc", + grpc_helpers, + ), ( WebRiskServiceAsyncClient, transports.WebRiskServiceGrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_web_risk_service_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -477,9 +565,74 @@ def test_web_risk_service_client_client_options_from_dict(): ) -def test_compute_threat_list_diff( - transport: str = "grpc", request_type=webrisk.ComputeThreatListDiffRequest +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + WebRiskServiceClient, + transports.WebRiskServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + WebRiskServiceAsyncClient, + transports.WebRiskServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_web_risk_service_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers ): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "webrisk.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="webrisk.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [webrisk.ComputeThreatListDiffRequest, dict,]) +def test_compute_threat_list_diff(request_type, transport: str = "grpc"): client = WebRiskServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -513,10 +666,6 @@ def test_compute_threat_list_diff( assert response.new_version_token == b"new_version_token_blob" -def test_compute_threat_list_diff_from_dict(): - test_compute_threat_list_diff(request_type=dict) - - def test_compute_threat_list_diff_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -601,11 +750,17 @@ def test_compute_threat_list_diff_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].threat_type == webrisk.ThreatType.MALWARE - assert args[0].version_token == b"version_token_blob" - assert args[0].constraints == webrisk.ComputeThreatListDiffRequest.Constraints( + arg = args[0].threat_type + mock_val = webrisk.ThreatType.MALWARE + assert arg == mock_val + arg = args[0].version_token + mock_val = b"version_token_blob" + assert arg == mock_val + arg = args[0].constraints + mock_val = webrisk.ComputeThreatListDiffRequest.Constraints( max_diff_entries=1687 ) + assert arg == mock_val def test_compute_threat_list_diff_flattened_error(): @@ -654,11 +809,17 @@ async def test_compute_threat_list_diff_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].threat_type == webrisk.ThreatType.MALWARE - assert args[0].version_token == b"version_token_blob" - assert args[0].constraints == webrisk.ComputeThreatListDiffRequest.Constraints( + arg = args[0].threat_type + mock_val = webrisk.ThreatType.MALWARE + assert arg == mock_val + arg = args[0].version_token + mock_val = b"version_token_blob" + assert arg == mock_val + arg = args[0].constraints + mock_val = webrisk.ComputeThreatListDiffRequest.Constraints( max_diff_entries=1687 ) + assert arg == mock_val @pytest.mark.asyncio @@ -680,7 +841,8 @@ async def test_compute_threat_list_diff_flattened_error_async(): ) -def test_search_uris(transport: str = "grpc", request_type=webrisk.SearchUrisRequest): +@pytest.mark.parametrize("request_type", [webrisk.SearchUrisRequest, dict,]) +def test_search_uris(request_type, transport: str = "grpc"): client = WebRiskServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -704,10 +866,6 @@ def test_search_uris(transport: str = "grpc", request_type=webrisk.SearchUrisReq assert isinstance(response, webrisk.SearchUrisResponse) -def test_search_uris_from_dict(): - test_search_uris(request_type=dict) - - def test_search_uris_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -774,8 +932,12 @@ def test_search_uris_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].uri == "uri_value" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].uri + mock_val = "uri_value" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val def test_search_uris_flattened_error(): @@ -815,8 +977,12 @@ async def test_search_uris_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].uri == "uri_value" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].uri + mock_val = "uri_value" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val @pytest.mark.asyncio @@ -835,9 +1001,8 @@ async def test_search_uris_flattened_error_async(): ) -def test_search_hashes( - transport: str = "grpc", request_type=webrisk.SearchHashesRequest -): +@pytest.mark.parametrize("request_type", [webrisk.SearchHashesRequest, dict,]) +def test_search_hashes(request_type, transport: str = "grpc"): client = WebRiskServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -861,10 +1026,6 @@ def test_search_hashes( assert isinstance(response, webrisk.SearchHashesResponse) -def test_search_hashes_from_dict(): - test_search_hashes(request_type=dict) - - def test_search_hashes_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -931,8 +1092,12 @@ def test_search_hashes_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].hash_prefix == b"hash_prefix_blob" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].hash_prefix + mock_val = b"hash_prefix_blob" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val def test_search_hashes_flattened_error(): @@ -972,8 +1137,12 @@ async def test_search_hashes_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].hash_prefix == b"hash_prefix_blob" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].hash_prefix + mock_val = b"hash_prefix_blob" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val @pytest.mark.asyncio @@ -992,9 +1161,8 @@ async def test_search_hashes_flattened_error_async(): ) -def test_create_submission( - transport: str = "grpc", request_type=webrisk.CreateSubmissionRequest -): +@pytest.mark.parametrize("request_type", [webrisk.CreateSubmissionRequest, dict,]) +def test_create_submission(request_type, transport: str = "grpc"): client = WebRiskServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -1021,10 +1189,6 @@ def test_create_submission( assert response.uri == "uri_value" -def test_create_submission_from_dict(): - test_create_submission(request_type=dict) - - def test_create_submission_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -1153,8 +1317,12 @@ def test_create_submission_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].submission == webrisk.Submission(uri="uri_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].submission + mock_val = webrisk.Submission(uri="uri_value") + assert arg == mock_val def test_create_submission_flattened_error(): @@ -1194,8 +1362,12 @@ async def test_create_submission_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].submission == webrisk.Submission(uri="uri_value") + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].submission + mock_val = webrisk.Submission(uri="uri_value") + assert arg == mock_val @pytest.mark.asyncio @@ -1234,6 +1406,23 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.WebRiskServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebRiskServiceClient(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 = WebRiskServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.WebRiskServiceGrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -1707,7 +1896,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( @@ -1772,3 +1961,33 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (WebRiskServiceClient, transports.WebRiskServiceGrpcTransport), + (WebRiskServiceAsyncClient, transports.WebRiskServiceGrpcAsyncIOTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) diff --git a/tests/unit/gapic/webrisk_v1beta1/test_web_risk_service_v1_beta1.py b/tests/unit/gapic/webrisk_v1beta1/test_web_risk_service_v1_beta1.py index c593e05..0527b6e 100644 --- a/tests/unit/gapic/webrisk_v1beta1/test_web_risk_service_v1_beta1.py +++ b/tests/unit/gapic/webrisk_v1beta1/test_web_risk_service_v1_beta1.py @@ -255,20 +255,20 @@ def test_web_risk_service_v1_beta1_client_client_options( # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): - client = client_class() + client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): - client = client_class() + client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -337,7 +337,7 @@ def test_web_risk_service_v1_beta1_client_mtls_env_auto( ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None @@ -414,6 +414,89 @@ def test_web_risk_service_v1_beta1_client_mtls_env_auto( ) +@pytest.mark.parametrize( + "client_class", [WebRiskServiceV1Beta1Client, WebRiskServiceV1Beta1AsyncClient] +) +@mock.patch.object( + WebRiskServiceV1Beta1Client, + "DEFAULT_ENDPOINT", + modify_default_endpoint(WebRiskServiceV1Beta1Client), +) +@mock.patch.object( + WebRiskServiceV1Beta1AsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(WebRiskServiceV1Beta1AsyncClient), +) +def test_web_risk_service_v1_beta1_client_get_mtls_endpoint_and_cert_source( + client_class, +): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + @pytest.mark.parametrize( "client_class,transport_class,transport_name", [ @@ -436,7 +519,7 @@ def test_web_risk_service_v1_beta1_client_client_options_scopes( options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, @@ -450,28 +533,31 @@ def test_web_risk_service_v1_beta1_client_client_options_scopes( @pytest.mark.parametrize( - "client_class,transport_class,transport_name", + "client_class,transport_class,transport_name,grpc_helpers", [ ( WebRiskServiceV1Beta1Client, transports.WebRiskServiceV1Beta1GrpcTransport, "grpc", + grpc_helpers, ), ( WebRiskServiceV1Beta1AsyncClient, transports.WebRiskServiceV1Beta1GrpcAsyncIOTransport, "grpc_asyncio", + grpc_helpers_async, ), ], ) def test_web_risk_service_v1_beta1_client_client_options_credentials_file( - client_class, transport_class, transport_name + client_class, transport_class, transport_name, grpc_helpers ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None - client = client_class(transport=transport_name, client_options=options) + client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", @@ -504,9 +590,74 @@ def test_web_risk_service_v1_beta1_client_client_options_from_dict(): ) -def test_compute_threat_list_diff( - transport: str = "grpc", request_type=webrisk.ComputeThreatListDiffRequest +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + WebRiskServiceV1Beta1Client, + transports.WebRiskServiceV1Beta1GrpcTransport, + "grpc", + grpc_helpers, + ), + ( + WebRiskServiceV1Beta1AsyncClient, + transports.WebRiskServiceV1Beta1GrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_web_risk_service_v1_beta1_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers ): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "webrisk.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="webrisk.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize("request_type", [webrisk.ComputeThreatListDiffRequest, dict,]) +def test_compute_threat_list_diff(request_type, transport: str = "grpc"): client = WebRiskServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -540,10 +691,6 @@ def test_compute_threat_list_diff( assert response.new_version_token == b"new_version_token_blob" -def test_compute_threat_list_diff_from_dict(): - test_compute_threat_list_diff(request_type=dict) - - def test_compute_threat_list_diff_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -630,11 +777,17 @@ def test_compute_threat_list_diff_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].threat_type == webrisk.ThreatType.MALWARE - assert args[0].version_token == b"version_token_blob" - assert args[0].constraints == webrisk.ComputeThreatListDiffRequest.Constraints( + arg = args[0].threat_type + mock_val = webrisk.ThreatType.MALWARE + assert arg == mock_val + arg = args[0].version_token + mock_val = b"version_token_blob" + assert arg == mock_val + arg = args[0].constraints + mock_val = webrisk.ComputeThreatListDiffRequest.Constraints( max_diff_entries=1687 ) + assert arg == mock_val def test_compute_threat_list_diff_flattened_error(): @@ -685,11 +838,17 @@ async def test_compute_threat_list_diff_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].threat_type == webrisk.ThreatType.MALWARE - assert args[0].version_token == b"version_token_blob" - assert args[0].constraints == webrisk.ComputeThreatListDiffRequest.Constraints( + arg = args[0].threat_type + mock_val = webrisk.ThreatType.MALWARE + assert arg == mock_val + arg = args[0].version_token + mock_val = b"version_token_blob" + assert arg == mock_val + arg = args[0].constraints + mock_val = webrisk.ComputeThreatListDiffRequest.Constraints( max_diff_entries=1687 ) + assert arg == mock_val @pytest.mark.asyncio @@ -711,7 +870,8 @@ async def test_compute_threat_list_diff_flattened_error_async(): ) -def test_search_uris(transport: str = "grpc", request_type=webrisk.SearchUrisRequest): +@pytest.mark.parametrize("request_type", [webrisk.SearchUrisRequest, dict,]) +def test_search_uris(request_type, transport: str = "grpc"): client = WebRiskServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -735,10 +895,6 @@ def test_search_uris(transport: str = "grpc", request_type=webrisk.SearchUrisReq assert isinstance(response, webrisk.SearchUrisResponse) -def test_search_uris_from_dict(): - test_search_uris(request_type=dict) - - def test_search_uris_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -807,8 +963,12 @@ def test_search_uris_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].uri == "uri_value" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].uri + mock_val = "uri_value" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val def test_search_uris_flattened_error(): @@ -850,8 +1010,12 @@ async def test_search_uris_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].uri == "uri_value" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].uri + mock_val = "uri_value" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val @pytest.mark.asyncio @@ -870,9 +1034,8 @@ async def test_search_uris_flattened_error_async(): ) -def test_search_hashes( - transport: str = "grpc", request_type=webrisk.SearchHashesRequest -): +@pytest.mark.parametrize("request_type", [webrisk.SearchHashesRequest, dict,]) +def test_search_hashes(request_type, transport: str = "grpc"): client = WebRiskServiceV1Beta1Client( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) @@ -896,10 +1059,6 @@ def test_search_hashes( assert isinstance(response, webrisk.SearchHashesResponse) -def test_search_hashes_from_dict(): - test_search_hashes(request_type=dict) - - def test_search_hashes_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @@ -968,8 +1127,12 @@ def test_search_hashes_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].hash_prefix == b"hash_prefix_blob" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].hash_prefix + mock_val = b"hash_prefix_blob" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val def test_search_hashes_flattened_error(): @@ -1011,8 +1174,12 @@ async def test_search_hashes_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].hash_prefix == b"hash_prefix_blob" - assert args[0].threat_types == [webrisk.ThreatType.MALWARE] + arg = args[0].hash_prefix + mock_val = b"hash_prefix_blob" + assert arg == mock_val + arg = args[0].threat_types + mock_val = [webrisk.ThreatType.MALWARE] + assert arg == mock_val @pytest.mark.asyncio @@ -1051,6 +1218,25 @@ def test_credentials_transport_error(): transport=transport, ) + # It is an error to provide an api_key and a transport instance. + transport = transports.WebRiskServiceV1Beta1GrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = WebRiskServiceV1Beta1Client( + 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 = WebRiskServiceV1Beta1Client( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + # It is an error to provide scopes and a transport instance. transport = transports.WebRiskServiceV1Beta1GrpcTransport( credentials=ga_credentials.AnonymousCredentials(), @@ -1529,7 +1715,7 @@ def test_parse_common_location_path(): assert expected == actual -def test_client_withDEFAULT_CLIENT_INFO(): +def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( @@ -1594,3 +1780,36 @@ def test_client_ctx(): with client: pass close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (WebRiskServiceV1Beta1Client, transports.WebRiskServiceV1Beta1GrpcTransport), + ( + WebRiskServiceV1Beta1AsyncClient, + transports.WebRiskServiceV1Beta1GrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + )