From dab2d539a1c89c0a5f09df4c4cab4d86f1a4ab08 Mon Sep 17 00:00:00 2001 From: Yoshi Automation Bot Date: Tue, 22 Dec 2020 09:40:46 -0800 Subject: [PATCH] fix: remove v1beta1 (#127) v1beta1 API has been turned down. --- .pre-commit-config.yaml | 17 + CONTRIBUTING.rst | 21 +- docs/asset_v1beta1/services.rst | 6 - docs/asset_v1beta1/types.rst | 6 - docs/index.rst | 9 - .../asset_service/transports/__init__.py | 1 - .../services/asset_service/transports/grpc.py | 19 +- .../asset_service/transports/grpc_asyncio.py | 15 +- google/cloud/asset_v1/types/__init__.py | 3 +- google/cloud/asset_v1/types/asset_service.py | 9 +- google/cloud/asset_v1beta1/__init__.py | 45 - google/cloud/asset_v1beta1/py.typed | 2 - .../cloud/asset_v1beta1/services/__init__.py | 16 - .../services/asset_service/__init__.py | 24 - .../services/asset_service/async_client.py | 280 ----- .../services/asset_service/client.py | 457 ------- .../asset_service/transports/__init__.py | 36 - .../services/asset_service/transports/base.py | 154 --- .../services/asset_service/transports/grpc.py | 316 ----- .../asset_service/transports/grpc_asyncio.py | 320 ----- google/cloud/asset_v1beta1/types/__init__.py | 45 - .../asset_v1beta1/types/asset_service.py | 210 ---- google/cloud/asset_v1beta1/types/assets.py | 158 --- .../asset_service/transports/__init__.py | 1 - .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 8 + .../cloud/asset_v1p1beta1/types/__init__.py | 1 - .../asset_service/transports/__init__.py | 1 - .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 8 + .../cloud/asset_v1p2beta1/types/__init__.py | 3 +- .../asset_service/transports/__init__.py | 1 - .../services/asset_service/transports/grpc.py | 19 +- .../asset_service/transports/grpc_asyncio.py | 15 +- .../cloud/asset_v1p4beta1/types/__init__.py | 1 - .../asset_service/transports/__init__.py | 1 - .../services/asset_service/transports/grpc.py | 10 +- .../asset_service/transports/grpc_asyncio.py | 8 + .../cloud/asset_v1p5beta1/types/__init__.py | 3 +- noxfile.py | 2 +- samples/snippets/noxfile.py | 17 +- synth.metadata | 203 +-- synth.py | 20 +- .../unit/gapic/asset_v1/test_asset_service.py | 8 + tests/unit/gapic/asset_v1beta1/__init__.py | 1 - .../gapic/asset_v1beta1/test_asset_service.py | 1120 ----------------- .../asset_v1p1beta1/test_asset_service.py | 8 + .../asset_v1p2beta1/test_asset_service.py | 8 + .../asset_v1p4beta1/test_asset_service.py | 8 + .../asset_v1p5beta1/test_asset_service.py | 8 + 50 files changed, 201 insertions(+), 3471 deletions(-) create mode 100644 .pre-commit-config.yaml delete mode 100644 docs/asset_v1beta1/services.rst delete mode 100644 docs/asset_v1beta1/types.rst delete mode 100644 google/cloud/asset_v1beta1/__init__.py delete mode 100644 google/cloud/asset_v1beta1/py.typed delete mode 100644 google/cloud/asset_v1beta1/services/__init__.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/__init__.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/async_client.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/client.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/transports/base.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py delete mode 100644 google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py delete mode 100644 google/cloud/asset_v1beta1/types/__init__.py delete mode 100644 google/cloud/asset_v1beta1/types/asset_service.py delete mode 100644 google/cloud/asset_v1beta1/types/assets.py delete mode 100644 tests/unit/gapic/asset_v1beta1/__init__.py delete mode 100644 tests/unit/gapic/asset_v1beta1/test_asset_service.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000..a9024b15 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,17 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.4.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml +- repo: https://github.com/psf/black + rev: 19.10b0 + hooks: + - id: black +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.8.4 + hooks: + - id: flake8 diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index a6c5d315..35bf37c0 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -21,8 +21,8 @@ In order to add a feature: - The feature must be documented in both the API and narrative documentation. -- The feature must work fully on the following CPython versions: 2.7, - 3.5, 3.6, 3.7 and 3.8 on both UNIX and Windows. +- The feature must work fully on the following CPython versions: + 3.6, 3.7, 3.8 and 3.9 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -111,6 +111,16 @@ Coding Style should point to the official ``googleapis`` checkout and the the branch should be the main branch on that remote (``master``). +- This repository contains configuration for the + `pre-commit `__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + Exceptions to PEP8: - Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for @@ -192,25 +202,24 @@ Supported Python Versions We support: -- `Python 3.5`_ - `Python 3.6`_ - `Python 3.7`_ - `Python 3.8`_ +- `Python 3.9`_ -.. _Python 3.5: https://docs.python.org/3.5/ .. _Python 3.6: https://docs.python.org/3.6/ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ Supported versions can be found in our ``noxfile.py`` `config`_. .. _config: https://github.com/googleapis/python-asset/blob/master/noxfile.py -Python 2.7 support is deprecated. All code changes should maintain Python 2.7 compatibility until January 1, 2020. We also explicitly decided to support Python 3 beginning with version -3.5. Reasons for this include: +3.6. Reasons for this include: - Encouraging use of newest versions of Python 3 - Taking the lead of `prominent`_ open-source `projects`_ diff --git a/docs/asset_v1beta1/services.rst b/docs/asset_v1beta1/services.rst deleted file mode 100644 index f14b6c6f..00000000 --- a/docs/asset_v1beta1/services.rst +++ /dev/null @@ -1,6 +0,0 @@ -Services for Google Cloud Asset v1beta1 API -=========================================== - -.. automodule:: google.cloud.asset_v1beta1.services.asset_service - :members: - :inherited-members: diff --git a/docs/asset_v1beta1/types.rst b/docs/asset_v1beta1/types.rst deleted file mode 100644 index 71ec231b..00000000 --- a/docs/asset_v1beta1/types.rst +++ /dev/null @@ -1,6 +0,0 @@ -Types for Google Cloud Asset v1beta1 API -======================================== - -.. automodule:: google.cloud.asset_v1beta1.types - :members: - :show-inheritance: diff --git a/docs/index.rst b/docs/index.rst index 9424b9c7..5eee2f9d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -58,15 +58,6 @@ v1p5beta1 asset_v1p5beta1/types -v1beta1 -~~~~~~~~~ -.. toctree:: - :maxdepth: 2 - - asset_v1beta1/services - asset_v1beta1/types - - Migration Guide --------------- diff --git a/google/cloud/asset_v1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1/services/asset_service/transports/__init__.py index 624eab74..c077c192 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1/services/asset_service/transports/__init__.py @@ -28,7 +28,6 @@ _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - __all__ = ( "AssetServiceTransport", "AssetServiceGrpcTransport", diff --git a/google/cloud/asset_v1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1/services/asset_service/transports/grpc.py index 26d840cb..acfa9f03 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -149,6 +149,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -167,9 +171,14 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._stubs = {} # type: Dict[str, Callable] + self._operations_client = None # Run the base constructor. super().__init__( @@ -193,7 +202,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[str]): The host for the channel to use. + address (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If @@ -240,13 +249,11 @@ def operations_client(self) -> operations_v1.OperationsClient: client. """ # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsClient( - self.grpc_channel - ) + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) # Return the client from cache. - return self.__dict__["operations_client"] + return self._operations_client @property def export_assets( diff --git a/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py index fe0ed4ff..ae98bc22 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py @@ -194,6 +194,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -212,6 +216,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) # Run the base constructor. @@ -225,6 +233,7 @@ def __init__( ) self._stubs = {} + self._operations_client = None @property def grpc_channel(self) -> aio.Channel: @@ -244,13 +253,13 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: client. """ # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( self.grpc_channel ) # Return the client from cache. - return self.__dict__["operations_client"] + return self._operations_client @property def export_assets( diff --git a/google/cloud/asset_v1/types/__init__.py b/google/cloud/asset_v1/types/__init__.py index eaae81f4..1dfca4b9 100644 --- a/google/cloud/asset_v1/types/__init__.py +++ b/google/cloud/asset_v1/types/__init__.py @@ -55,9 +55,9 @@ IamPolicyAnalysisOutputConfig, AnalyzeIamPolicyLongrunningRequest, AnalyzeIamPolicyLongrunningResponse, + ContentType, ) - __all__ = ( "TemporalAsset", "TimeWindow", @@ -96,4 +96,5 @@ "IamPolicyAnalysisOutputConfig", "AnalyzeIamPolicyLongrunningRequest", "AnalyzeIamPolicyLongrunningResponse", + "ContentType", ) diff --git a/google/cloud/asset_v1/types/asset_service.py b/google/cloud/asset_v1/types/asset_service.py index 83e732b3..c1606428 100644 --- a/google/cloud/asset_v1/types/asset_service.py +++ b/google/cloud/asset_v1/types/asset_service.py @@ -424,10 +424,11 @@ class BigQueryDestination(proto.Message): [partition_spec] determines whether to export to partitioned table(s) and how to partition the data. - If [partition_spec] is unset or [partition_spec.partition_key] - is unset or ``PARTITION_KEY_UNSPECIFIED``, the snapshot - results will be exported to non-partitioned table(s). - [force] will decide whether to overwrite existing table(s). + If [partition_spec] is unset or + [partition_spec.partition_key] is unset or + ``PARTITION_KEY_UNSPECIFIED``, the snapshot results will be + exported to non-partitioned table(s). [force] will decide + whether to overwrite existing table(s). If [partition_spec] is specified. First, the snapshot results will be written to partitioned table(s) with two diff --git a/google/cloud/asset_v1beta1/__init__.py b/google/cloud/asset_v1beta1/__init__.py deleted file mode 100644 index 49e794c1..00000000 --- a/google/cloud/asset_v1beta1/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- 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. -# - -from .services.asset_service import AssetServiceClient -from .types.asset_service import BatchGetAssetsHistoryRequest -from .types.asset_service import BatchGetAssetsHistoryResponse -from .types.asset_service import ContentType -from .types.asset_service import ExportAssetsRequest -from .types.asset_service import ExportAssetsResponse -from .types.asset_service import GcsDestination -from .types.asset_service import OutputConfig -from .types.assets import Asset -from .types.assets import Resource -from .types.assets import TemporalAsset -from .types.assets import TimeWindow - - -__all__ = ( - "Asset", - "BatchGetAssetsHistoryRequest", - "BatchGetAssetsHistoryResponse", - "ContentType", - "ExportAssetsRequest", - "ExportAssetsResponse", - "GcsDestination", - "OutputConfig", - "Resource", - "TemporalAsset", - "TimeWindow", - "AssetServiceClient", -) diff --git a/google/cloud/asset_v1beta1/py.typed b/google/cloud/asset_v1beta1/py.typed deleted file mode 100644 index 3dbb09a3..00000000 --- a/google/cloud/asset_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-asset package uses inline types. diff --git a/google/cloud/asset_v1beta1/services/__init__.py b/google/cloud/asset_v1beta1/services/__init__.py deleted file mode 100644 index 42ffdf2b..00000000 --- a/google/cloud/asset_v1beta1/services/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- 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. -# diff --git a/google/cloud/asset_v1beta1/services/asset_service/__init__.py b/google/cloud/asset_v1beta1/services/asset_service/__init__.py deleted file mode 100644 index ec3c27d2..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- 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. -# - -from .client import AssetServiceClient -from .async_client import AssetServiceAsyncClient - -__all__ = ( - "AssetServiceClient", - "AssetServiceAsyncClient", -) diff --git a/google/cloud/asset_v1beta1/services/asset_service/async_client.py b/google/cloud/asset_v1beta1/services/asset_service/async_client.py deleted file mode 100644 index 225dd6d4..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/async_client.py +++ /dev/null @@ -1,280 +0,0 @@ -# -*- 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. -# - -from collections import OrderedDict -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.asset_v1beta1.types import asset_service -from google.cloud.asset_v1beta1.types import assets - -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport -from .client import AssetServiceClient - - -class AssetServiceAsyncClient: - """Asset service definition.""" - - _client: AssetServiceClient - - DEFAULT_ENDPOINT = AssetServiceClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = AssetServiceClient.DEFAULT_MTLS_ENDPOINT - - asset_path = staticmethod(AssetServiceClient.asset_path) - - common_billing_account_path = staticmethod( - AssetServiceClient.common_billing_account_path - ) - parse_common_billing_account_path = staticmethod( - AssetServiceClient.parse_common_billing_account_path - ) - - common_folder_path = staticmethod(AssetServiceClient.common_folder_path) - parse_common_folder_path = staticmethod(AssetServiceClient.parse_common_folder_path) - - common_organization_path = staticmethod(AssetServiceClient.common_organization_path) - parse_common_organization_path = staticmethod( - AssetServiceClient.parse_common_organization_path - ) - - common_project_path = staticmethod(AssetServiceClient.common_project_path) - parse_common_project_path = staticmethod( - AssetServiceClient.parse_common_project_path - ) - - common_location_path = staticmethod(AssetServiceClient.common_location_path) - parse_common_location_path = staticmethod( - AssetServiceClient.parse_common_location_path - ) - - from_service_account_file = AssetServiceClient.from_service_account_file - from_service_account_json = from_service_account_file - - @property - def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client instance. - """ - return self._client.transport - - get_transport_class = functools.partial( - type(AssetServiceClient).get_transport_class, type(AssetServiceClient) - ) - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, AssetServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the asset service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.AssetServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = AssetServiceClient( - credentials=credentials, - transport=transport, - client_options=client_options, - client_info=client_info, - ) - - async def export_assets( - self, - request: asset_service.ExportAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Exports assets with time and resource types to a given Cloud - Storage location. The output format is newline-delimited JSON. - This API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. - - Args: - request (:class:`~.asset_service.ExportAssetsRequest`): - The request object. Export asset request. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.asset_service.ExportAssetsResponse``: The - export asset response. This message is returned by the - [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] - method in the returned - [google.longrunning.Operation.response][google.longrunning.Operation.response] - field. - - """ - # Create or coerce a protobuf request object. - - request = asset_service.ExportAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.export_assets, - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - asset_service.ExportAssetsResponse, - metadata_type=asset_service.ExportAssetsRequest, - ) - - # Done; return the response. - return response - - async def batch_get_assets_history( - self, - request: asset_service.BatchGetAssetsHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: - r"""Batch gets the update history of assets that overlap a time - window. For RESOURCE content, this API outputs history with - asset in both non-delete or deleted status. For IAM_POLICY - content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the - output history. If a specified asset does not exist, this API - returns an INVALID_ARGUMENT error. - - Args: - request (:class:`~.asset_service.BatchGetAssetsHistoryRequest`): - The request object. Batch get assets history request. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.BatchGetAssetsHistoryResponse: - Batch get assets history response. - """ - # Create or coerce a protobuf request object. - - request = asset_service.BatchGetAssetsHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_get_assets_history, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ("AssetServiceAsyncClient",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/client.py b/google/cloud/asset_v1beta1/services/asset_service/client.py deleted file mode 100644 index 52a01dcf..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/client.py +++ /dev/null @@ -1,457 +0,0 @@ -# -*- 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. -# - -from collections import OrderedDict -from distutils import util -import os -import re -from typing import Callable, 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 # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import 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 - -from google.api_core import operation # type: ignore -from google.api_core import operation_async # type: ignore -from google.cloud.asset_v1beta1.types import asset_service -from google.cloud.asset_v1beta1.types import assets - -from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .transports.grpc import AssetServiceGrpcTransport -from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport - - -class AssetServiceClientMeta(type): - """Metaclass for the AssetService client. - - This provides class-level methods for building and retrieving - support objects (e.g. transport) without polluting the client instance - objects. - """ - - _transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] - _transport_registry["grpc"] = AssetServiceGrpcTransport - _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - - def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: - """Return an appropriate transport class. - - Args: - label: The name of the desired transport. If none is - provided, then the first transport in the registry is used. - - Returns: - The transport class to use. - """ - # If a specific transport is requested, return that one. - if label: - return cls._transport_registry[label] - - # No transport is requested; return the default (that is, the first one - # in the dictionary). - return next(iter(cls._transport_registry.values())) - - -class AssetServiceClient(metaclass=AssetServiceClientMeta): - """Asset service definition.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. - Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to - "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. - Args: - api_endpoint (Optional[str]): the api endpoint to convert. - Returns: - str: converted mTLS api endpoint. - """ - if not api_endpoint: - return api_endpoint - - mtls_endpoint_re = re.compile( - r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" - ) - - m = mtls_endpoint_re.match(api_endpoint) - name, mtls, sandbox, googledomain = m.groups() - if mtls or not googledomain: - return api_endpoint - - if sandbox: - return api_endpoint.replace( - "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" - ) - - return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") - - DEFAULT_ENDPOINT = "cloudasset.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @classmethod - def from_service_account_file(cls, filename: str, *args, **kwargs): - """Creates an instance of this client using the provided credentials - file. - - Args: - filename (str): The path to the service account private key json - file. - args: Additional arguments to pass to the constructor. - kwargs: Additional arguments to pass to the constructor. - - Returns: - {@api.name}: The constructed client. - """ - credentials = service_account.Credentials.from_service_account_file(filename) - kwargs["credentials"] = credentials - return cls(*args, **kwargs) - - from_service_account_json = from_service_account_file - - @property - def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. - - Returns: - AssetServiceTransport: The transport used by the client instance. - """ - return self._transport - - @staticmethod - def asset_path() -> str: - """Return a fully-qualified asset string.""" - return "*".format() - - @staticmethod - def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" - return "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - - @staticmethod - def parse_common_billing_account_path(path: str) -> Dict[str, str]: - """Parse a billing_account path into its component segments.""" - m = re.match(r"^billingAccounts/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" - return "folders/{folder}".format(folder=folder,) - - @staticmethod - def parse_common_folder_path(path: str) -> Dict[str, str]: - """Parse a folder path into its component segments.""" - m = re.match(r"^folders/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" - return "organizations/{organization}".format(organization=organization,) - - @staticmethod - def parse_common_organization_path(path: str) -> Dict[str, str]: - """Parse a organization path into its component segments.""" - m = re.match(r"^organizations/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" - return "projects/{project}".format(project=project,) - - @staticmethod - def parse_common_project_path(path: str) -> Dict[str, str]: - """Parse a project path into its component segments.""" - m = re.match(r"^projects/(?P.+?)$", path) - return m.groupdict() if m else {} - - @staticmethod - def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" - return "projects/{project}/locations/{location}".format( - project=project, location=location, - ) - - @staticmethod - def parse_common_location_path(path: str) -> Dict[str, str]: - """Parse a location path into its component segments.""" - m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) - return m.groupdict() if m else {} - - def __init__( - self, - *, - credentials: Optional[credentials.Credentials] = None, - transport: Union[str, AssetServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the asset service client. - - Args: - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - transport (Union[str, ~.AssetServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (client_options_lib.ClientOptions): Custom options for the - client. It won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint) and "auto" (auto switch to the - default mTLS endpoint if client certificate is present, this is - the default value). However, the ``api_endpoint`` property takes - precedence if provided. - (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable - is "true", then the ``client_cert_source`` property can be used - to provide client certificate for mutual TLS transport. If - not provided, the default SSL client certificate will be used if - present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not - set, no client certificate will be used. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = client_options_lib.from_dict(client_options) - 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")) - ) - - ssl_credentials = None - is_mtls = False - if use_client_cert: - if client_options.client_cert_source: - import grpc # type: ignore - - cert, key = client_options.client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - is_mtls = True - else: - creds = SslCredentials() - is_mtls = creds.is_mtls - ssl_credentials = creds.ssl_credentials if is_mtls else 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": - api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT - ) - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" - ) - - # 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, AssetServiceTransport): - # transport is a AssetServiceTransport instance. - if credentials or client_options.credentials_file: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=api_endpoint, - scopes=client_options.scopes, - ssl_channel_credentials=ssl_credentials, - quota_project_id=client_options.quota_project_id, - client_info=client_info, - ) - - def export_assets( - self, - request: asset_service.ExportAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Exports assets with time and resource types to a given Cloud - Storage location. The output format is newline-delimited JSON. - This API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. - - Args: - request (:class:`~.asset_service.ExportAssetsRequest`): - The request object. Export asset request. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.asset_service.ExportAssetsResponse``: The - export asset response. This message is returned by the - [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] - method in the returned - [google.longrunning.Operation.response][google.longrunning.Operation.response] - field. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.ExportAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.ExportAssetsRequest): - request = asset_service.ExportAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.export_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - asset_service.ExportAssetsResponse, - metadata_type=asset_service.ExportAssetsRequest, - ) - - # Done; return the response. - return response - - def batch_get_assets_history( - self, - request: asset_service.BatchGetAssetsHistoryRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> asset_service.BatchGetAssetsHistoryResponse: - r"""Batch gets the update history of assets that overlap a time - window. For RESOURCE content, this API outputs history with - asset in both non-delete or deleted status. For IAM_POLICY - content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the - output history. If a specified asset does not exist, this API - returns an INVALID_ARGUMENT error. - - Args: - request (:class:`~.asset_service.BatchGetAssetsHistoryRequest`): - The request object. Batch get assets history request. - - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.asset_service.BatchGetAssetsHistoryResponse: - Batch get assets history response. - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a asset_service.BatchGetAssetsHistoryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, asset_service.BatchGetAssetsHistoryRequest): - request = asset_service.BatchGetAssetsHistoryRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.batch_get_assets_history] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -__all__ = ("AssetServiceClient",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py deleted file mode 100644 index 624eab74..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- 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. -# - -from collections import OrderedDict -from typing import Dict, Type - -from .base import AssetServiceTransport -from .grpc import AssetServiceGrpcTransport -from .grpc_asyncio import AssetServiceGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[AssetServiceTransport]] -_transport_registry["grpc"] = AssetServiceGrpcTransport -_transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - - -__all__ = ( - "AssetServiceTransport", - "AssetServiceGrpcTransport", - "AssetServiceGrpcAsyncIOTransport", -) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1beta1/services/asset_service/transports/base.py deleted file mode 100644 index 98418226..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/transports/base.py +++ /dev/null @@ -1,154 +0,0 @@ -# -*- 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. -# - -import abc -import typing -import pkg_resources - -from google import auth # type: ignore -from google.api_core import 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 operations_v1 # type: ignore -from google.auth import credentials # type: ignore - -from google.cloud.asset_v1beta1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore - - -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() - - -class AssetServiceTransport(abc.ABC): - """Abstract transport class for AssetService.""" - - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - *, - host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id - ) - - # Save the credentials. - self._credentials = credentials - - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages(client_info) - - def _prep_wrapped_messages(self, client_info): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.export_assets: gapic_v1.method.wrap_method( - self.export_assets, default_timeout=60.0, client_info=client_info, - ), - self.batch_get_assets_history: gapic_v1.method.wrap_method( - self.batch_get_assets_history, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def export_assets( - self, - ) -> typing.Callable[ - [asset_service.ExportAssetsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], - ]: - raise NotImplementedError() - - @property - def batch_get_assets_history( - self, - ) -> typing.Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - typing.Union[ - asset_service.BatchGetAssetsHistoryResponse, - typing.Awaitable[asset_service.BatchGetAssetsHistoryResponse], - ], - ]: - raise NotImplementedError() - - -__all__ = ("AssetServiceTransport",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py deleted file mode 100644 index 9a5eb9da..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py +++ /dev/null @@ -1,316 +0,0 @@ -# -*- 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. -# - -import warnings -from typing import Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore - -from google.cloud.asset_v1beta1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore - -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO - - -class AssetServiceGrpcTransport(AssetServiceTransport): - """gRPC backend transport for AssetService. - - Asset service definition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _stubs: Dict[str, Callable] - - def __init__( - self, - *, - host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - quota_project_id: Optional[str] = None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._ssl_channel_credentials = ssl_channel_credentials - - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - elif api_mtls_endpoint: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - self._ssl_channel_credentials = ssl_credentials - else: - host = host if ":" in host else host + ":443" - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - @classmethod - def create_channel( - cls, - host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - address (Optionsl[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - grpc.Channel: A gRPC channel object. - - Raises: - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Return the channel designed to connect to this service. - """ - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def export_assets( - self, - ) -> Callable[[asset_service.ExportAssetsRequest], operations.Operation]: - r"""Return a callable for the export assets method over gRPC. - - Exports assets with time and resource types to a given Cloud - Storage location. The output format is newline-delimited JSON. - This API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. - - Returns: - Callable[[~.ExportAssetsRequest], - ~.Operation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "export_assets" not in self._stubs: - self._stubs["export_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.asset.v1beta1.AssetService/ExportAssets", - request_serializer=asset_service.ExportAssetsRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["export_assets"] - - @property - def batch_get_assets_history( - self, - ) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - asset_service.BatchGetAssetsHistoryResponse, - ]: - r"""Return a callable for the batch get assets history method over gRPC. - - Batch gets the update history of assets that overlap a time - window. For RESOURCE content, this API outputs history with - asset in both non-delete or deleted status. For IAM_POLICY - content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the - output history. If a specified asset does not exist, this API - returns an INVALID_ARGUMENT error. - - Returns: - Callable[[~.BatchGetAssetsHistoryRequest], - ~.BatchGetAssetsHistoryResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "batch_get_assets_history" not in self._stubs: - self._stubs["batch_get_assets_history"] = self.grpc_channel.unary_unary( - "/google.cloud.asset.v1beta1.AssetService/BatchGetAssetsHistory", - request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, - response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, - ) - return self._stubs["batch_get_assets_history"] - - -__all__ = ("AssetServiceGrpcTransport",) diff --git a/google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py deleted file mode 100644 index 0331ade0..00000000 --- a/google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py +++ /dev/null @@ -1,320 +0,0 @@ -# -*- 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. -# - -import warnings -from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import gapic_v1 # type: ignore -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.asset_v1beta1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore - -from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO -from .grpc import AssetServiceGrpcTransport - - -class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): - """gRPC AsyncIO backend transport for AssetService. - - Asset service definition. - - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. - - It sends protocol buffers over the wire using gRPC (which is built on - top of HTTP/2); the ``grpcio`` package must be installed. - """ - - _grpc_channel: aio.Channel - _stubs: Dict[str, Callable] = {} - - @classmethod - def create_channel( - cls, - host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs, - ) -> aio.Channel: - """Create and return a gRPC AsyncIO channel object. - Args: - address (Optional[str]): The host for the channel to use. - credentials (Optional[~.Credentials]): The - authorization credentials to attach to requests. These - credentials identify this application to the service. If - none are specified, the client will attempt to ascertain - the credentials from the environment. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - kwargs (Optional[dict]): Keyword arguments, which are passed to the - channel creation. - Returns: - aio.Channel: A gRPC AsyncIO channel object. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - quota_project_id=None, - client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - credentials (Optional[google.auth.credentials.Credentials]): The - authorization credentials to attach to requests. These - credentials identify the application to the service; if none - are specified, the client will attempt to ascertain the - credentials from the environment. - This argument is ignored if ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional list of scopes needed for this - service. These are only used when credentials are not specified and - are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. - If provided, it overrides the ``host`` argument and tries to create - a mutual TLS channel with client SSL credentials from - ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): - Deprecated. A callback to provide client SSL certificate bytes and - private key bytes, both in PEM format. It is ignored if - ``api_mtls_endpoint`` is None. - ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for grpc channel. It is ignored if ``channel`` is provided. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - client_info (google.api_core.gapic_v1.client_info.ClientInfo): - The client info used to send a user-agent string along with - API requests. If ``None``, then default info will be used. - Generally, you only need to set this if you're developing - your own client library. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` - and ``credentials_file`` are passed. - """ - self._ssl_channel_credentials = ssl_channel_credentials - - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - self._ssl_channel_credentials = None - elif api_mtls_endpoint: - warnings.warn( - "api_mtls_endpoint and client_cert_source are deprecated", - DeprecationWarning, - ) - - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - self._ssl_channel_credentials = ssl_credentials - else: - host = host if ":" in host else host + ":443" - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_channel_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - client_info=client_info, - ) - - self._stubs = {} - - @property - def grpc_channel(self) -> aio.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def export_assets( - self, - ) -> Callable[[asset_service.ExportAssetsRequest], Awaitable[operations.Operation]]: - r"""Return a callable for the export assets method over gRPC. - - Exports assets with time and resource types to a given Cloud - Storage location. The output format is newline-delimited JSON. - This API implements the - [google.longrunning.Operation][google.longrunning.Operation] API - allowing you to keep track of the export. - - Returns: - Callable[[~.ExportAssetsRequest], - Awaitable[~.Operation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "export_assets" not in self._stubs: - self._stubs["export_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.asset.v1beta1.AssetService/ExportAssets", - request_serializer=asset_service.ExportAssetsRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["export_assets"] - - @property - def batch_get_assets_history( - self, - ) -> Callable[ - [asset_service.BatchGetAssetsHistoryRequest], - Awaitable[asset_service.BatchGetAssetsHistoryResponse], - ]: - r"""Return a callable for the batch get assets history method over gRPC. - - Batch gets the update history of assets that overlap a time - window. For RESOURCE content, this API outputs history with - asset in both non-delete or deleted status. For IAM_POLICY - content, this API outputs history when the asset and its - attached IAM POLICY both exist. This can create gaps in the - output history. If a specified asset does not exist, this API - returns an INVALID_ARGUMENT error. - - Returns: - Callable[[~.BatchGetAssetsHistoryRequest], - Awaitable[~.BatchGetAssetsHistoryResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "batch_get_assets_history" not in self._stubs: - self._stubs["batch_get_assets_history"] = self.grpc_channel.unary_unary( - "/google.cloud.asset.v1beta1.AssetService/BatchGetAssetsHistory", - request_serializer=asset_service.BatchGetAssetsHistoryRequest.serialize, - response_deserializer=asset_service.BatchGetAssetsHistoryResponse.deserialize, - ) - return self._stubs["batch_get_assets_history"] - - -__all__ = ("AssetServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/asset_v1beta1/types/__init__.py b/google/cloud/asset_v1beta1/types/__init__.py deleted file mode 100644 index 1269a393..00000000 --- a/google/cloud/asset_v1beta1/types/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -# -*- 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. -# - -from .assets import ( - TemporalAsset, - TimeWindow, - Asset, - Resource, -) -from .asset_service import ( - ExportAssetsRequest, - ExportAssetsResponse, - BatchGetAssetsHistoryRequest, - BatchGetAssetsHistoryResponse, - OutputConfig, - GcsDestination, -) - - -__all__ = ( - "TemporalAsset", - "TimeWindow", - "Asset", - "Resource", - "ExportAssetsRequest", - "ExportAssetsResponse", - "BatchGetAssetsHistoryRequest", - "BatchGetAssetsHistoryResponse", - "OutputConfig", - "GcsDestination", -) diff --git a/google/cloud/asset_v1beta1/types/asset_service.py b/google/cloud/asset_v1beta1/types/asset_service.py deleted file mode 100644 index 6294f3e7..00000000 --- a/google/cloud/asset_v1beta1/types/asset_service.py +++ /dev/null @@ -1,210 +0,0 @@ -# -*- 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. -# - -import proto # type: ignore - - -from google.cloud.asset_v1beta1.types import assets as gca_assets -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.asset.v1beta1", - manifest={ - "ContentType", - "ExportAssetsRequest", - "ExportAssetsResponse", - "BatchGetAssetsHistoryRequest", - "BatchGetAssetsHistoryResponse", - "OutputConfig", - "GcsDestination", - }, -) - - -class ContentType(proto.Enum): - r"""Asset content type.""" - CONTENT_TYPE_UNSPECIFIED = 0 - RESOURCE = 1 - IAM_POLICY = 2 - - -class ExportAssetsRequest(proto.Message): - r"""Export asset request. - - Attributes: - parent (str): - Required. The relative name of the root - asset. This can only be an organization number - (such as "organizations/123"), a project ID - (such as "projects/my-project-id"), a project - number (such as "projects/12345"), or a folder - number (such as "folders/123"). - read_time (~.timestamp.Timestamp): - Timestamp to take an asset snapshot. This can - only be set to a timestamp between 2018-10-02 - UTC (inclusive) and the current time. If not - specified, the current time will be used. Due to - delays in resource data collection and indexing, - there is a volatile window during which running - the same query may get different results. - asset_types (Sequence[str]): - A list of asset types of which to take a snapshot for. For - example: "google.compute.Disk". If specified, only matching - assets will be returned. See `Introduction to Cloud Asset - Inventory `__ - for all supported asset types. - content_type (~.asset_service.ContentType): - Asset content type. If not specified, no - content but the asset name will be returned. - output_config (~.asset_service.OutputConfig): - Required. Output configuration indicating - where the results will be output to. All results - will be in newline delimited JSON format. - """ - - parent = proto.Field(proto.STRING, number=1) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - asset_types = proto.RepeatedField(proto.STRING, number=3) - - content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) - - output_config = proto.Field(proto.MESSAGE, number=5, message="OutputConfig",) - - -class ExportAssetsResponse(proto.Message): - r"""The export asset response. This message is returned by the - [google.longrunning.Operations.GetOperation][google.longrunning.Operations.GetOperation] - method in the returned - [google.longrunning.Operation.response][google.longrunning.Operation.response] - field. - - Attributes: - read_time (~.timestamp.Timestamp): - Time the snapshot was taken. - output_config (~.asset_service.OutputConfig): - Output configuration indicating where the - results were output to. All results are in JSON - format. - """ - - read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - output_config = proto.Field(proto.MESSAGE, number=2, message="OutputConfig",) - - -class BatchGetAssetsHistoryRequest(proto.Message): - r"""Batch get assets history request. - - Attributes: - parent (str): - Required. The relative name of the root - asset. It can only be an organization number - (such as "organizations/123"), a project ID - (such as "projects/my-project-id")", or a - project number (such as "projects/12345"). - asset_names (Sequence[str]): - A list of the full names of the assets. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource - Names `__ - for more info. - - The request becomes a no-op if the asset name list is empty, - and the max size of the asset name list is 100 in one - request. - content_type (~.asset_service.ContentType): - Optional. The content type. - read_time_window (~.gca_assets.TimeWindow): - Optional. The time window for the asset history. Both - start_time and end_time are optional and if set, it must be - after 2018-10-02 UTC. If end_time is not set, it is default - to current timestamp. If start_time is not set, the snapshot - of the assets at end_time will be returned. The returned - results contain all temporal assets whose time window - overlap with read_time_window. - """ - - parent = proto.Field(proto.STRING, number=1) - - asset_names = proto.RepeatedField(proto.STRING, number=2) - - content_type = proto.Field(proto.ENUM, number=3, enum="ContentType",) - - read_time_window = proto.Field( - proto.MESSAGE, number=4, message=gca_assets.TimeWindow, - ) - - -class BatchGetAssetsHistoryResponse(proto.Message): - r"""Batch get assets history response. - - Attributes: - assets (Sequence[~.gca_assets.TemporalAsset]): - A list of assets with valid time windows. - """ - - assets = proto.RepeatedField( - proto.MESSAGE, number=1, message=gca_assets.TemporalAsset, - ) - - -class OutputConfig(proto.Message): - r"""Output configuration for export assets destination. - - Attributes: - gcs_destination (~.asset_service.GcsDestination): - Destination on Cloud Storage. - """ - - gcs_destination = proto.Field( - proto.MESSAGE, number=1, oneof="destination", message="GcsDestination", - ) - - -class GcsDestination(proto.Message): - r"""A Cloud Storage location. - - Attributes: - uri (str): - The uri of the Cloud Storage object. It's the same uri that - is used by gsutil. For example: - "gs://bucket_name/object_name". See `Viewing and Editing - Object - Metadata `__ - for more information. - uri_prefix (str): - The uri prefix of all generated Cloud Storage objects. For - example: "gs://bucket_name/object_name_prefix". Each object - uri is in format: "gs://bucket_name/object_name_prefix// and - only contains assets for that type. starts from 0. For - example: - "gs://bucket_name/object_name_prefix/google.compute.disk/0" - is the first shard of output objects containing all - google.compute.disk assets. An INVALID_ARGUMENT error will - be returned if file with the same name - "gs://bucket_name/object_name_prefix" already exists. - """ - - uri = proto.Field(proto.STRING, number=1, oneof="object_uri") - - uri_prefix = proto.Field(proto.STRING, number=2, oneof="object_uri") - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1beta1/types/assets.py b/google/cloud/asset_v1beta1/types/assets.py deleted file mode 100644 index 6f06635b..00000000 --- a/google/cloud/asset_v1beta1/types/assets.py +++ /dev/null @@ -1,158 +0,0 @@ -# -*- 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. -# - -import proto # type: ignore - - -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.asset.v1beta1", - manifest={"TemporalAsset", "TimeWindow", "Asset", "Resource",}, -) - - -class TemporalAsset(proto.Message): - r"""Temporal asset. In addition to the asset, the temporal asset - includes the status of the asset and valid from and to time of - it. - - Attributes: - window (~.assets.TimeWindow): - The time window when the asset data and state - was observed. - deleted (bool): - If the asset is deleted or not. - asset (~.assets.Asset): - Asset. - """ - - window = proto.Field(proto.MESSAGE, number=1, message="TimeWindow",) - - deleted = proto.Field(proto.BOOL, number=2) - - asset = proto.Field(proto.MESSAGE, number=3, message="Asset",) - - -class TimeWindow(proto.Message): - r"""A time window of (start_time, end_time]. - - Attributes: - start_time (~.timestamp.Timestamp): - Start time of the time window (exclusive). - end_time (~.timestamp.Timestamp): - End time of the time window (inclusive). - Current timestamp if not specified. - """ - - start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - -class Asset(proto.Message): - r"""Cloud asset. This includes all Google Cloud Platform - resources, Cloud IAM policies, and other non-GCP assets. - - Attributes: - name (str): - The full name of the asset. For example: - ``//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1``. - See `Resource - Names `__ - for more information. - asset_type (str): - Type of the asset. Example: - "google.compute.Disk". - resource (~.assets.Resource): - Representation of the resource. - iam_policy (~.policy.Policy): - Representation of the actual Cloud IAM policy - set on a cloud resource. For each resource, - there must be at most one Cloud IAM policy set - on it. - """ - - name = proto.Field(proto.STRING, number=1) - - asset_type = proto.Field(proto.STRING, number=2) - - resource = proto.Field(proto.MESSAGE, number=3, message="Resource",) - - iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy.Policy,) - - -class Resource(proto.Message): - r"""Representation of a cloud resource. - - Attributes: - version (str): - The API version. Example: "v1". - discovery_document_uri (str): - The URL of the discovery document containing the resource's - JSON schema. For example: - ``"https://www.googleapis.com/discovery/v1/apis/compute/v1/rest"``. - It will be left unspecified for resources without a - discovery-based API, such as Cloud Bigtable. - discovery_name (str): - The JSON schema name listed in the discovery - document. Example: "Project". It will be left - unspecified for resources (such as Cloud - Bigtable) without a discovery-based API. - resource_url (str): - The REST URL for accessing the resource. An HTTP GET - operation using this URL returns the resource itself. - Example: - ``https://cloudresourcemanager.googleapis.com/v1/projects/my-project-123``. - It will be left unspecified for resources without a REST - API. - parent (str): - The full name of the immediate parent of this resource. See - `Resource - Names `__ - for more information. - - For GCP assets, it is the parent resource defined in the - `Cloud IAM policy - hierarchy `__. - For example: - ``"//cloudresourcemanager.googleapis.com/projects/my_project_123"``. - - For third-party assets, it is up to the users to define. - data (~.struct.Struct): - The content of the resource, in which some - sensitive fields are scrubbed away and may not - be present. - """ - - version = proto.Field(proto.STRING, number=1) - - discovery_document_uri = proto.Field(proto.STRING, number=2) - - discovery_name = proto.Field(proto.STRING, number=3) - - resource_url = proto.Field(proto.STRING, number=4) - - parent = proto.Field(proto.STRING, number=5) - - data = proto.Field(proto.MESSAGE, number=6, message=struct.Struct,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py index 624eab74..c077c192 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py @@ -28,7 +28,6 @@ _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - __all__ = ( "AssetServiceTransport", "AssetServiceGrpcTransport", diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py index 42bcaa91..1310afdb 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py @@ -146,6 +146,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -164,6 +168,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._stubs = {} # type: Dict[str, Callable] @@ -190,7 +198,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[str]): The host for the channel to use. + address (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py index 8f42e007..6810dd05 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py @@ -191,6 +191,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -209,6 +213,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) # Run the base constructor. diff --git a/google/cloud/asset_v1p1beta1/types/__init__.py b/google/cloud/asset_v1p1beta1/types/__init__.py index da73ca1e..a5dd1af7 100644 --- a/google/cloud/asset_v1p1beta1/types/__init__.py +++ b/google/cloud/asset_v1p1beta1/types/__init__.py @@ -27,7 +27,6 @@ SearchAllIamPoliciesResponse, ) - __all__ = ( "StandardResourceMetadata", "IamPolicySearchResult", diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py index 624eab74..c077c192 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py @@ -28,7 +28,6 @@ _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - __all__ = ( "AssetServiceTransport", "AssetServiceGrpcTransport", diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py index e6b034a2..e30ae165 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py @@ -147,6 +147,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -165,6 +169,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._stubs = {} # type: Dict[str, Callable] @@ -191,7 +199,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[str]): The host for the channel to use. + address (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py index 2d7ef306..59b54443 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py @@ -192,6 +192,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -210,6 +214,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) # Run the base constructor. diff --git a/google/cloud/asset_v1p2beta1/types/__init__.py b/google/cloud/asset_v1p2beta1/types/__init__.py index 43e90db3..7c5b86e3 100644 --- a/google/cloud/asset_v1p2beta1/types/__init__.py +++ b/google/cloud/asset_v1p2beta1/types/__init__.py @@ -33,9 +33,9 @@ PubsubDestination, FeedOutputConfig, Feed, + ContentType, ) - __all__ = ( "TemporalAsset", "TimeWindow", @@ -52,4 +52,5 @@ "PubsubDestination", "FeedOutputConfig", "Feed", + "ContentType", ) diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py index 624eab74..c077c192 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py @@ -28,7 +28,6 @@ _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - __all__ = ( "AssetServiceTransport", "AssetServiceGrpcTransport", diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py index 981aea53..301fb6f9 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py @@ -148,6 +148,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -166,9 +170,14 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._stubs = {} # type: Dict[str, Callable] + self._operations_client = None # Run the base constructor. super().__init__( @@ -192,7 +201,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[str]): The host for the channel to use. + address (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If @@ -239,13 +248,11 @@ def operations_client(self) -> operations_v1.OperationsClient: client. """ # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsClient( - self.grpc_channel - ) + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) # Return the client from cache. - return self.__dict__["operations_client"] + return self._operations_client @property def analyze_iam_policy( diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py index 3740eabf..52f74e7d 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py @@ -193,6 +193,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -211,6 +215,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) # Run the base constructor. @@ -224,6 +232,7 @@ def __init__( ) self._stubs = {} + self._operations_client = None @property def grpc_channel(self) -> aio.Channel: @@ -243,13 +252,13 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: client. """ # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( self.grpc_channel ) # Return the client from cache. - return self.__dict__["operations_client"] + return self._operations_client @property def analyze_iam_policy( diff --git a/google/cloud/asset_v1p4beta1/types/__init__.py b/google/cloud/asset_v1p4beta1/types/__init__.py index 06794497..72b608ca 100644 --- a/google/cloud/asset_v1p4beta1/types/__init__.py +++ b/google/cloud/asset_v1p4beta1/types/__init__.py @@ -25,7 +25,6 @@ ExportIamPolicyAnalysisResponse, ) - __all__ = ( "IamPolicyAnalysisResult", "IamPolicyAnalysisQuery", diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py index 624eab74..c077c192 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py @@ -28,7 +28,6 @@ _transport_registry["grpc"] = AssetServiceGrpcTransport _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport - __all__ = ( "AssetServiceTransport", "AssetServiceGrpcTransport", diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py index a0670c85..85dd47c6 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py @@ -146,6 +146,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -164,6 +168,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._stubs = {} # type: Dict[str, Callable] @@ -190,7 +198,7 @@ def create_channel( ) -> grpc.Channel: """Create and return a gRPC channel object. Args: - address (Optionsl[str]): The host for the channel to use. + address (Optional[str]): The host for the channel to use. credentials (Optional[~.Credentials]): The authorization credentials to attach to requests. These credentials identify this application to the service. If diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py index 87abf403..5c2586db 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py @@ -191,6 +191,10 @@ def __init__( ssl_credentials=ssl_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) self._ssl_channel_credentials = ssl_credentials else: @@ -209,6 +213,10 @@ def __init__( ssl_credentials=ssl_channel_credentials, scopes=scopes or self.AUTH_SCOPES, quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) # Run the base constructor. diff --git a/google/cloud/asset_v1p5beta1/types/__init__.py b/google/cloud/asset_v1p5beta1/types/__init__.py index 4f19a666..c5930340 100644 --- a/google/cloud/asset_v1p5beta1/types/__init__.py +++ b/google/cloud/asset_v1p5beta1/types/__init__.py @@ -22,12 +22,13 @@ from .asset_service import ( ListAssetsRequest, ListAssetsResponse, + ContentType, ) - __all__ = ( "Asset", "Resource", "ListAssetsRequest", "ListAssetsResponse", + "ContentType", ) diff --git a/noxfile.py b/noxfile.py index 41eeb037..7f6a9544 100644 --- a/noxfile.py +++ b/noxfile.py @@ -28,7 +28,7 @@ DEFAULT_PYTHON_VERSION = "3.8" SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] @nox.session(python=DEFAULT_PYTHON_VERSION) diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index b90eef00..bca0522e 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -17,6 +17,7 @@ import os from pathlib import Path import sys +from typing import Callable, Dict, List, Optional import nox @@ -68,7 +69,7 @@ TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) -def get_pytest_env_vars(): +def get_pytest_env_vars() -> Dict[str, str]: """Returns a dict for pytest invocation.""" ret = {} @@ -97,7 +98,7 @@ def get_pytest_env_vars(): # -def _determine_local_import_names(start_dir): +def _determine_local_import_names(start_dir: str) -> List[str]: """Determines all import names that should be considered "local". This is used when running the linter to insure that import order is @@ -135,7 +136,7 @@ def _determine_local_import_names(start_dir): @nox.session -def lint(session): +def lint(session: nox.sessions.Session) -> None: if not TEST_CONFIG['enforce_type_hints']: session.install("flake8", "flake8-import-order") else: @@ -154,7 +155,7 @@ def lint(session): @nox.session -def blacken(session): +def blacken(session: nox.sessions.Session) -> None: session.install("black") python_files = [path for path in os.listdir(".") if path.endswith(".py")] @@ -168,7 +169,7 @@ def blacken(session): PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] -def _session_tests(session, post_install=None): +def _session_tests(session: nox.sessions.Session, post_install: Callable = None) -> None: """Runs py.test for a particular project.""" if os.path.exists("requirements.txt"): session.install("-r", "requirements.txt") @@ -194,7 +195,7 @@ def _session_tests(session, post_install=None): @nox.session(python=ALL_VERSIONS) -def py(session): +def py(session: nox.sessions.Session) -> None: """Runs py.test for a sample using the specified version of Python.""" if session.python in TESTED_VERSIONS: _session_tests(session) @@ -209,7 +210,7 @@ def py(session): # -def _get_repo_root(): +def _get_repo_root() -> Optional[str]: """ Returns the root folder of the project. """ # Get root of this repository. Assume we don't have directories nested deeper than 10 items. p = Path(os.getcwd()) @@ -232,7 +233,7 @@ def _get_repo_root(): @nox.session @nox.parametrize("path", GENERATED_READMES) -def readmegen(session, path): +def readmegen(session: nox.sessions.Session, path: str) -> None: """(Re-)generates the readme for a sample.""" session.install("jinja2", "pyyaml") dir_ = os.path.dirname(path) diff --git a/synth.metadata b/synth.metadata index ec14d3d5..a46a7786 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,43 +3,34 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-asset.git", - "sha": "a020a9c0bfe43d2e079579f39292a7a970ceca8e" + "remote": "git@github.com:googleapis/python-asset.git", + "sha": "0681277e9b1a2e57f371838e6014288340f10e0d" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "2f019bf70bfe06f1e2af1b04011b0a2405190e43", - "internalRef": "343202295" + "sha": "bfdb1df3876564228c43c3ea64edf5f90d10d92f", + "internalRef": "348500610" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "a073c873f3928c561bdf87fdfbf1d081d1998984" + "sha": "363fe305e9ce34a6cd53951c6ee5f997094b54ee" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "a073c873f3928c561bdf87fdfbf1d081d1998984" + "sha": "363fe305e9ce34a6cd53951c6ee5f997094b54ee" } } ], "destinations": [ - { - "client": { - "source": "googleapis", - "apiName": "asset", - "apiVersion": "v1beta1", - "language": "python", - "generator": "bazel" - } - }, { "client": { "source": "googleapis", @@ -85,187 +76,5 @@ "generator": "bazel" } } - ], - "generatedFiles": [ - ".flake8", - ".github/CONTRIBUTING.md", - ".github/ISSUE_TEMPLATE/bug_report.md", - ".github/ISSUE_TEMPLATE/feature_request.md", - ".github/ISSUE_TEMPLATE/support_request.md", - ".github/PULL_REQUEST_TEMPLATE.md", - ".github/release-please.yml", - ".github/snippet-bot.yml", - ".gitignore", - ".kokoro/build.sh", - ".kokoro/continuous/common.cfg", - ".kokoro/continuous/continuous.cfg", - ".kokoro/docker/docs/Dockerfile", - ".kokoro/docker/docs/fetch_gpg_keys.sh", - ".kokoro/docs/common.cfg", - ".kokoro/docs/docs-presubmit.cfg", - ".kokoro/docs/docs.cfg", - ".kokoro/populate-secrets.sh", - ".kokoro/presubmit/common.cfg", - ".kokoro/presubmit/presubmit.cfg", - ".kokoro/publish-docs.sh", - ".kokoro/release.sh", - ".kokoro/release/common.cfg", - ".kokoro/release/release.cfg", - ".kokoro/samples/lint/common.cfg", - ".kokoro/samples/lint/continuous.cfg", - ".kokoro/samples/lint/periodic.cfg", - ".kokoro/samples/lint/presubmit.cfg", - ".kokoro/samples/python3.6/common.cfg", - ".kokoro/samples/python3.6/continuous.cfg", - ".kokoro/samples/python3.6/periodic.cfg", - ".kokoro/samples/python3.6/presubmit.cfg", - ".kokoro/samples/python3.7/common.cfg", - ".kokoro/samples/python3.7/continuous.cfg", - ".kokoro/samples/python3.7/periodic.cfg", - ".kokoro/samples/python3.7/presubmit.cfg", - ".kokoro/samples/python3.8/common.cfg", - ".kokoro/samples/python3.8/continuous.cfg", - ".kokoro/samples/python3.8/periodic.cfg", - ".kokoro/samples/python3.8/presubmit.cfg", - ".kokoro/test-samples.sh", - ".kokoro/trampoline.sh", - ".kokoro/trampoline_v2.sh", - ".trampolinerc", - "CODE_OF_CONDUCT.md", - "CONTRIBUTING.rst", - "LICENSE", - "MANIFEST.in", - "docs/_static/custom.css", - "docs/_templates/layout.html", - "docs/asset_v1/services.rst", - "docs/asset_v1/types.rst", - "docs/asset_v1beta1/services.rst", - "docs/asset_v1beta1/types.rst", - "docs/asset_v1p1beta1/services.rst", - "docs/asset_v1p1beta1/types.rst", - "docs/asset_v1p2beta1/services.rst", - "docs/asset_v1p2beta1/types.rst", - "docs/asset_v1p4beta1/services.rst", - "docs/asset_v1p4beta1/types.rst", - "docs/asset_v1p5beta1/services.rst", - "docs/asset_v1p5beta1/types.rst", - "docs/conf.py", - "docs/multiprocessing.rst", - "google/cloud/asset/__init__.py", - "google/cloud/asset/py.typed", - "google/cloud/asset_v1/__init__.py", - "google/cloud/asset_v1/py.typed", - "google/cloud/asset_v1/services/__init__.py", - "google/cloud/asset_v1/services/asset_service/__init__.py", - "google/cloud/asset_v1/services/asset_service/async_client.py", - "google/cloud/asset_v1/services/asset_service/client.py", - "google/cloud/asset_v1/services/asset_service/pagers.py", - "google/cloud/asset_v1/services/asset_service/transports/__init__.py", - "google/cloud/asset_v1/services/asset_service/transports/base.py", - "google/cloud/asset_v1/services/asset_service/transports/grpc.py", - "google/cloud/asset_v1/services/asset_service/transports/grpc_asyncio.py", - "google/cloud/asset_v1/types/__init__.py", - "google/cloud/asset_v1/types/asset_service.py", - "google/cloud/asset_v1/types/assets.py", - "google/cloud/asset_v1beta1/__init__.py", - "google/cloud/asset_v1beta1/py.typed", - "google/cloud/asset_v1beta1/services/__init__.py", - "google/cloud/asset_v1beta1/services/asset_service/__init__.py", - "google/cloud/asset_v1beta1/services/asset_service/async_client.py", - "google/cloud/asset_v1beta1/services/asset_service/client.py", - "google/cloud/asset_v1beta1/services/asset_service/transports/__init__.py", - "google/cloud/asset_v1beta1/services/asset_service/transports/base.py", - "google/cloud/asset_v1beta1/services/asset_service/transports/grpc.py", - "google/cloud/asset_v1beta1/services/asset_service/transports/grpc_asyncio.py", - "google/cloud/asset_v1beta1/types/__init__.py", - "google/cloud/asset_v1beta1/types/asset_service.py", - "google/cloud/asset_v1beta1/types/assets.py", - "google/cloud/asset_v1p1beta1/__init__.py", - "google/cloud/asset_v1p1beta1/py.typed", - "google/cloud/asset_v1p1beta1/services/__init__.py", - "google/cloud/asset_v1p1beta1/services/asset_service/__init__.py", - "google/cloud/asset_v1p1beta1/services/asset_service/async_client.py", - "google/cloud/asset_v1p1beta1/services/asset_service/client.py", - "google/cloud/asset_v1p1beta1/services/asset_service/pagers.py", - "google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py", - "google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py", - "google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py", - "google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc_asyncio.py", - "google/cloud/asset_v1p1beta1/types/__init__.py", - "google/cloud/asset_v1p1beta1/types/asset_service.py", - "google/cloud/asset_v1p1beta1/types/assets.py", - "google/cloud/asset_v1p2beta1/__init__.py", - "google/cloud/asset_v1p2beta1/py.typed", - "google/cloud/asset_v1p2beta1/services/__init__.py", - "google/cloud/asset_v1p2beta1/services/asset_service/__init__.py", - "google/cloud/asset_v1p2beta1/services/asset_service/async_client.py", - "google/cloud/asset_v1p2beta1/services/asset_service/client.py", - "google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py", - "google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py", - "google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py", - "google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc_asyncio.py", - "google/cloud/asset_v1p2beta1/types/__init__.py", - "google/cloud/asset_v1p2beta1/types/asset_service.py", - "google/cloud/asset_v1p2beta1/types/assets.py", - "google/cloud/asset_v1p4beta1/__init__.py", - "google/cloud/asset_v1p4beta1/py.typed", - "google/cloud/asset_v1p4beta1/services/__init__.py", - "google/cloud/asset_v1p4beta1/services/asset_service/__init__.py", - "google/cloud/asset_v1p4beta1/services/asset_service/async_client.py", - "google/cloud/asset_v1p4beta1/services/asset_service/client.py", - "google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py", - "google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py", - "google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py", - "google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc_asyncio.py", - "google/cloud/asset_v1p4beta1/types/__init__.py", - "google/cloud/asset_v1p4beta1/types/asset_service.py", - "google/cloud/asset_v1p4beta1/types/assets.py", - "google/cloud/asset_v1p5beta1/__init__.py", - "google/cloud/asset_v1p5beta1/py.typed", - "google/cloud/asset_v1p5beta1/services/__init__.py", - "google/cloud/asset_v1p5beta1/services/asset_service/__init__.py", - "google/cloud/asset_v1p5beta1/services/asset_service/async_client.py", - "google/cloud/asset_v1p5beta1/services/asset_service/client.py", - "google/cloud/asset_v1p5beta1/services/asset_service/pagers.py", - "google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py", - "google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py", - "google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py", - "google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc_asyncio.py", - "google/cloud/asset_v1p5beta1/types/__init__.py", - "google/cloud/asset_v1p5beta1/types/asset_service.py", - "google/cloud/asset_v1p5beta1/types/assets.py", - "mypy.ini", - "noxfile.py", - "renovate.json", - "samples/AUTHORING_GUIDE.md", - "samples/CONTRIBUTING.md", - "samples/snippets/noxfile.py", - "scripts/decrypt-secrets.sh", - "scripts/fixup_asset_v1_keywords.py", - "scripts/fixup_asset_v1beta1_keywords.py", - "scripts/fixup_asset_v1p1beta1_keywords.py", - "scripts/fixup_asset_v1p2beta1_keywords.py", - "scripts/fixup_asset_v1p4beta1_keywords.py", - "scripts/fixup_asset_v1p5beta1_keywords.py", - "scripts/readme-gen/readme_gen.py", - "scripts/readme-gen/templates/README.tmpl.rst", - "scripts/readme-gen/templates/auth.tmpl.rst", - "scripts/readme-gen/templates/auth_api_key.tmpl.rst", - "scripts/readme-gen/templates/install_deps.tmpl.rst", - "scripts/readme-gen/templates/install_portaudio.tmpl.rst", - "setup.cfg", - "testing/.gitignore", - "tests/unit/gapic/asset_v1/__init__.py", - "tests/unit/gapic/asset_v1/test_asset_service.py", - "tests/unit/gapic/asset_v1beta1/__init__.py", - "tests/unit/gapic/asset_v1beta1/test_asset_service.py", - "tests/unit/gapic/asset_v1p1beta1/__init__.py", - "tests/unit/gapic/asset_v1p1beta1/test_asset_service.py", - "tests/unit/gapic/asset_v1p2beta1/__init__.py", - "tests/unit/gapic/asset_v1p2beta1/test_asset_service.py", - "tests/unit/gapic/asset_v1p4beta1/__init__.py", - "tests/unit/gapic/asset_v1p4beta1/test_asset_service.py", - "tests/unit/gapic/asset_v1p5beta1/__init__.py", - "tests/unit/gapic/asset_v1p5beta1/test_asset_service.py" ] } \ No newline at end of file diff --git a/synth.py b/synth.py index eef5a28e..091a879c 100644 --- a/synth.py +++ b/synth.py @@ -22,7 +22,7 @@ gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() -versions = ["v1beta1", "v1p1beta1", "v1p2beta1", "v1p4beta1", "v1p5beta1", "v1"] +versions = ["v1p1beta1", "v1p2beta1", "v1p4beta1", "v1p5beta1", "v1"] excludes = ["setup.py", "nox*.py", "README.rst", "docs/conf.py", "docs/index.rst"] @@ -88,24 +88,6 @@ def parse_asset_path.*?@staticmethod""", python.py_samples(skip_readmes=True) -s.replace( - "noxfile.py", - "google\.cloud\.cloudasset", - "google/cloud", -) - -s.replace( - "noxfile.py", - '''["']--cov=google\.cloud["'],''', - "", -) - -s.replace( - "noxfile.py", - """"--cov=tests.unit",""", - """"--cov=tests/unit",""", -) - # Temporarily disable warnings due to # https://github.com/googleapis/gapic-generator-python/issues/525 s.replace("noxfile.py", '[\"\']-W[\"\']', '# "-W"') diff --git a/tests/unit/gapic/asset_v1/test_asset_service.py b/tests/unit/gapic/asset_v1/test_asset_service.py index ff391b24..69785f09 100644 --- a/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1/test_asset_service.py @@ -2969,6 +2969,10 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @@ -3007,6 +3011,10 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/asset_v1beta1/__init__.py b/tests/unit/gapic/asset_v1beta1/__init__.py deleted file mode 100644 index 8b137891..00000000 --- a/tests/unit/gapic/asset_v1beta1/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/tests/unit/gapic/asset_v1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1beta1/test_asset_service.py deleted file mode 100644 index 83bf52f0..00000000 --- a/tests/unit/gapic/asset_v1beta1/test_asset_service.py +++ /dev/null @@ -1,1120 +0,0 @@ -# -*- 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. -# - -import os -import mock - -import grpc -from grpc.experimental import aio -import math -import pytest -from proto.marshal.rules.dates import DurationRule, TimestampRule - -from google import auth -from google.api_core import client_options -from google.api_core import exceptions -from google.api_core import future -from google.api_core import gapic_v1 -from google.api_core import grpc_helpers -from google.api_core import grpc_helpers_async -from google.api_core import operation_async # type: ignore -from google.api_core import operations_v1 -from google.auth import credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.asset_v1beta1.services.asset_service import AssetServiceAsyncClient -from google.cloud.asset_v1beta1.services.asset_service import AssetServiceClient -from google.cloud.asset_v1beta1.services.asset_service import transports -from google.cloud.asset_v1beta1.types import asset_service -from google.cloud.asset_v1beta1.types import assets -from google.longrunning import operations_pb2 -from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -# If default endpoint is localhost, then default mtls endpoint will be the same. -# This method modifies the default endpoint so the client can produce a different -# mtls endpoint for endpoint testing purposes. -def modify_default_endpoint(client): - return ( - "foo.googleapis.com" - if ("localhost" in client.DEFAULT_ENDPOINT) - else client.DEFAULT_ENDPOINT - ) - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert AssetServiceClient._get_default_mtls_endpoint(None) is None - assert ( - AssetServiceClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint - ) - assert ( - AssetServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - AssetServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - AssetServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert AssetServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - - -@pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient]) -def test_asset_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = client_class.from_service_account_file("dummy/file/path.json") - assert client.transport._credentials == creds - - client = client_class.from_service_account_json("dummy/file/path.json") - assert client.transport._credentials == creds - - assert client.transport._host == "cloudasset.googleapis.com:443" - - -def test_asset_service_client_get_transport_class(): - transport = AssetServiceClient.get_transport_class() - assert transport == transports.AssetServiceGrpcTransport - - transport = AssetServiceClient.get_transport_class("grpc") - assert transport == transports.AssetServiceGrpcTransport - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - ( - AssetServiceAsyncClient, - transports.AssetServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - ], -) -@mock.patch.object( - AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) -) -@mock.patch.object( - AssetServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(AssetServiceAsyncClient), -) -def test_asset_service_client_client_options( - client_class, transport_class, transport_name -): - # Check that if channel is provided we won't create a new one. - with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: - transport = transport_class(credentials=credentials.AnonymousCredentials()) - client = client_class(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch.object(AssetServiceClient, "get_transport_class") as gtc: - client = client_class(transport=transport_name) - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - 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=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "never". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is - # "always". - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): - with mock.patch.object(transport_class, "__init__") as patched: - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_MTLS_ENDPOINT, - scopes=None, - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has - # unsupported value. - with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): - with pytest.raises(MutualTLSChannelError): - client = client_class() - - # 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() - - # 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(client_options=options) - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - ssl_channel_credentials=None, - quota_project_id="octopus", - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name,use_client_cert_env", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "true"), - ( - AssetServiceAsyncClient, - transports.AssetServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "true", - ), - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc", "false"), - ( - AssetServiceAsyncClient, - transports.AssetServiceGrpcAsyncIOTransport, - "grpc_asyncio", - "false", - ), - ], -) -@mock.patch.object( - AssetServiceClient, "DEFAULT_ENDPOINT", modify_default_endpoint(AssetServiceClient) -) -@mock.patch.object( - AssetServiceAsyncClient, - "DEFAULT_ENDPOINT", - modify_default_endpoint(AssetServiceAsyncClient), -) -@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) -def test_asset_service_client_mtls_env_auto( - client_class, transport_class, transport_name, use_client_cert_env -): - # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default - # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. - - # Check the case client_cert_source is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch.object(transport_class, "__init__") as patched: - ssl_channel_creds = mock.Mock() - with mock.patch( - "grpc.ssl_channel_credentials", return_value=ssl_channel_creds - ): - patched.return_value = None - client = client_class(client_options=options) - - if use_client_cert_env == "false": - expected_ssl_channel_creds = None - expected_host = client.DEFAULT_ENDPOINT - else: - expected_ssl_channel_creds = ssl_channel_creds - expected_host = client.DEFAULT_MTLS_ENDPOINT - - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case ADC client cert is provided. Whether client cert is used depends on - # GOOGLE_API_USE_CLIENT_CERTIFICATE value. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None - ): - with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.ssl_credentials", - new_callable=mock.PropertyMock, - ) as ssl_credentials_mock: - if use_client_cert_env == "false": - is_mtls_mock.return_value = False - ssl_credentials_mock.return_value = None - expected_host = client.DEFAULT_ENDPOINT - expected_ssl_channel_creds = None - else: - is_mtls_mock.return_value = True - ssl_credentials_mock.return_value = mock.Mock() - expected_host = client.DEFAULT_MTLS_ENDPOINT - expected_ssl_channel_creds = ( - ssl_credentials_mock.return_value - ) - - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=expected_host, - scopes=None, - ssl_channel_credentials=expected_ssl_channel_creds, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - # Check the case client_cert_source and ADC client cert are not provided. - with mock.patch.dict( - os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} - ): - with mock.patch.object(transport_class, "__init__") as patched: - with mock.patch( - "google.auth.transport.grpc.SslCredentials.__init__", return_value=None - ): - with mock.patch( - "google.auth.transport.grpc.SslCredentials.is_mtls", - new_callable=mock.PropertyMock, - ) as is_mtls_mock: - is_mtls_mock.return_value = False - patched.return_value = None - client = client_class() - patched.assert_called_once_with( - credentials=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=None, - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - ( - AssetServiceAsyncClient, - transports.AssetServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - ], -) -def test_asset_service_client_client_options_scopes( - client_class, transport_class, transport_name -): - # Check the case scopes are provided. - options = client_options.ClientOptions(scopes=["1", "2"],) - 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=None, - credentials_file=None, - host=client.DEFAULT_ENDPOINT, - scopes=["1", "2"], - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -@pytest.mark.parametrize( - "client_class,transport_class,transport_name", - [ - (AssetServiceClient, transports.AssetServiceGrpcTransport, "grpc"), - ( - AssetServiceAsyncClient, - transports.AssetServiceGrpcAsyncIOTransport, - "grpc_asyncio", - ), - ], -) -def test_asset_service_client_client_options_credentials_file( - client_class, transport_class, transport_name -): - # 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) - patched.assert_called_once_with( - credentials=None, - credentials_file="credentials.json", - host=client.DEFAULT_ENDPOINT, - scopes=None, - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_asset_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = AssetServiceClient(client_options={"api_endpoint": "squid.clam.whelk"}) - grpc_transport.assert_called_once_with( - credentials=None, - credentials_file=None, - host="squid.clam.whelk", - scopes=None, - ssl_channel_credentials=None, - quota_project_id=None, - client_info=transports.base.DEFAULT_CLIENT_INFO, - ) - - -def test_export_assets( - transport: str = "grpc", request_type=asset_service.ExportAssetsRequest -): - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_assets), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - - response = client.export_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == asset_service.ExportAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -def test_export_assets_from_dict(): - test_export_assets(request_type=dict) - - -@pytest.mark.asyncio -async def test_export_assets_async( - transport: str = "grpc_asyncio", request_type=asset_service.ExportAssetsRequest -): - client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_assets), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - - response = await client.export_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == asset_service.ExportAssetsRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) - - -@pytest.mark.asyncio -async def test_export_assets_async_from_dict(): - await test_export_assets_async(request_type=dict) - - -def test_export_assets_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ExportAssetsRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_assets), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - - client.export_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_export_assets_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.ExportAssetsRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.export_assets), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - - await client.export_assets(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] - - -def test_batch_get_assets_history( - transport: str = "grpc", request_type=asset_service.BatchGetAssetsHistoryRequest -): - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_assets_history), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = asset_service.BatchGetAssetsHistoryResponse() - - response = client.batch_get_assets_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - - assert args[0] == asset_service.BatchGetAssetsHistoryRequest() - - # Establish that the response is the type that we expect. - - assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) - - -def test_batch_get_assets_history_from_dict(): - test_batch_get_assets_history(request_type=dict) - - -@pytest.mark.asyncio -async def test_batch_get_assets_history_async( - transport: str = "grpc_asyncio", - request_type=asset_service.BatchGetAssetsHistoryRequest, -): - client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_assets_history), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - asset_service.BatchGetAssetsHistoryResponse() - ) - - response = await client.batch_get_assets_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - - assert args[0] == asset_service.BatchGetAssetsHistoryRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.BatchGetAssetsHistoryResponse) - - -@pytest.mark.asyncio -async def test_batch_get_assets_history_async_from_dict(): - await test_batch_get_assets_history_async(request_type=dict) - - -def test_batch_get_assets_history_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.BatchGetAssetsHistoryRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_assets_history), "__call__" - ) as call: - call.return_value = asset_service.BatchGetAssetsHistoryResponse() - - client.batch_get_assets_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] - - -@pytest.mark.asyncio -async def test_batch_get_assets_history_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = asset_service.BatchGetAssetsHistoryRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_get_assets_history), "__call__" - ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - asset_service.BatchGetAssetsHistoryResponse() - ) - - await client.batch_get_assets_history(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, - ) - - # It is an error to provide a credentials file and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) - - # It is an error to provide scopes and a transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = AssetServiceClient( - client_options={"scopes": ["1", "2"]}, transport=transport, - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - client = AssetServiceClient(transport=transport) - assert client.transport is transport - - -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel - - -@pytest.mark.parametrize( - "transport_class", - [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) - assert isinstance(client.transport, transports.AssetServiceGrpcTransport,) - - -def test_asset_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(exceptions.DuplicateCredentialArgs): - transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) - - -def test_asset_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "export_assets", - "batch_get_assets_history", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client - - -def test_asset_service_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file - with mock.patch.object( - auth, "load_credentials_from_file" - ) as load_creds, mock.patch( - "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport( - credentials_file="credentials.json", quota_project_id="octopus", - ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) - - -def test_asset_service_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(auth, "default") as adc, mock.patch( - "google.cloud.asset_v1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) - transport = transports.AssetServiceTransport() - adc.assert_called_once() - - -def test_asset_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - AssetServiceClient() - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, - ) - - -def test_asset_service_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.AssetServiceGrpcTransport( - host="squid.clam.whelk", quota_project_id="octopus" - ) - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", - ) - - -def test_asset_service_host_no_port(): - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="cloudasset.googleapis.com" - ), - ) - assert client.transport._host == "cloudasset.googleapis.com:443" - - -def test_asset_service_host_with_port(): - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="cloudasset.googleapis.com:8000" - ), - ) - assert client.transport._host == "cloudasset.googleapis.com:8000" - - -def test_asset_service_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcTransport( - host="squid.clam.whelk", channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -def test_asset_service_grpc_asyncio_transport_channel(): - channel = aio.insecure_channel("http://localhost/") - - # Check that channel is used if provided. - transport = transports.AssetServiceGrpcAsyncIOTransport( - host="squid.clam.whelk", channel=channel, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None - - -@pytest.mark.parametrize( - "transport_class", - [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], -) -def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel", autospec=True - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - cred = credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() - - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred - - -@pytest.mark.parametrize( - "transport_class", - [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], -) -def test_asset_service_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel", autospec=True - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() - - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) - - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_asset_service_grpc_lro_client(): - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance(transport.operations_client, operations_v1.OperationsClient,) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_asset_service_grpc_lro_async_client(): - client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance(transport.operations_client, operations_v1.OperationsAsyncClient,) - - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client - - -def test_asset_path(): - - expected = "*".format() - actual = AssetServiceClient.asset_path() - assert expected == actual - - -def test_common_billing_account_path(): - billing_account = "squid" - - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, - ) - actual = AssetServiceClient.common_billing_account_path(billing_account) - assert expected == actual - - -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "clam", - } - path = AssetServiceClient.common_billing_account_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_billing_account_path(path) - assert expected == actual - - -def test_common_folder_path(): - folder = "whelk" - - expected = "folders/{folder}".format(folder=folder,) - actual = AssetServiceClient.common_folder_path(folder) - assert expected == actual - - -def test_parse_common_folder_path(): - expected = { - "folder": "octopus", - } - path = AssetServiceClient.common_folder_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_folder_path(path) - assert expected == actual - - -def test_common_organization_path(): - organization = "oyster" - - expected = "organizations/{organization}".format(organization=organization,) - actual = AssetServiceClient.common_organization_path(organization) - assert expected == actual - - -def test_parse_common_organization_path(): - expected = { - "organization": "nudibranch", - } - path = AssetServiceClient.common_organization_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_organization_path(path) - assert expected == actual - - -def test_common_project_path(): - project = "cuttlefish" - - expected = "projects/{project}".format(project=project,) - actual = AssetServiceClient.common_project_path(project) - assert expected == actual - - -def test_parse_common_project_path(): - expected = { - "project": "mussel", - } - path = AssetServiceClient.common_project_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_project_path(path) - assert expected == actual - - -def test_common_location_path(): - project = "winkle" - location = "nautilus" - - expected = "projects/{project}/locations/{location}".format( - project=project, location=location, - ) - actual = AssetServiceClient.common_location_path(project, location) - assert expected == actual - - -def test_parse_common_location_path(): - expected = { - "project": "scallop", - "location": "abalone", - } - path = AssetServiceClient.common_location_path(**expected) - - # Check that the path construction is reversible. - actual = AssetServiceClient.parse_common_location_path(path) - assert expected == actual - - -def test_client_withDEFAULT_CLIENT_INFO(): - client_info = gapic_v1.client_info.ClientInfo() - - with mock.patch.object( - transports.AssetServiceTransport, "_prep_wrapped_messages" - ) as prep: - client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, - ) - prep.assert_called_once_with(client_info) - - with mock.patch.object( - transports.AssetServiceTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = AssetServiceClient.get_transport_class() - transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, - ) - prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py index b1bcae16..b818753e 100644 --- a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -1444,6 +1444,10 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @@ -1482,6 +1486,10 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py index b355f0ab..0bba0cd6 100644 --- a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -1662,6 +1662,10 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @@ -1700,6 +1704,10 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py index a555f8ce..abc1823f 100644 --- a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py @@ -947,6 +947,10 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @@ -985,6 +989,10 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py index 77efc366..37d63e8e 100644 --- a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -904,6 +904,10 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel assert transport._ssl_channel_credentials == mock_ssl_cred @@ -942,6 +946,10 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): scopes=("https://www.googleapis.com/auth/cloud-platform",), ssl_credentials=mock_ssl_cred, quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], ) assert transport.grpc_channel == mock_grpc_channel