From d0b9b21300eb9ad233cd8f7e0c73941bebc5fe46 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 20 May 2021 16:57:35 -0600 Subject: [PATCH] chore: upgrade gapic-generator-python to 0.46.3 (#189) feat: support self-signed JWT flow for service accounts fix: add async client to %name_%version/init.py chore: add autogenerated snippets chore: remove auth, policy, and options from the reserved names list chore: enable GAPIC metadata generation chore: sort subpackages in %namespace/%name/init.py --- docs/asset_v1/asset_service.rst | 1 - docs/asset_v1p1beta1/asset_service.rst | 1 - docs/asset_v1p5beta1/asset_service.rst | 1 - google/cloud/asset/__init__.py | 26 +- google/cloud/asset_v1/__init__.py | 9 +- google/cloud/asset_v1/gapic_metadata.json | 133 ++++ google/cloud/asset_v1/services/__init__.py | 1 - .../services/asset_service/__init__.py | 2 - .../services/asset_service/async_client.py | 71 +- .../asset_v1/services/asset_service/client.py | 94 +-- .../asset_v1/services/asset_service/pagers.py | 6 +- .../asset_service/transports/__init__.py | 2 - .../services/asset_service/transports/base.py | 179 +++-- .../services/asset_service/transports/grpc.py | 40 +- .../asset_service/transports/grpc_asyncio.py | 41 +- google/cloud/asset_v1/types/__init__.py | 2 - google/cloud/asset_v1/types/asset_service.py | 204 ++---- google/cloud/asset_v1/types/assets.py | 167 ++--- google/cloud/asset_v1p1beta1/__init__.py | 7 +- .../cloud/asset_v1p1beta1/gapic_metadata.json | 43 ++ .../asset_v1p1beta1/services/__init__.py | 1 - .../services/asset_service/__init__.py | 2 - .../services/asset_service/async_client.py | 34 +- .../services/asset_service/client.py | 63 +- .../services/asset_service/pagers.py | 6 +- .../asset_service/transports/__init__.py | 2 - .../services/asset_service/transports/base.py | 116 +++- .../services/asset_service/transports/grpc.py | 22 +- .../asset_service/transports/grpc_asyncio.py | 23 +- .../cloud/asset_v1p1beta1/types/__init__.py | 2 - .../asset_v1p1beta1/types/asset_service.py | 41 +- google/cloud/asset_v1p1beta1/types/assets.py | 46 +- google/cloud/asset_v1p2beta1/__init__.py | 9 +- .../cloud/asset_v1p2beta1/gapic_metadata.json | 73 ++ .../asset_v1p2beta1/services/__init__.py | 1 - .../services/asset_service/__init__.py | 2 - .../services/asset_service/async_client.py | 43 +- .../services/asset_service/client.py | 76 +-- .../asset_service/transports/__init__.py | 2 - .../services/asset_service/transports/base.py | 132 +++- .../services/asset_service/transports/grpc.py | 30 +- .../asset_service/transports/grpc_asyncio.py | 29 +- .../cloud/asset_v1p2beta1/types/__init__.py | 2 - .../asset_v1p2beta1/types/asset_service.py | 46 +- google/cloud/asset_v1p2beta1/types/assets.py | 49 +- google/cloud/asset_v1p4beta1/__init__.py | 7 +- .../cloud/asset_v1p4beta1/gapic_metadata.json | 43 ++ .../asset_v1p4beta1/services/__init__.py | 1 - .../services/asset_service/__init__.py | 2 - .../services/asset_service/async_client.py | 31 +- .../services/asset_service/client.py | 61 +- .../asset_service/transports/__init__.py | 2 - .../services/asset_service/transports/base.py | 114 +++- .../services/asset_service/transports/grpc.py | 30 +- .../asset_service/transports/grpc_asyncio.py | 30 +- .../cloud/asset_v1p4beta1/types/__init__.py | 2 - .../asset_v1p4beta1/types/asset_service.py | 75 +- google/cloud/asset_v1p4beta1/types/assets.py | 47 +- google/cloud/asset_v1p5beta1/__init__.py | 9 +- .../cloud/asset_v1p5beta1/gapic_metadata.json | 33 + .../asset_v1p5beta1/services/__init__.py | 1 - .../services/asset_service/__init__.py | 2 - .../services/asset_service/async_client.py | 28 +- .../services/asset_service/client.py | 61 +- .../services/asset_service/pagers.py | 4 +- .../asset_service/transports/__init__.py | 2 - .../services/asset_service/transports/base.py | 107 ++- .../services/asset_service/transports/grpc.py | 22 +- .../asset_service/transports/grpc_asyncio.py | 23 +- .../cloud/asset_v1p5beta1/types/__init__.py | 2 - .../asset_v1p5beta1/types/asset_service.py | 28 +- google/cloud/asset_v1p5beta1/types/assets.py | 59 +- owlbot.py | 12 +- scripts/fixup_asset_v1_keywords.py | 27 +- scripts/fixup_asset_v1p1beta1_keywords.py | 9 +- scripts/fixup_asset_v1p2beta1_keywords.py | 15 +- scripts/fixup_asset_v1p4beta1_keywords.py | 9 +- scripts/fixup_asset_v1p5beta1_keywords.py | 7 +- setup.py | 1 + testing/constraints-3.6.txt | 2 + tests/__init__.py | 15 + tests/unit/__init__.py | 15 + tests/unit/gapic/__init__.py | 15 + tests/unit/gapic/asset_v1/__init__.py | 1 - .../unit/gapic/asset_v1/test_asset_service.py | 644 ++++++++++-------- tests/unit/gapic/asset_v1p1beta1/__init__.py | 1 - .../asset_v1p1beta1/test_asset_service.py | 372 +++++++--- tests/unit/gapic/asset_v1p2beta1/__init__.py | 1 - .../asset_v1p2beta1/test_asset_service.py | 465 ++++++++----- tests/unit/gapic/asset_v1p4beta1/__init__.py | 1 - .../asset_v1p4beta1/test_asset_service.py | 331 +++++++-- tests/unit/gapic/asset_v1p5beta1/__init__.py | 1 - .../asset_v1p5beta1/test_asset_service.py | 317 +++++++-- 93 files changed, 2981 insertions(+), 1988 deletions(-) create mode 100644 google/cloud/asset_v1/gapic_metadata.json create mode 100644 google/cloud/asset_v1p1beta1/gapic_metadata.json create mode 100644 google/cloud/asset_v1p2beta1/gapic_metadata.json create mode 100644 google/cloud/asset_v1p4beta1/gapic_metadata.json create mode 100644 google/cloud/asset_v1p5beta1/gapic_metadata.json create mode 100644 tests/__init__.py create mode 100644 tests/unit/__init__.py create mode 100644 tests/unit/gapic/__init__.py diff --git a/docs/asset_v1/asset_service.rst b/docs/asset_v1/asset_service.rst index 46426270..b2f80a4b 100644 --- a/docs/asset_v1/asset_service.rst +++ b/docs/asset_v1/asset_service.rst @@ -5,7 +5,6 @@ AssetService :members: :inherited-members: - .. automodule:: google.cloud.asset_v1.services.asset_service.pagers :members: :inherited-members: diff --git a/docs/asset_v1p1beta1/asset_service.rst b/docs/asset_v1p1beta1/asset_service.rst index f88f0e38..c034bc69 100644 --- a/docs/asset_v1p1beta1/asset_service.rst +++ b/docs/asset_v1p1beta1/asset_service.rst @@ -5,7 +5,6 @@ AssetService :members: :inherited-members: - .. automodule:: google.cloud.asset_v1p1beta1.services.asset_service.pagers :members: :inherited-members: diff --git a/docs/asset_v1p5beta1/asset_service.rst b/docs/asset_v1p5beta1/asset_service.rst index 5286192b..fa5fcb62 100644 --- a/docs/asset_v1p5beta1/asset_service.rst +++ b/docs/asset_v1p5beta1/asset_service.rst @@ -5,7 +5,6 @@ AssetService :members: :inherited-members: - .. automodule:: google.cloud.asset_v1p5beta1.services.asset_service.pagers :members: :inherited-members: diff --git a/google/cloud/asset/__init__.py b/google/cloud/asset/__init__.py index 89ddcdf7..58379fd4 100644 --- a/google/cloud/asset/__init__.py +++ b/google/cloud/asset/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,10 +14,11 @@ # limitations under the License. # +from google.cloud.asset_v1.services.asset_service.client import AssetServiceClient from google.cloud.asset_v1.services.asset_service.async_client import ( AssetServiceAsyncClient, ) -from google.cloud.asset_v1.services.asset_service.client import AssetServiceClient + from google.cloud.asset_v1.types.asset_service import AnalyzeIamPolicyLongrunningRequest from google.cloud.asset_v1.types.asset_service import ( AnalyzeIamPolicyLongrunningResponse, @@ -28,7 +28,6 @@ from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryRequest from google.cloud.asset_v1.types.asset_service import BatchGetAssetsHistoryResponse from google.cloud.asset_v1.types.asset_service import BigQueryDestination -from google.cloud.asset_v1.types.asset_service import ContentType from google.cloud.asset_v1.types.asset_service import CreateFeedRequest from google.cloud.asset_v1.types.asset_service import DeleteFeedRequest from google.cloud.asset_v1.types.asset_service import ExportAssetsRequest @@ -51,6 +50,7 @@ from google.cloud.asset_v1.types.asset_service import SearchAllResourcesRequest from google.cloud.asset_v1.types.asset_service import SearchAllResourcesResponse from google.cloud.asset_v1.types.asset_service import UpdateFeedRequest +from google.cloud.asset_v1.types.asset_service import ContentType from google.cloud.asset_v1.types.assets import Asset from google.cloud.asset_v1.types.assets import IamPolicyAnalysisResult from google.cloud.asset_v1.types.assets import IamPolicyAnalysisState @@ -61,17 +61,15 @@ from google.cloud.asset_v1.types.assets import TimeWindow __all__ = ( + "AssetServiceClient", + "AssetServiceAsyncClient", "AnalyzeIamPolicyLongrunningRequest", "AnalyzeIamPolicyLongrunningResponse", "AnalyzeIamPolicyRequest", "AnalyzeIamPolicyResponse", - "Asset", - "AssetServiceAsyncClient", - "AssetServiceClient", "BatchGetAssetsHistoryRequest", "BatchGetAssetsHistoryResponse", "BigQueryDestination", - "ContentType", "CreateFeedRequest", "DeleteFeedRequest", "ExportAssetsRequest", @@ -83,22 +81,24 @@ "GetFeedRequest", "IamPolicyAnalysisOutputConfig", "IamPolicyAnalysisQuery", - "IamPolicyAnalysisResult", - "IamPolicyAnalysisState", - "IamPolicySearchResult", "ListFeedsRequest", "ListFeedsResponse", "OutputConfig", "OutputResult", "PartitionSpec", "PubsubDestination", - "Resource", - "ResourceSearchResult", "SearchAllIamPoliciesRequest", "SearchAllIamPoliciesResponse", "SearchAllResourcesRequest", "SearchAllResourcesResponse", + "UpdateFeedRequest", + "ContentType", + "Asset", + "IamPolicyAnalysisResult", + "IamPolicyAnalysisState", + "IamPolicySearchResult", + "Resource", + "ResourceSearchResult", "TemporalAsset", "TimeWindow", - "UpdateFeedRequest", ) diff --git a/google/cloud/asset_v1/__init__.py b/google/cloud/asset_v1/__init__.py index 5596fcd7..6c24e39c 100644 --- a/google/cloud/asset_v1/__init__.py +++ b/google/cloud/asset_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + from .types.asset_service import AnalyzeIamPolicyLongrunningRequest from .types.asset_service import AnalyzeIamPolicyLongrunningResponse from .types.asset_service import AnalyzeIamPolicyRequest @@ -23,7 +24,6 @@ from .types.asset_service import BatchGetAssetsHistoryRequest from .types.asset_service import BatchGetAssetsHistoryResponse from .types.asset_service import BigQueryDestination -from .types.asset_service import ContentType from .types.asset_service import CreateFeedRequest from .types.asset_service import DeleteFeedRequest from .types.asset_service import ExportAssetsRequest @@ -46,6 +46,7 @@ from .types.asset_service import SearchAllResourcesRequest from .types.asset_service import SearchAllResourcesResponse from .types.asset_service import UpdateFeedRequest +from .types.asset_service import ContentType from .types.assets import Asset from .types.assets import IamPolicyAnalysisResult from .types.assets import IamPolicyAnalysisState @@ -55,13 +56,14 @@ from .types.assets import TemporalAsset from .types.assets import TimeWindow - __all__ = ( + "AssetServiceAsyncClient", "AnalyzeIamPolicyLongrunningRequest", "AnalyzeIamPolicyLongrunningResponse", "AnalyzeIamPolicyRequest", "AnalyzeIamPolicyResponse", "Asset", + "AssetServiceClient", "BatchGetAssetsHistoryRequest", "BatchGetAssetsHistoryResponse", "BigQueryDestination", @@ -95,5 +97,4 @@ "TemporalAsset", "TimeWindow", "UpdateFeedRequest", - "AssetServiceClient", ) diff --git a/google/cloud/asset_v1/gapic_metadata.json b/google/cloud/asset_v1/gapic_metadata.json new file mode 100644 index 00000000..a80eb281 --- /dev/null +++ b/google/cloud/asset_v1/gapic_metadata.json @@ -0,0 +1,133 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1", + "protoPackage": "google.cloud.asset.v1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "analyze_iam_policy_longrunning" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "AnalyzeIamPolicyLongrunning": { + "methods": [ + "analyze_iam_policy_longrunning" + ] + }, + "BatchGetAssetsHistory": { + "methods": [ + "batch_get_assets_history" + ] + }, + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "ExportAssets": { + "methods": [ + "export_assets" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/asset_v1/services/__init__.py b/google/cloud/asset_v1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/asset_v1/services/__init__.py +++ b/google/cloud/asset_v1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/asset_v1/services/asset_service/__init__.py b/google/cloud/asset_v1/services/asset_service/__init__.py index ec3c27d2..cb995a56 100644 --- a/google/cloud/asset_v1/services/asset_service/__init__.py +++ b/google/cloud/asset_v1/services/asset_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AssetServiceClient from .async_client import AssetServiceAsyncClient diff --git a/google/cloud/asset_v1/services/asset_service/async_client.py b/google/cloud/asset_v1/services/asset_service/async_client.py index 56d7a1c2..87bc8bc1 100644 --- a/google/cloud/asset_v1/services/asset_service/async_client.py +++ b/google/cloud/asset_v1/services/asset_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,10 +20,10 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.api_core import operation # type: ignore @@ -33,8 +31,7 @@ from google.cloud.asset_v1.services.asset_service import pagers from google.cloud.asset_v1.types import asset_service from google.cloud.asset_v1.types import assets -from google.type import expr_pb2 as expr # type: ignore - +from google.type import expr_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .client import AssetServiceClient @@ -52,27 +49,22 @@ class AssetServiceAsyncClient: feed_path = staticmethod(AssetServiceClient.feed_path) parse_feed_path = staticmethod(AssetServiceClient.parse_feed_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 @@ -80,7 +72,8 @@ class AssetServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -95,7 +88,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -112,7 +105,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AssetServiceTransport: The transport used by the client instance. @@ -126,12 +119,12 @@ def transport(self) -> AssetServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -163,7 +156,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AssetServiceClient( credentials=credentials, transport=transport, @@ -196,7 +188,6 @@ async def export_assets( Args: request (:class:`google.cloud.asset_v1.types.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. @@ -215,7 +206,6 @@ async def export_assets( """ # Create or coerce a protobuf request object. - request = asset_service.ExportAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -265,7 +255,6 @@ async def batch_get_assets_history( Args: request (:class:`google.cloud.asset_v1.types.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. @@ -277,7 +266,6 @@ async def batch_get_assets_history( 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, @@ -289,7 +277,8 @@ async def batch_get_assets_history( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -339,7 +328,6 @@ async def create_feed( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -371,7 +359,6 @@ async def create_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -418,7 +405,6 @@ async def get_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -450,7 +436,6 @@ async def get_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -463,7 +448,8 @@ async def get_feed( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -509,7 +495,6 @@ async def list_feeds( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -534,7 +519,6 @@ async def list_feeds( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -547,7 +531,8 @@ async def list_feeds( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -591,7 +576,6 @@ async def update_feed( This corresponds to the ``feed`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -623,7 +607,6 @@ async def update_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if feed is not None: request.feed = feed @@ -672,7 +655,6 @@ async def delete_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -693,7 +675,6 @@ async def delete_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -706,7 +687,8 @@ async def delete_feed( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -815,7 +797,6 @@ async def search_all_resources( This corresponds to the ``asset_types`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -844,12 +825,10 @@ async def search_all_resources( # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: request.query = query - if asset_types: request.asset_types.extend(asset_types) @@ -862,7 +841,8 @@ async def search_all_resources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -961,7 +941,6 @@ async def search_all_iam_policies( This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -990,7 +969,6 @@ async def search_all_iam_policies( # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: @@ -1005,7 +983,8 @@ async def search_all_iam_policies( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -1046,7 +1025,6 @@ async def analyze_iam_policy( request (:class:`google.cloud.asset_v1.types.AnalyzeIamPolicyRequest`): The request object. A request message for [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1060,7 +1038,6 @@ async def analyze_iam_policy( """ # Create or coerce a protobuf request object. - request = asset_service.AnalyzeIamPolicyRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -1071,7 +1048,9 @@ async def analyze_iam_policy( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=300.0, ), default_timeout=300.0, @@ -1117,7 +1096,6 @@ async def analyze_iam_policy_longrunning( request (:class:`google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest`): The request object. A request message for [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1135,7 +1113,6 @@ async def analyze_iam_policy_longrunning( """ # Create or coerce a protobuf request object. - request = asset_service.AnalyzeIamPolicyLongrunningRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/asset_v1/services/asset_service/client.py b/google/cloud/asset_v1/services/asset_service/client.py index f65e8ba8..40b3fe71 100644 --- a/google/cloud/asset_v1/services/asset_service/client.py +++ b/google/cloud/asset_v1/services/asset_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -37,8 +35,7 @@ from google.cloud.asset_v1.services.asset_service import pagers from google.cloud.asset_v1.types import asset_service from google.cloud.asset_v1.types import assets -from google.type import expr_pb2 as expr # type: ignore - +from google.type import expr_pb2 # type: ignore from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -57,7 +54,7 @@ class AssetServiceClientMeta(type): _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -80,7 +77,8 @@ class AssetServiceClient(metaclass=AssetServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -114,7 +112,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -131,7 +130,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -150,32 +149,33 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AssetServiceTransport: The transport used by the client instance. + AssetServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def asset_path() -> str: - """Return a fully-qualified asset string.""" + """Returns a fully-qualified asset string.""" return "*".format() @staticmethod def feed_path(project: str, feed: str,) -> str: - """Return a fully-qualified feed string.""" + """Returns a fully-qualified feed string.""" return "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) @staticmethod def parse_feed_path(path: str) -> Dict[str, str]: - """Parse a feed path into its component segments.""" + """Parses a feed path into its component segments.""" m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -188,7 +188,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -199,7 +199,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -210,7 +210,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -221,7 +221,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -235,12 +235,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -295,9 +295,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -309,12 +310,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -329,8 +332,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -370,7 +373,6 @@ def export_assets( Args: request (google.cloud.asset_v1.types.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. @@ -389,7 +391,6 @@ def export_assets( """ # 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 @@ -440,7 +441,6 @@ def batch_get_assets_history( Args: request (google.cloud.asset_v1.types.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. @@ -452,7 +452,6 @@ def batch_get_assets_history( 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 @@ -506,7 +505,6 @@ def create_feed( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -540,10 +538,8 @@ def create_feed( # there are no flattened fields. if not isinstance(request, asset_service.CreateFeedRequest): request = asset_service.CreateFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -586,7 +582,6 @@ def get_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -620,10 +615,8 @@ def get_feed( # there are no flattened fields. if not isinstance(request, asset_service.GetFeedRequest): request = asset_service.GetFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -669,7 +662,6 @@ def list_feeds( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -696,10 +688,8 @@ def list_feeds( # there are no flattened fields. if not isinstance(request, asset_service.ListFeedsRequest): request = asset_service.ListFeedsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -743,7 +733,6 @@ def update_feed( This corresponds to the ``feed`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -777,10 +766,8 @@ def update_feed( # there are no flattened fields. if not isinstance(request, asset_service.UpdateFeedRequest): request = asset_service.UpdateFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if feed is not None: request.feed = feed @@ -825,7 +812,6 @@ def delete_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -848,10 +834,8 @@ def delete_feed( # there are no flattened fields. if not isinstance(request, asset_service.DeleteFeedRequest): request = asset_service.DeleteFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -960,7 +944,6 @@ def search_all_resources( This corresponds to the ``asset_types`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -991,10 +974,8 @@ def search_all_resources( # there are no flattened fields. if not isinstance(request, asset_service.SearchAllResourcesRequest): request = asset_service.SearchAllResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: @@ -1097,7 +1078,6 @@ def search_all_iam_policies( This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1128,10 +1108,8 @@ def search_all_iam_policies( # there are no flattened fields. if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): request = asset_service.SearchAllIamPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: @@ -1174,7 +1152,6 @@ def analyze_iam_policy( request (google.cloud.asset_v1.types.AnalyzeIamPolicyRequest): The request object. A request message for [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1188,7 +1165,6 @@ def analyze_iam_policy( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a asset_service.AnalyzeIamPolicyRequest. # There's no risk of modifying the input as we've already verified @@ -1239,7 +1215,6 @@ def analyze_iam_policy_longrunning( request (google.cloud.asset_v1.types.AnalyzeIamPolicyLongrunningRequest): The request object. A request message for [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1257,7 +1232,6 @@ def analyze_iam_policy_longrunning( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a asset_service.AnalyzeIamPolicyLongrunningRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/asset_v1/services/asset_service/pagers.py b/google/cloud/asset_v1/services/asset_service/pagers.py index 1c251731..8db1ae2e 100644 --- a/google/cloud/asset_v1/services/asset_service/pagers.py +++ b/google/cloud/asset_v1/services/asset_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -246,7 +244,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 c077c192..9158fc25 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1/services/asset_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/asset_v1/services/asset_service/transports/base.py b/google/cloud/asset_v1/services/asset_service/transports/base.py index 22201371..40fdf882 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1/services/asset_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,22 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -38,27 +37,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudasset.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -67,7 +80,7 @@ def __init__( 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. + scopes (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): @@ -81,29 +94,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -117,7 +177,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -134,7 +195,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -148,7 +210,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -165,7 +228,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -179,7 +243,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -193,7 +258,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -206,7 +272,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=300.0, ), default_timeout=300.0, @@ -227,20 +295,20 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def export_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.ExportAssetsRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() @property def batch_get_assets_history( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.BatchGetAssetsHistoryRequest], - typing.Union[ + Union[ asset_service.BatchGetAssetsHistoryResponse, - typing.Awaitable[asset_service.BatchGetAssetsHistoryResponse], + Awaitable[asset_service.BatchGetAssetsHistoryResponse], ], ]: raise NotImplementedError() @@ -248,29 +316,28 @@ def batch_get_assets_history( @property def create_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.CreateFeedRequest], - typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], ]: raise NotImplementedError() @property def get_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.GetFeedRequest], - typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], ]: raise NotImplementedError() @property def list_feeds( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.ListFeedsRequest], - typing.Union[ - asset_service.ListFeedsResponse, - typing.Awaitable[asset_service.ListFeedsResponse], + Union[ + asset_service.ListFeedsResponse, Awaitable[asset_service.ListFeedsResponse] ], ]: raise NotImplementedError() @@ -278,29 +345,29 @@ def list_feeds( @property def update_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.UpdateFeedRequest], - typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], ]: raise NotImplementedError() @property def delete_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.DeleteFeedRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() @property def search_all_resources( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.SearchAllResourcesRequest], - typing.Union[ + Union[ asset_service.SearchAllResourcesResponse, - typing.Awaitable[asset_service.SearchAllResourcesResponse], + Awaitable[asset_service.SearchAllResourcesResponse], ], ]: raise NotImplementedError() @@ -308,11 +375,11 @@ def search_all_resources( @property def search_all_iam_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.SearchAllIamPoliciesRequest], - typing.Union[ + Union[ asset_service.SearchAllIamPoliciesResponse, - typing.Awaitable[asset_service.SearchAllIamPoliciesResponse], + Awaitable[asset_service.SearchAllIamPoliciesResponse], ], ]: raise NotImplementedError() @@ -320,11 +387,11 @@ def search_all_iam_policies( @property def analyze_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.AnalyzeIamPolicyRequest], - typing.Union[ + Union[ asset_service.AnalyzeIamPolicyResponse, - typing.Awaitable[asset_service.AnalyzeIamPolicyResponse], + Awaitable[asset_service.AnalyzeIamPolicyResponse], ], ]: raise NotImplementedError() @@ -332,9 +399,9 @@ def analyze_iam_policy( @property def analyze_iam_policy_longrunning( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.AnalyzeIamPolicyLongrunningRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() 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 daf07dfa..adf72412 100644 --- a/google/cloud/asset_v1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1/services/asset_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -67,7 +64,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -178,7 +176,7 @@ def __init__( def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -209,13 +207,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -242,7 +242,7 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def export_assets( self, - ) -> Callable[[asset_service.ExportAssetsRequest], operations.Operation]: + ) -> Callable[[asset_service.ExportAssetsRequest], operations_pb2.Operation]: r"""Return a callable for the export assets method over gRPC. Exports assets with time and resource types to a given Cloud @@ -273,7 +273,7 @@ def export_assets( self._stubs["export_assets"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1.AssetService/ExportAssets", request_serializer=asset_service.ExportAssetsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_assets"] @@ -418,7 +418,9 @@ def update_feed( return self._stubs["update_feed"] @property - def delete_feed(self) -> Callable[[asset_service.DeleteFeedRequest], empty.Empty]: + def delete_feed( + self, + ) -> Callable[[asset_service.DeleteFeedRequest], empty_pb2.Empty]: r"""Return a callable for the delete feed method over gRPC. Deletes an asset feed. @@ -437,7 +439,7 @@ def delete_feed(self) -> Callable[[asset_service.DeleteFeedRequest], empty.Empty self._stubs["delete_feed"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1.AssetService/DeleteFeed", request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_feed"] @@ -538,7 +540,7 @@ def analyze_iam_policy( def analyze_iam_policy_longrunning( self, ) -> Callable[ - [asset_service.AnalyzeIamPolicyLongrunningRequest], operations.Operation + [asset_service.AnalyzeIamPolicyLongrunningRequest], operations_pb2.Operation ]: r"""Return a callable for the analyze iam policy longrunning method over gRPC. @@ -571,7 +573,7 @@ def analyze_iam_policy_longrunning( ] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning", request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["analyze_iam_policy_longrunning"] 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 2bb35c01..fcfa7d90 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,24 +13,22 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.asset_v1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.longrunning import operations_pb2 # type: ignore +from google.protobuf import empty_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AssetServiceGrpcTransport @@ -56,7 +53,7 @@ class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -83,13 +80,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -97,7 +96,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -111,7 +110,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -170,7 +170,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -248,7 +247,9 @@ def operations_client(self) -> operations_v1.OperationsAsyncClient: @property def export_assets( self, - ) -> Callable[[asset_service.ExportAssetsRequest], Awaitable[operations.Operation]]: + ) -> Callable[ + [asset_service.ExportAssetsRequest], Awaitable[operations_pb2.Operation] + ]: r"""Return a callable for the export assets method over gRPC. Exports assets with time and resource types to a given Cloud @@ -279,7 +280,7 @@ def export_assets( self._stubs["export_assets"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1.AssetService/ExportAssets", request_serializer=asset_service.ExportAssetsRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_assets"] @@ -430,7 +431,7 @@ def update_feed( @property def delete_feed( self, - ) -> Callable[[asset_service.DeleteFeedRequest], Awaitable[empty.Empty]]: + ) -> Callable[[asset_service.DeleteFeedRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete feed method over gRPC. Deletes an asset feed. @@ -449,7 +450,7 @@ def delete_feed( self._stubs["delete_feed"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1.AssetService/DeleteFeed", request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_feed"] @@ -552,7 +553,7 @@ def analyze_iam_policy_longrunning( self, ) -> Callable[ [asset_service.AnalyzeIamPolicyLongrunningRequest], - Awaitable[operations.Operation], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the analyze iam policy longrunning method over gRPC. @@ -585,7 +586,7 @@ def analyze_iam_policy_longrunning( ] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1.AssetService/AnalyzeIamPolicyLongrunning", request_serializer=asset_service.AnalyzeIamPolicyLongrunningRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["analyze_iam_policy_longrunning"] diff --git a/google/cloud/asset_v1/types/__init__.py b/google/cloud/asset_v1/types/__init__.py index 1143f78b..b75ed5e3 100644 --- a/google/cloud/asset_v1/types/__init__.py +++ b/google/cloud/asset_v1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset_service import ( AnalyzeIamPolicyLongrunningRequest, AnalyzeIamPolicyLongrunningResponse, diff --git a/google/cloud/asset_v1/types/asset_service.py b/google/cloud/asset_v1/types/asset_service.py index 02fca9fe..26ec00c0 100644 --- a/google/cloud/asset_v1/types/asset_service.py +++ b/google/cloud/asset_v1/types/asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,15 +13,13 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.asset_v1.types import assets as gca_assets -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore __protobuf__ = proto.module( @@ -74,7 +71,6 @@ class ContentType(proto.Enum): class ExportAssetsRequest(proto.Message): r"""Export asset request. - Attributes: parent (str): Required. The relative name of the root @@ -123,14 +119,10 @@ class ExportAssetsRequest(proto.Message): where the results will be output to. """ - 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) - + parent = proto.Field(proto.STRING, number=1,) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.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",) @@ -156,16 +148,13 @@ class ExportAssetsResponse(proto.Message): it exceeds a single Google Cloud Storage object limit. """ - read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - + read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) output_config = proto.Field(proto.MESSAGE, number=2, message="OutputConfig",) - output_result = proto.Field(proto.MESSAGE, number=3, message="OutputResult",) class BatchGetAssetsHistoryRequest(proto.Message): r"""Batch get assets history request. - Attributes: parent (str): Required. The relative name of the root @@ -195,12 +184,9 @@ class BatchGetAssetsHistoryRequest(proto.Message): whose time window overlap with read_time_window. """ - parent = proto.Field(proto.STRING, number=1) - - asset_names = proto.RepeatedField(proto.STRING, number=2) - + 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, ) @@ -208,7 +194,6 @@ class BatchGetAssetsHistoryRequest(proto.Message): class BatchGetAssetsHistoryResponse(proto.Message): r"""Batch get assets history response. - Attributes: assets (Sequence[google.cloud.asset_v1.types.TemporalAsset]): A list of assets with valid time windows. @@ -221,7 +206,6 @@ class BatchGetAssetsHistoryResponse(proto.Message): class CreateFeedRequest(proto.Message): r"""Create asset feed request. - Attributes: parent (str): Required. The name of the @@ -244,16 +228,13 @@ class CreateFeedRequest(proto.Message): organizations/organization_number/feeds/feed_id """ - parent = proto.Field(proto.STRING, number=1) - - feed_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + feed_id = proto.Field(proto.STRING, number=2,) feed = proto.Field(proto.MESSAGE, number=3, message="Feed",) class GetFeedRequest(proto.Message): r"""Get asset feed request. - Attributes: name (str): Required. The name of the Feed and it must be in the format @@ -262,12 +243,11 @@ class GetFeedRequest(proto.Message): organizations/organization_number/feeds/feed_id """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListFeedsRequest(proto.Message): r"""List asset feeds request. - Attributes: parent (str): Required. The parent @@ -278,12 +258,11 @@ class ListFeedsRequest(proto.Message): "projects/my-project-id"). """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class ListFeedsResponse(proto.Message): r""" - Attributes: feeds (Sequence[google.cloud.asset_v1.types.Feed]): A list of feeds. @@ -294,7 +273,6 @@ class ListFeedsResponse(proto.Message): class UpdateFeedRequest(proto.Message): r"""Update asset feed request. - Attributes: feed (google.cloud.asset_v1.types.Feed): Required. The new values of feed details. It must match an @@ -309,13 +287,13 @@ class UpdateFeedRequest(proto.Message): """ feed = proto.Field(proto.MESSAGE, number=1, message="Feed",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteFeedRequest(proto.Message): r""" - Attributes: name (str): Required. The name of the feed and it must be in the format @@ -324,12 +302,11 @@ class DeleteFeedRequest(proto.Message): organizations/organization_number/feeds/feed_id """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class OutputConfig(proto.Message): r"""Output configuration for export assets destination. - Attributes: gcs_destination (google.cloud.asset_v1.types.GcsDestination): Destination on Cloud Storage. @@ -342,7 +319,6 @@ class OutputConfig(proto.Message): gcs_destination = proto.Field( proto.MESSAGE, number=1, oneof="destination", message="GcsDestination", ) - bigquery_destination = proto.Field( proto.MESSAGE, number=2, oneof="destination", message="BigQueryDestination", ) @@ -350,7 +326,6 @@ class OutputConfig(proto.Message): class OutputResult(proto.Message): r"""Output result of export assets. - Attributes: gcs_result (google.cloud.asset_v1.types.GcsOutputResult): Export result on Cloud Storage. @@ -363,19 +338,17 @@ class OutputResult(proto.Message): class GcsOutputResult(proto.Message): r"""A Cloud Storage output result. - Attributes: uris (Sequence[str]): List of uris of the Cloud Storage objects. Example: "gs://bucket_name/object_name". """ - uris = proto.RepeatedField(proto.STRING, number=1) + uris = proto.RepeatedField(proto.STRING, number=1,) 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 @@ -395,14 +368,12 @@ class GcsDestination(proto.Message): "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") + uri = proto.Field(proto.STRING, number=1, oneof="object_uri",) + uri_prefix = proto.Field(proto.STRING, number=2, oneof="object_uri",) class BigQueryDestination(proto.Message): r"""A BigQuery destination for exporting assets to. - Attributes: dataset (str): Required. The BigQuery dataset in format @@ -478,15 +449,11 @@ class BigQueryDestination(proto.Message): a table. """ - dataset = proto.Field(proto.STRING, number=1) - - table = proto.Field(proto.STRING, number=2) - - force = proto.Field(proto.BOOL, number=3) - + dataset = proto.Field(proto.STRING, number=1,) + table = proto.Field(proto.STRING, number=2,) + force = proto.Field(proto.BOOL, number=3,) partition_spec = proto.Field(proto.MESSAGE, number=4, message="PartitionSpec",) - - separate_tables_per_asset_type = proto.Field(proto.BOOL, number=5) + separate_tables_per_asset_type = proto.Field(proto.BOOL, number=5,) class PartitionSpec(proto.Message): @@ -515,19 +482,17 @@ class PartitionKey(proto.Enum): class PubsubDestination(proto.Message): r"""A Pub/Sub destination. - Attributes: topic (str): The name of the Pub/Sub topic to publish to. Example: ``projects/PROJECT_ID/topics/TOPIC_ID``. """ - topic = proto.Field(proto.STRING, number=1) + topic = proto.Field(proto.STRING, number=1,) class FeedOutputConfig(proto.Message): r"""Output configuration for asset feed destination. - Attributes: pubsub_destination (google.cloud.asset_v1.types.PubsubDestination): Destination on Pub/Sub. @@ -599,24 +564,18 @@ class Feed(proto.Message): for detailed instructions. """ - name = proto.Field(proto.STRING, number=1) - - asset_names = proto.RepeatedField(proto.STRING, number=2) - - asset_types = proto.RepeatedField(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + asset_names = proto.RepeatedField(proto.STRING, number=2,) + asset_types = proto.RepeatedField(proto.STRING, number=3,) content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) - feed_output_config = proto.Field( proto.MESSAGE, number=5, message="FeedOutputConfig", ) - - condition = proto.Field(proto.MESSAGE, number=6, message=expr.Expr,) + condition = proto.Field(proto.MESSAGE, number=6, message=expr_pb2.Expr,) class SearchAllResourcesRequest(proto.Message): r"""Search all resources request. - Attributes: scope (str): Required. A scope can be a project, a folder, or an @@ -700,22 +659,16 @@ class SearchAllResourcesRequest(proto.Message): ``additionalAttributes``) are not supported. """ - scope = proto.Field(proto.STRING, number=1) - - query = proto.Field(proto.STRING, number=2) - - asset_types = proto.RepeatedField(proto.STRING, number=3) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) - - order_by = proto.Field(proto.STRING, number=6) + scope = proto.Field(proto.STRING, number=1,) + query = proto.Field(proto.STRING, number=2,) + asset_types = proto.RepeatedField(proto.STRING, number=3,) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) + order_by = proto.Field(proto.STRING, number=6,) class SearchAllResourcesResponse(proto.Message): r"""Search all resources response. - Attributes: results (Sequence[google.cloud.asset_v1.types.ResourceSearchResult]): A list of Resources that match the search @@ -735,13 +688,11 @@ def raw_page(self): results = proto.RepeatedField( proto.MESSAGE, number=1, message=gca_assets.ResourceSearchResult, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class SearchAllIamPoliciesRequest(proto.Message): r"""Search all IAM policies request. - Attributes: scope (str): Required. A scope can be a project, a folder, or an @@ -801,18 +752,14 @@ class SearchAllIamPoliciesRequest(proto.Message): identical to those in the previous call. """ - scope = proto.Field(proto.STRING, number=1) - - query = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + scope = proto.Field(proto.STRING, number=1,) + query = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class SearchAllIamPoliciesResponse(proto.Message): r"""Search all IAM policies response. - Attributes: results (Sequence[google.cloud.asset_v1.types.IamPolicySearchResult]): A list of IamPolicy that match the search @@ -832,13 +779,11 @@ def raw_page(self): results = proto.RepeatedField( proto.MESSAGE, number=1, message=gca_assets.IamPolicySearchResult, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class IamPolicyAnalysisQuery(proto.Message): r"""IAM policy analysis query message. - Attributes: scope (str): Required. The relative name of the root asset. Only @@ -880,7 +825,7 @@ class ResourceSelector(proto.Message): types `__. """ - full_resource_name = proto.Field(proto.STRING, number=1) + full_resource_name = proto.Field(proto.STRING, number=1,) class IdentitySelector(proto.Message): r"""Specifies an identity for which to determine resource access, @@ -902,7 +847,7 @@ class IdentitySelector(proto.Message): supported. You must give a specific identity. """ - identity = proto.Field(proto.STRING, number=1) + identity = proto.Field(proto.STRING, number=1,) class AccessSelector(proto.Message): r"""Specifies roles and/or permissions to analyze, to determine @@ -919,13 +864,11 @@ class AccessSelector(proto.Message): result. """ - roles = proto.RepeatedField(proto.STRING, number=1) - - permissions = proto.RepeatedField(proto.STRING, number=2) + roles = proto.RepeatedField(proto.STRING, number=1,) + permissions = proto.RepeatedField(proto.STRING, number=2,) class Options(proto.Message): r"""Contains query options. - Attributes: expand_groups (bool): Optional. If true, the identities section of the result will @@ -1015,26 +958,17 @@ class Options(proto.Message): Default is false. """ - expand_groups = proto.Field(proto.BOOL, number=1) - - expand_roles = proto.Field(proto.BOOL, number=2) - - expand_resources = proto.Field(proto.BOOL, number=3) - - output_resource_edges = proto.Field(proto.BOOL, number=4) - - output_group_edges = proto.Field(proto.BOOL, number=5) - - analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6) - - scope = proto.Field(proto.STRING, number=1) + expand_groups = proto.Field(proto.BOOL, number=1,) + expand_roles = proto.Field(proto.BOOL, number=2,) + expand_resources = proto.Field(proto.BOOL, number=3,) + output_resource_edges = proto.Field(proto.BOOL, number=4,) + output_group_edges = proto.Field(proto.BOOL, number=5,) + analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6,) + scope = proto.Field(proto.STRING, number=1,) resource_selector = proto.Field(proto.MESSAGE, number=2, message=ResourceSelector,) - identity_selector = proto.Field(proto.MESSAGE, number=3, message=IdentitySelector,) - access_selector = proto.Field(proto.MESSAGE, number=4, message=AccessSelector,) - options = proto.Field(proto.MESSAGE, number=5, message=Options,) @@ -1063,8 +997,9 @@ class AnalyzeIamPolicyRequest(proto.Message): analysis_query = proto.Field( proto.MESSAGE, number=1, message="IamPolicyAnalysisQuery", ) - - execution_timeout = proto.Field(proto.MESSAGE, number=2, message=duration.Duration,) + execution_timeout = proto.Field( + proto.MESSAGE, number=2, message=duration_pb2.Duration, + ) class AnalyzeIamPolicyResponse(proto.Message): @@ -1089,7 +1024,6 @@ class AnalyzeIamPolicyResponse(proto.Message): class IamPolicyAnalysis(proto.Message): r"""An analysis message to group the query and results. - Attributes: analysis_query (google.cloud.asset_v1.types.IamPolicyAnalysisQuery): The analysis query. @@ -1110,24 +1044,19 @@ class IamPolicyAnalysis(proto.Message): analysis_query = proto.Field( proto.MESSAGE, number=1, message="IamPolicyAnalysisQuery", ) - analysis_results = proto.RepeatedField( proto.MESSAGE, number=2, message=gca_assets.IamPolicyAnalysisResult, ) - - fully_explored = proto.Field(proto.BOOL, number=3) - + fully_explored = proto.Field(proto.BOOL, number=3,) non_critical_errors = proto.RepeatedField( proto.MESSAGE, number=5, message=gca_assets.IamPolicyAnalysisState, ) main_analysis = proto.Field(proto.MESSAGE, number=1, message=IamPolicyAnalysis,) - service_account_impersonation_analysis = proto.RepeatedField( proto.MESSAGE, number=2, message=IamPolicyAnalysis, ) - - fully_explored = proto.Field(proto.BOOL, number=3) + fully_explored = proto.Field(proto.BOOL, number=3,) class IamPolicyAnalysisOutputConfig(proto.Message): @@ -1143,7 +1072,6 @@ class IamPolicyAnalysisOutputConfig(proto.Message): class GcsDestination(proto.Message): r"""A Cloud Storage location. - Attributes: uri (str): Required. The uri of the Cloud Storage object. It's the same @@ -1154,11 +1082,10 @@ class GcsDestination(proto.Message): for examples. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) class BigQueryDestination(proto.Message): r"""A BigQuery destination. - Attributes: dataset (str): Required. The BigQuery dataset in format @@ -1210,22 +1137,18 @@ class PartitionKey(proto.Enum): PARTITION_KEY_UNSPECIFIED = 0 REQUEST_TIME = 1 - dataset = proto.Field(proto.STRING, number=1) - - table_prefix = proto.Field(proto.STRING, number=2) - + dataset = proto.Field(proto.STRING, number=1,) + table_prefix = proto.Field(proto.STRING, number=2,) partition_key = proto.Field( proto.ENUM, number=3, enum="IamPolicyAnalysisOutputConfig.BigQueryDestination.PartitionKey", ) - - write_disposition = proto.Field(proto.STRING, number=4) + write_disposition = proto.Field(proto.STRING, number=4,) gcs_destination = proto.Field( proto.MESSAGE, number=1, oneof="destination", message=GcsDestination, ) - bigquery_destination = proto.Field( proto.MESSAGE, number=2, oneof="destination", message=BigQueryDestination, ) @@ -1246,7 +1169,6 @@ class AnalyzeIamPolicyLongrunningRequest(proto.Message): analysis_query = proto.Field( proto.MESSAGE, number=1, message="IamPolicyAnalysisQuery", ) - output_config = proto.Field( proto.MESSAGE, number=2, message="IamPolicyAnalysisOutputConfig", ) @@ -1255,7 +1177,7 @@ class AnalyzeIamPolicyLongrunningRequest(proto.Message): class AnalyzeIamPolicyLongrunningResponse(proto.Message): r"""A response message for [AssetService.AnalyzeIamPolicyLongrunning][google.cloud.asset.v1.AssetService.AnalyzeIamPolicyLongrunning]. - """ + """ __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1/types/assets.py b/google/cloud/asset_v1/types/assets.py index 43eb2482..f4086a8e 100644 --- a/google/cloud/asset_v1/types/assets.py +++ b/google/cloud/asset_v1/types/assets.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,19 +13,17 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 as orgpolicy # type: ignore +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore from google.cloud.osconfig_v1 import Inventory # type: ignore -from google.iam.v1 import policy_pb2 as gi_policy # type: ignore -from google.identity.accesscontextmanager.v1 import access_level_pb2 as gia_access_level # type: ignore -from google.identity.accesscontextmanager.v1 import access_policy_pb2 as gia_access_policy # type: ignore -from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 as gia_service_perimeter # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.rpc import code_pb2 as gr_code # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_level_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore __protobuf__ = proto.module( @@ -74,19 +71,14 @@ class PriorAssetState(proto.Enum): DELETED = 4 window = proto.Field(proto.MESSAGE, number=1, message="TimeWindow",) - - deleted = proto.Field(proto.BOOL, number=2) - + deleted = proto.Field(proto.BOOL, number=2,) asset = proto.Field(proto.MESSAGE, number=3, message="Asset",) - prior_asset_state = proto.Field(proto.ENUM, number=4, enum=PriorAssetState,) - prior_asset = proto.Field(proto.MESSAGE, number=5, message="Asset",) class TimeWindow(proto.Message): r"""A time window specified by its ``start_time`` and ``end_time``. - Attributes: start_time (google.protobuf.timestamp_pb2.Timestamp): Start time of the time window (exclusive). @@ -96,9 +88,8 @@ class TimeWindow(proto.Message): instead. """ - start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class Asset(proto.Message): @@ -157,7 +148,7 @@ class Asset(proto.Message): service_perimeter (google.identity.accesscontextmanager.v1.service_perimeter_pb2.ServicePerimeter): Please also refer to the `service perimeter user guide `__. - os_inventory (google.cloud.osconfig.v1.inventory_pb2.Inventory): + os_inventory (ggoogle.cloud.osconfig_v1.Inventory): A representation of runtime OS Inventory information. See `this topic `__ @@ -175,47 +166,40 @@ class Asset(proto.Message): ``["projects/123456789", "folders/5432", "organizations/1234"]`` """ - update_time = proto.Field(proto.MESSAGE, number=11, message=timestamp.Timestamp,) - - name = proto.Field(proto.STRING, number=1) - - asset_type = proto.Field(proto.STRING, number=2) - + update_time = proto.Field( + proto.MESSAGE, number=11, message=timestamp_pb2.Timestamp, + ) + 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=gi_policy.Policy,) - - org_policy = proto.RepeatedField(proto.MESSAGE, number=6, message=orgpolicy.Policy,) - + iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy_pb2.Policy,) + org_policy = proto.RepeatedField( + proto.MESSAGE, number=6, message=orgpolicy_pb2.Policy, + ) access_policy = proto.Field( proto.MESSAGE, number=7, oneof="access_context_policy", - message=gia_access_policy.AccessPolicy, + message=access_policy_pb2.AccessPolicy, ) - access_level = proto.Field( proto.MESSAGE, number=8, oneof="access_context_policy", - message=gia_access_level.AccessLevel, + message=access_level_pb2.AccessLevel, ) - service_perimeter = proto.Field( proto.MESSAGE, number=9, oneof="access_context_policy", - message=gia_service_perimeter.ServicePerimeter, + message=service_perimeter_pb2.ServicePerimeter, ) - os_inventory = proto.Field(proto.MESSAGE, number=12, message=Inventory,) - - ancestors = proto.RepeatedField(proto.STRING, number=10) + ancestors = proto.RepeatedField(proto.STRING, number=10,) class Resource(proto.Message): r"""A representation of a Google Cloud resource. - Attributes: version (str): The API version. Example: ``v1`` @@ -262,19 +246,13 @@ class Resource(proto.Message): https://cloud.google.com/about/locations/. """ - 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,) - - location = proto.Field(proto.STRING, number=8) + 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_pb2.Struct,) + location = proto.Field(proto.STRING, number=8,) class ResourceSearchResult(proto.Message): @@ -385,23 +363,17 @@ class ResourceSearchResult(proto.Message): can issue a query ``foobar``. """ - name = proto.Field(proto.STRING, number=1) - - asset_type = proto.Field(proto.STRING, number=2) - - project = proto.Field(proto.STRING, number=3) - - display_name = proto.Field(proto.STRING, number=4) - - description = proto.Field(proto.STRING, number=5) - - location = proto.Field(proto.STRING, number=6) - - labels = proto.MapField(proto.STRING, proto.STRING, number=7) - - network_tags = proto.RepeatedField(proto.STRING, number=8) - - additional_attributes = proto.Field(proto.MESSAGE, number=9, message=struct.Struct,) + name = proto.Field(proto.STRING, number=1,) + asset_type = proto.Field(proto.STRING, number=2,) + project = proto.Field(proto.STRING, number=3,) + display_name = proto.Field(proto.STRING, number=4,) + description = proto.Field(proto.STRING, number=5,) + location = proto.Field(proto.STRING, number=6,) + labels = proto.MapField(proto.STRING, proto.STRING, number=7,) + network_tags = proto.RepeatedField(proto.STRING, number=8,) + additional_attributes = proto.Field( + proto.MESSAGE, number=9, message=struct_pb2.Struct, + ) class IamPolicySearchResult(proto.Message): @@ -459,7 +431,6 @@ class IamPolicySearchResult(proto.Message): class Explanation(proto.Message): r"""Explanation about the IAM policy search result. - Attributes: matched_permissions (Sequence[google.cloud.asset_v1.types.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): The map from roles to their included permissions that match @@ -476,14 +447,13 @@ class Explanation(proto.Message): class Permissions(proto.Message): r"""IAM permissions - Attributes: permissions (Sequence[str]): A list of permissions. A sample permission string: ``compute.disk.get``. """ - permissions = proto.RepeatedField(proto.STRING, number=1) + permissions = proto.RepeatedField(proto.STRING, number=1,) matched_permissions = proto.MapField( proto.STRING, @@ -492,12 +462,9 @@ class Permissions(proto.Message): message="IamPolicySearchResult.Explanation.Permissions", ) - resource = proto.Field(proto.STRING, number=1) - - project = proto.Field(proto.STRING, number=2) - - policy = proto.Field(proto.MESSAGE, number=3, message=gi_policy.Policy,) - + resource = proto.Field(proto.STRING, number=1,) + project = proto.Field(proto.STRING, number=2,) + policy = proto.Field(proto.MESSAGE, number=3, message=policy_pb2.Policy,) explanation = proto.Field(proto.MESSAGE, number=4, message=Explanation,) @@ -521,9 +488,8 @@ class IamPolicyAnalysisState(proto.Message): of failure. """ - code = proto.Field(proto.ENUM, number=1, enum=gr_code.Code,) - - cause = proto.Field(proto.STRING, number=2) + code = proto.Field(proto.ENUM, number=1, enum=code_pb2.Code,) + cause = proto.Field(proto.STRING, number=2,) class IamPolicyAnalysisResult(proto.Message): @@ -557,7 +523,6 @@ class IamPolicyAnalysisResult(proto.Message): class Resource(proto.Message): r"""A Google Cloud resource under analysis. - Attributes: full_resource_name (str): The `full resource @@ -566,15 +531,13 @@ class Resource(proto.Message): The analysis state of this resource. """ - full_resource_name = proto.Field(proto.STRING, number=1) - + full_resource_name = proto.Field(proto.STRING, number=1,) analysis_state = proto.Field( proto.MESSAGE, number=2, message="IamPolicyAnalysisState", ) class Access(proto.Message): r"""An IAM role or permission under analysis. - Attributes: role (str): The role. @@ -584,17 +547,14 @@ class Access(proto.Message): The analysis state of this access. """ - role = proto.Field(proto.STRING, number=1, oneof="oneof_access") - - permission = proto.Field(proto.STRING, number=2, oneof="oneof_access") - + role = proto.Field(proto.STRING, number=1, oneof="oneof_access",) + permission = proto.Field(proto.STRING, number=2, oneof="oneof_access",) analysis_state = proto.Field( proto.MESSAGE, number=3, message="IamPolicyAnalysisState", ) class Identity(proto.Message): r"""An identity under analysis. - Attributes: name (str): The identity name in any form of members appear in `IAM @@ -613,15 +573,13 @@ class Identity(proto.Message): The analysis state of this identity. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) analysis_state = proto.Field( proto.MESSAGE, number=2, message="IamPolicyAnalysisState", ) class Edge(proto.Message): r"""A directional edge. - Attributes: source_node (str): The source node of the edge. For example, it @@ -633,9 +591,8 @@ class Edge(proto.Message): node or an email of an identity. """ - source_node = proto.Field(proto.STRING, number=1) - - target_node = proto.Field(proto.STRING, number=2) + source_node = proto.Field(proto.STRING, number=1,) + target_node = proto.Field(proto.STRING, number=2,) class AccessControlList(proto.Message): r"""An access control list, derived from the above IAM policy binding, @@ -684,18 +641,15 @@ class AccessControlList(proto.Message): resources = proto.RepeatedField( proto.MESSAGE, number=1, message="IamPolicyAnalysisResult.Resource", ) - accesses = proto.RepeatedField( proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.Access", ) - resource_edges = proto.RepeatedField( proto.MESSAGE, number=3, message="IamPolicyAnalysisResult.Edge", ) class IdentityList(proto.Message): r"""The identities and group edges. - Attributes: identities (Sequence[google.cloud.asset_v1.types.IamPolicyAnalysisResult.Identity]): Only the identities that match one of the following @@ -721,22 +675,17 @@ class IdentityList(proto.Message): identities = proto.RepeatedField( proto.MESSAGE, number=1, message="IamPolicyAnalysisResult.Identity", ) - group_edges = proto.RepeatedField( proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.Edge", ) - attached_resource_full_name = proto.Field(proto.STRING, number=1) - - iam_binding = proto.Field(proto.MESSAGE, number=2, message=gi_policy.Binding,) - + attached_resource_full_name = proto.Field(proto.STRING, number=1,) + iam_binding = proto.Field(proto.MESSAGE, number=2, message=policy_pb2.Binding,) access_control_lists = proto.RepeatedField( proto.MESSAGE, number=3, message=AccessControlList, ) - identity_list = proto.Field(proto.MESSAGE, number=4, message=IdentityList,) - - fully_explored = proto.Field(proto.BOOL, number=5) + fully_explored = proto.Field(proto.BOOL, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p1beta1/__init__.py b/google/cloud/asset_v1p1beta1/__init__.py index 05b10389..e8433f15 100644 --- a/google/cloud/asset_v1p1beta1/__init__.py +++ b/google/cloud/asset_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + from .types.asset_service import SearchAllIamPoliciesRequest from .types.asset_service import SearchAllIamPoliciesResponse from .types.asset_service import SearchAllResourcesRequest @@ -24,8 +25,9 @@ from .types.assets import Permissions from .types.assets import StandardResourceMetadata - __all__ = ( + "AssetServiceAsyncClient", + "AssetServiceClient", "IamPolicySearchResult", "Permissions", "SearchAllIamPoliciesRequest", @@ -33,5 +35,4 @@ "SearchAllResourcesRequest", "SearchAllResourcesResponse", "StandardResourceMetadata", - "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p1beta1/gapic_metadata.json b/google/cloud/asset_v1p1beta1/gapic_metadata.json new file mode 100644 index 00000000..175cd294 --- /dev/null +++ b/google/cloud/asset_v1p1beta1/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p1beta1", + "protoPackage": "google.cloud.asset.v1p1beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "SearchAllIamPolicies": { + "methods": [ + "search_all_iam_policies" + ] + }, + "SearchAllResources": { + "methods": [ + "search_all_resources" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/asset_v1p1beta1/services/__init__.py b/google/cloud/asset_v1p1beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/asset_v1p1beta1/services/__init__.py +++ b/google/cloud/asset_v1p1beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py index ec3c27d2..cb995a56 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AssetServiceClient from .async_client import AssetServiceAsyncClient diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py index 056f1410..3e9880e3 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.asset_v1p1beta1.services.asset_service import pagers from google.cloud.asset_v1p1beta1.types import asset_service from google.cloud.asset_v1p1beta1.types import assets - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .client import AssetServiceClient @@ -51,20 +48,16 @@ class AssetServiceAsyncClient: 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 @@ -72,7 +65,8 @@ class AssetServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -87,7 +81,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -104,7 +98,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AssetServiceTransport: The transport used by the client instance. @@ -118,12 +112,12 @@ def transport(self) -> AssetServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -155,7 +149,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AssetServiceClient( credentials=credentials, transport=transport, @@ -212,7 +205,6 @@ async def search_all_resources( This corresponds to the ``asset_types`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -241,12 +233,10 @@ async def search_all_resources( # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: request.query = query - if asset_types: request.asset_types.extend(asset_types) @@ -259,7 +249,8 @@ async def search_all_resources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -329,7 +320,6 @@ async def search_all_iam_policies( This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -358,7 +348,6 @@ async def search_all_iam_policies( # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: @@ -373,7 +362,8 @@ async def search_all_iam_policies( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/client.py b/google/cloud/asset_v1p1beta1/services/asset_service/client.py index e2a25499..7199d5b9 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/client.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,7 +33,6 @@ from google.cloud.asset_v1p1beta1.services.asset_service import pagers from google.cloud.asset_v1p1beta1.types import asset_service from google.cloud.asset_v1p1beta1.types import assets - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class AssetServiceClientMeta(type): _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +74,8 @@ class AssetServiceClient(metaclass=AssetServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -111,7 +109,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +127,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,16 +146,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AssetServiceTransport: The transport used by the client instance. + AssetServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -169,7 +169,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -180,7 +180,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -191,7 +191,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -202,7 +202,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -216,12 +216,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -276,9 +276,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -290,12 +291,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -310,8 +313,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -375,7 +378,6 @@ def search_all_resources( This corresponds to the ``asset_types`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -406,10 +408,8 @@ def search_all_resources( # there are no flattened fields. if not isinstance(request, asset_service.SearchAllResourcesRequest): request = asset_service.SearchAllResourcesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: @@ -483,7 +483,6 @@ def search_all_iam_policies( This corresponds to the ``query`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -514,10 +513,8 @@ def search_all_iam_policies( # there are no flattened fields. if not isinstance(request, asset_service.SearchAllIamPoliciesRequest): request = asset_service.SearchAllIamPoliciesRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if scope is not None: request.scope = scope if query is not None: diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py b/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py index 234b82b0..e0afa1a0 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -246,7 +244,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 c077c192..9158fc25 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py index ac7805cf..8ee42a9b 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.asset_v1p1beta1.types import asset_service - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, @@ -35,27 +34,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudasset.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -64,7 +77,7 @@ def __init__( 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. + scopes (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): @@ -78,29 +91,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -111,7 +171,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -125,7 +186,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=15.0, ), @@ -137,11 +199,11 @@ def _prep_wrapped_messages(self, client_info): @property def search_all_resources( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.SearchAllResourcesRequest], - typing.Union[ + Union[ asset_service.SearchAllResourcesResponse, - typing.Awaitable[asset_service.SearchAllResourcesResponse], + Awaitable[asset_service.SearchAllResourcesResponse], ], ]: raise NotImplementedError() @@ -149,11 +211,11 @@ def search_all_resources( @property def search_all_iam_policies( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.SearchAllIamPoliciesRequest], - typing.Union[ + Union[ asset_service.SearchAllIamPoliciesResponse, - typing.Awaitable[asset_service.SearchAllIamPoliciesResponse], + Awaitable[asset_service.SearchAllIamPoliciesResponse], ], ]: raise NotImplementedError() 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 ddeedcc9..4b4b685f 100644 --- a/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p1beta1/services/asset_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.asset_v1p1beta1.types import asset_service - from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO @@ -50,7 +47,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -64,7 +61,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -174,7 +172,7 @@ def __init__( def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -205,13 +203,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) 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 fc04ac39..a93fad9a 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.asset_v1p1beta1.types import asset_service - from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AssetServiceGrpcTransport @@ -53,7 +50,7 @@ class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -80,13 +77,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -94,7 +93,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -108,7 +107,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -166,7 +166,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/asset_v1p1beta1/types/__init__.py b/google/cloud/asset_v1p1beta1/types/__init__.py index 47321140..c70c551c 100644 --- a/google/cloud/asset_v1p1beta1/types/__init__.py +++ b/google/cloud/asset_v1p1beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset_service import ( SearchAllIamPoliciesRequest, SearchAllIamPoliciesResponse, diff --git a/google/cloud/asset_v1p1beta1/types/asset_service.py b/google/cloud/asset_v1p1beta1/types/asset_service.py index b0c8459f..ba012487 100644 --- a/google/cloud/asset_v1p1beta1/types/asset_service.py +++ b/google/cloud/asset_v1p1beta1/types/asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,10 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.asset_v1p1beta1.types import assets @@ -34,7 +31,6 @@ class SearchAllResourcesRequest(proto.Message): r"""Search all resources request. - Attributes: scope (str): Required. The relative name of an asset. The search is @@ -73,22 +69,16 @@ class SearchAllResourcesRequest(proto.Message): example, " foo , bar desc ". """ - scope = proto.Field(proto.STRING, number=1) - - query = proto.Field(proto.STRING, number=2) - - asset_types = proto.RepeatedField(proto.STRING, number=3) - - page_size = proto.Field(proto.INT32, number=4) - - page_token = proto.Field(proto.STRING, number=5) - - order_by = proto.Field(proto.STRING, number=10) + scope = proto.Field(proto.STRING, number=1,) + query = proto.Field(proto.STRING, number=2,) + asset_types = proto.RepeatedField(proto.STRING, number=3,) + page_size = proto.Field(proto.INT32, number=4,) + page_token = proto.Field(proto.STRING, number=5,) + order_by = proto.Field(proto.STRING, number=10,) class SearchAllResourcesResponse(proto.Message): r"""Search all resources response. - Attributes: results (Sequence[google.cloud.asset_v1p1beta1.types.StandardResourceMetadata]): A list of resource that match the search @@ -107,13 +97,11 @@ def raw_page(self): results = proto.RepeatedField( proto.MESSAGE, number=1, message=assets.StandardResourceMetadata, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class SearchAllIamPoliciesRequest(proto.Message): r"""Search all IAM policies request. - Attributes: scope (str): Required. The relative name of an asset. The search is @@ -144,18 +132,14 @@ class SearchAllIamPoliciesRequest(proto.Message): identical to those in the previous call. """ - scope = proto.Field(proto.STRING, number=1) - - query = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - page_token = proto.Field(proto.STRING, number=4) + scope = proto.Field(proto.STRING, number=1,) + query = proto.Field(proto.STRING, number=2,) + page_size = proto.Field(proto.INT32, number=3,) + page_token = proto.Field(proto.STRING, number=4,) class SearchAllIamPoliciesResponse(proto.Message): r"""Search all IAM policies response. - Attributes: results (Sequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult]): A list of IamPolicy that match the search @@ -175,8 +159,7 @@ def raw_page(self): results = proto.RepeatedField( proto.MESSAGE, number=1, message=assets.IamPolicySearchResult, ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p1beta1/types/assets.py b/google/cloud/asset_v1p1beta1/types/assets.py index 9fa19903..1046dd68 100644 --- a/google/cloud/asset_v1p1beta1/types/assets.py +++ b/google/cloud/asset_v1p1beta1/types/assets.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # 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 giv_policy # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore __protobuf__ = proto.module( @@ -29,7 +26,6 @@ class StandardResourceMetadata(proto.Message): r"""The standard metadata of a cloud resource. - Attributes: name (str): The full resource name. For example: @@ -70,28 +66,19 @@ class StandardResourceMetadata(proto.Message): for more information. """ - name = proto.Field(proto.STRING, number=1) - - asset_type = proto.Field(proto.STRING, number=2) - - project = proto.Field(proto.STRING, number=3) - - display_name = proto.Field(proto.STRING, number=4) - - description = proto.Field(proto.STRING, number=5) - - additional_attributes = proto.RepeatedField(proto.STRING, number=10) - - location = proto.Field(proto.STRING, number=11) - - labels = proto.MapField(proto.STRING, proto.STRING, number=12) - - network_tags = proto.RepeatedField(proto.STRING, number=13) + name = proto.Field(proto.STRING, number=1,) + asset_type = proto.Field(proto.STRING, number=2,) + project = proto.Field(proto.STRING, number=3,) + display_name = proto.Field(proto.STRING, number=4,) + description = proto.Field(proto.STRING, number=5,) + additional_attributes = proto.RepeatedField(proto.STRING, number=10,) + location = proto.Field(proto.STRING, number=11,) + labels = proto.MapField(proto.STRING, proto.STRING, number=12,) + network_tags = proto.RepeatedField(proto.STRING, number=13,) class IamPolicySearchResult(proto.Message): r"""The result for a IAM Policy search. - Attributes: resource (str): The `full resource @@ -120,7 +107,6 @@ class IamPolicySearchResult(proto.Message): class Explanation(proto.Message): r"""Explanation about the IAM policy search result. - Attributes: matched_permissions (Sequence[google.cloud.asset_v1p1beta1.types.IamPolicySearchResult.Explanation.MatchedPermissionsEntry]): The map from roles to their included permission matching the @@ -135,25 +121,21 @@ class Explanation(proto.Message): proto.STRING, proto.MESSAGE, number=1, message="Permissions", ) - resource = proto.Field(proto.STRING, number=1) - - project = proto.Field(proto.STRING, number=3) - - policy = proto.Field(proto.MESSAGE, number=4, message=giv_policy.Policy,) - + resource = proto.Field(proto.STRING, number=1,) + project = proto.Field(proto.STRING, number=3,) + policy = proto.Field(proto.MESSAGE, number=4, message=policy_pb2.Policy,) explanation = proto.Field(proto.MESSAGE, number=5, message=Explanation,) class Permissions(proto.Message): r"""IAM permissions - Attributes: permissions (Sequence[str]): A list of permissions. A sample permission string: "compute.disk.get". """ - permissions = proto.RepeatedField(proto.STRING, number=1) + permissions = proto.RepeatedField(proto.STRING, number=1,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p2beta1/__init__.py b/google/cloud/asset_v1p2beta1/__init__.py index 159a6d98..8a77ccdd 100644 --- a/google/cloud/asset_v1p2beta1/__init__.py +++ b/google/cloud/asset_v1p2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,7 +15,8 @@ # from .services.asset_service import AssetServiceClient -from .types.asset_service import ContentType +from .services.asset_service import AssetServiceAsyncClient + from .types.asset_service import CreateFeedRequest from .types.asset_service import DeleteFeedRequest from .types.asset_service import Feed @@ -28,14 +28,16 @@ from .types.asset_service import OutputConfig from .types.asset_service import PubsubDestination from .types.asset_service import UpdateFeedRequest +from .types.asset_service import ContentType from .types.assets import Asset from .types.assets import Resource from .types.assets import TemporalAsset from .types.assets import TimeWindow - __all__ = ( + "AssetServiceAsyncClient", "Asset", + "AssetServiceClient", "ContentType", "CreateFeedRequest", "DeleteFeedRequest", @@ -51,5 +53,4 @@ "TemporalAsset", "TimeWindow", "UpdateFeedRequest", - "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p2beta1/gapic_metadata.json b/google/cloud/asset_v1p2beta1/gapic_metadata.json new file mode 100644 index 00000000..3c3674a8 --- /dev/null +++ b/google/cloud/asset_v1p2beta1/gapic_metadata.json @@ -0,0 +1,73 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p2beta1", + "protoPackage": "google.cloud.asset.v1p2beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "CreateFeed": { + "methods": [ + "create_feed" + ] + }, + "DeleteFeed": { + "methods": [ + "delete_feed" + ] + }, + "GetFeed": { + "methods": [ + "get_feed" + ] + }, + "ListFeeds": { + "methods": [ + "list_feeds" + ] + }, + "UpdateFeed": { + "methods": [ + "update_feed" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/asset_v1p2beta1/services/__init__.py b/google/cloud/asset_v1p2beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/asset_v1p2beta1/services/__init__.py +++ b/google/cloud/asset_v1p2beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py index ec3c27d2..cb995a56 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AssetServiceClient from .async_client import AssetServiceAsyncClient diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py index b6ab2109..9d06f397 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,14 +20,13 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.asset_v1p2beta1.types import asset_service - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .client import AssetServiceClient @@ -45,27 +42,22 @@ class AssetServiceAsyncClient: feed_path = staticmethod(AssetServiceClient.feed_path) parse_feed_path = staticmethod(AssetServiceClient.parse_feed_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 @@ -73,7 +65,8 @@ class AssetServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -88,7 +81,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -105,7 +98,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AssetServiceTransport: The transport used by the client instance. @@ -119,12 +112,12 @@ def transport(self) -> AssetServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -156,7 +149,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AssetServiceClient( credentials=credentials, transport=transport, @@ -194,7 +186,6 @@ async def create_feed( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -226,7 +217,6 @@ async def create_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -273,7 +263,6 @@ async def get_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -305,7 +294,6 @@ async def get_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -318,7 +306,8 @@ async def get_feed( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -364,7 +353,6 @@ async def list_feeds( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -389,7 +377,6 @@ async def list_feeds( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -402,7 +389,8 @@ async def list_feeds( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -446,7 +434,6 @@ async def update_feed( This corresponds to the ``feed`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -478,7 +465,6 @@ async def update_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if feed is not None: request.feed = feed @@ -527,7 +513,6 @@ async def delete_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -548,7 +533,6 @@ async def delete_feed( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -561,7 +545,8 @@ async def delete_feed( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/client.py b/google/cloud/asset_v1p2beta1/services/asset_service/client.py index a2ddcef1..1a06af4f 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/client.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,17 +21,16 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.asset_v1p2beta1.types import asset_service - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -52,7 +49,7 @@ class AssetServiceClientMeta(type): _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -75,7 +72,8 @@ class AssetServiceClient(metaclass=AssetServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -109,7 +107,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -126,7 +125,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -145,27 +144,28 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AssetServiceTransport: The transport used by the client instance. + AssetServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def feed_path(project: str, feed: str,) -> str: - """Return a fully-qualified feed string.""" + """Returns a fully-qualified feed string.""" return "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) @staticmethod def parse_feed_path(path: str) -> Dict[str, str]: - """Parse a feed path into its component segments.""" + """Parses a feed path into its component segments.""" m = re.match(r"^projects/(?P.+?)/feeds/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -178,7 +178,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -189,7 +189,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -200,7 +200,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -211,7 +211,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -225,12 +225,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -285,9 +285,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -299,12 +300,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -319,8 +322,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -365,7 +368,6 @@ def create_feed( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -399,10 +401,8 @@ def create_feed( # there are no flattened fields. if not isinstance(request, asset_service.CreateFeedRequest): request = asset_service.CreateFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -445,7 +445,6 @@ def get_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -479,10 +478,8 @@ def get_feed( # there are no flattened fields. if not isinstance(request, asset_service.GetFeedRequest): request = asset_service.GetFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -528,7 +525,6 @@ def list_feeds( This corresponds to the ``parent`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -555,10 +551,8 @@ def list_feeds( # there are no flattened fields. if not isinstance(request, asset_service.ListFeedsRequest): request = asset_service.ListFeedsRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent @@ -602,7 +596,6 @@ def update_feed( This corresponds to the ``feed`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -636,10 +629,8 @@ def update_feed( # there are no flattened fields. if not isinstance(request, asset_service.UpdateFeedRequest): request = asset_service.UpdateFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if feed is not None: request.feed = feed @@ -684,7 +675,6 @@ def delete_feed( This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -707,10 +697,8 @@ def delete_feed( # there are no flattened fields. if not isinstance(request, asset_service.DeleteFeedRequest): request = asset_service.DeleteFeedRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name 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 c077c192..9158fc25 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py index fae4c7be..5d867d28 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -36,27 +35,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudasset.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -65,7 +78,7 @@ def __init__( 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. + scopes (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): @@ -79,29 +92,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -115,7 +175,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -129,7 +190,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -146,7 +208,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -158,29 +221,28 @@ def _prep_wrapped_messages(self, client_info): @property def create_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.CreateFeedRequest], - typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], ]: raise NotImplementedError() @property def get_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.GetFeedRequest], - typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], ]: raise NotImplementedError() @property def list_feeds( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.ListFeedsRequest], - typing.Union[ - asset_service.ListFeedsResponse, - typing.Awaitable[asset_service.ListFeedsResponse], + Union[ + asset_service.ListFeedsResponse, Awaitable[asset_service.ListFeedsResponse] ], ]: raise NotImplementedError() @@ -188,18 +250,18 @@ def list_feeds( @property def update_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.UpdateFeedRequest], - typing.Union[asset_service.Feed, typing.Awaitable[asset_service.Feed]], + Union[asset_service.Feed, Awaitable[asset_service.Feed]], ]: raise NotImplementedError() @property def delete_feed( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.DeleteFeedRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]], ]: raise NotImplementedError() 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 70d3ab33..c6342408 100644 --- a/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p2beta1/services/asset_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO @@ -51,7 +48,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -65,7 +62,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -175,7 +173,7 @@ def __init__( def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -206,13 +204,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -328,7 +328,9 @@ def update_feed( return self._stubs["update_feed"] @property - def delete_feed(self) -> Callable[[asset_service.DeleteFeedRequest], empty.Empty]: + def delete_feed( + self, + ) -> Callable[[asset_service.DeleteFeedRequest], empty_pb2.Empty]: r"""Return a callable for the delete feed method over gRPC. Deletes an asset feed. @@ -347,7 +349,7 @@ def delete_feed(self) -> Callable[[asset_service.DeleteFeedRequest], empty.Empty self._stubs["delete_feed"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed", request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_feed"] 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 275c68d3..aaaa591f 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.asset_v1p2beta1.types import asset_service -from google.protobuf import empty_pb2 as empty # type: ignore - +from google.protobuf import empty_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AssetServiceGrpcTransport @@ -54,7 +51,7 @@ class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -81,13 +78,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -95,7 +94,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -109,7 +108,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -167,7 +167,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -338,7 +337,7 @@ def update_feed( @property def delete_feed( self, - ) -> Callable[[asset_service.DeleteFeedRequest], Awaitable[empty.Empty]]: + ) -> Callable[[asset_service.DeleteFeedRequest], Awaitable[empty_pb2.Empty]]: r"""Return a callable for the delete feed method over gRPC. Deletes an asset feed. @@ -357,7 +356,7 @@ def delete_feed( self._stubs["delete_feed"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1p2beta1.AssetService/DeleteFeed", request_serializer=asset_service.DeleteFeedRequest.serialize, - response_deserializer=empty.Empty.FromString, + response_deserializer=empty_pb2.Empty.FromString, ) return self._stubs["delete_feed"] diff --git a/google/cloud/asset_v1p2beta1/types/__init__.py b/google/cloud/asset_v1p2beta1/types/__init__.py index 0976221c..a4ac7216 100644 --- a/google/cloud/asset_v1p2beta1/types/__init__.py +++ b/google/cloud/asset_v1p2beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset_service import ( CreateFeedRequest, DeleteFeedRequest, diff --git a/google/cloud/asset_v1p2beta1/types/asset_service.py b/google/cloud/asset_v1p2beta1/types/asset_service.py index 74a242ca..682756ea 100644 --- a/google/cloud/asset_v1p2beta1/types/asset_service.py +++ b/google/cloud/asset_v1p2beta1/types/asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,11 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore __protobuf__ = proto.module( @@ -49,7 +46,6 @@ class ContentType(proto.Enum): class CreateFeedRequest(proto.Message): r"""Create asset feed request. - Attributes: parent (str): Required. The name of the @@ -72,16 +68,13 @@ class CreateFeedRequest(proto.Message): organizations/organization_number/feeds/feed_id """ - parent = proto.Field(proto.STRING, number=1) - - feed_id = proto.Field(proto.STRING, number=2) - + parent = proto.Field(proto.STRING, number=1,) + feed_id = proto.Field(proto.STRING, number=2,) feed = proto.Field(proto.MESSAGE, number=3, message="Feed",) class GetFeedRequest(proto.Message): r"""Get asset feed request. - Attributes: name (str): Required. The name of the Feed and it must be in the format @@ -90,12 +83,11 @@ class GetFeedRequest(proto.Message): organizations/organization_number/feeds/feed_id """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListFeedsRequest(proto.Message): r"""List asset feeds request. - Attributes: parent (str): Required. The parent @@ -106,12 +98,11 @@ class ListFeedsRequest(proto.Message): "projects/my-project-id"). """ - parent = proto.Field(proto.STRING, number=1) + parent = proto.Field(proto.STRING, number=1,) class ListFeedsResponse(proto.Message): r""" - Attributes: feeds (Sequence[google.cloud.asset_v1p2beta1.types.Feed]): A list of feeds. @@ -122,7 +113,6 @@ class ListFeedsResponse(proto.Message): class UpdateFeedRequest(proto.Message): r"""Update asset feed request. - Attributes: feed (google.cloud.asset_v1p2beta1.types.Feed): Required. The new values of feed details. It must match an @@ -137,13 +127,13 @@ class UpdateFeedRequest(proto.Message): """ feed = proto.Field(proto.MESSAGE, number=1, message="Feed",) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=2, message=field_mask_pb2.FieldMask, + ) class DeleteFeedRequest(proto.Message): r""" - Attributes: name (str): Required. The name of the feed and it must be in the format @@ -152,12 +142,11 @@ class DeleteFeedRequest(proto.Message): organizations/organization_number/feeds/feed_id """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class OutputConfig(proto.Message): r"""Output configuration for export assets destination. - Attributes: gcs_destination (google.cloud.asset_v1p2beta1.types.GcsDestination): Destination on Cloud Storage. @@ -170,7 +159,6 @@ class OutputConfig(proto.Message): 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 @@ -181,24 +169,22 @@ class GcsDestination(proto.Message): for more information. """ - uri = proto.Field(proto.STRING, number=1, oneof="object_uri") + uri = proto.Field(proto.STRING, number=1, oneof="object_uri",) class PubsubDestination(proto.Message): r"""A Cloud Pubsub destination. - Attributes: topic (str): The name of the Cloud Pub/Sub topic to publish to. For example: ``projects/PROJECT_ID/topics/TOPIC_ID``. """ - topic = proto.Field(proto.STRING, number=1) + topic = proto.Field(proto.STRING, number=1,) class FeedOutputConfig(proto.Message): r"""Output configuration for asset feed destination. - Attributes: pubsub_destination (google.cloud.asset_v1p2beta1.types.PubsubDestination): Destination on Cloud Pubsub. @@ -255,14 +241,10 @@ class Feed(proto.Message): where the asset updates are published to. """ - name = proto.Field(proto.STRING, number=1) - - asset_names = proto.RepeatedField(proto.STRING, number=2) - - asset_types = proto.RepeatedField(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + asset_names = proto.RepeatedField(proto.STRING, number=2,) + asset_types = proto.RepeatedField(proto.STRING, number=3,) content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) - feed_output_config = proto.Field( proto.MESSAGE, number=5, message="FeedOutputConfig", ) diff --git a/google/cloud/asset_v1p2beta1/types/assets.py b/google/cloud/asset_v1p2beta1/types/assets.py index aa225389..50722bd7 100644 --- a/google/cloud/asset_v1p2beta1/types/assets.py +++ b/google/cloud/asset_v1p2beta1/types/assets.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,13 +13,11 @@ # 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 +from google.iam.v1 import policy_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -45,15 +42,12 @@ class TemporalAsset(proto.Message): """ window = proto.Field(proto.MESSAGE, number=1, message="TimeWindow",) - - deleted = proto.Field(proto.BOOL, number=2) - + 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 (google.protobuf.timestamp_pb2.Timestamp): Start time of the time window (exclusive). @@ -62,9 +56,8 @@ class TimeWindow(proto.Message): 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,) + start_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) class Asset(proto.Message): @@ -99,20 +92,15 @@ class Asset(proto.Message): "organizations/1234"] """ - name = proto.Field(proto.STRING, number=1) - - asset_type = proto.Field(proto.STRING, number=2) - + 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,) - - ancestors = proto.RepeatedField(proto.STRING, number=6) + iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy_pb2.Policy,) + ancestors = proto.RepeatedField(proto.STRING, number=6,) class Resource(proto.Message): r"""Representation of a cloud resource. - Attributes: version (str): The API version. Example: "v1". @@ -153,17 +141,12 @@ class Resource(proto.Message): 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,) + 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_pb2.Struct,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p4beta1/__init__.py b/google/cloud/asset_v1p4beta1/__init__.py index 108a29dc..4852a868 100644 --- a/google/cloud/asset_v1p4beta1/__init__.py +++ b/google/cloud/asset_v1p4beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,6 +15,8 @@ # from .services.asset_service import AssetServiceClient +from .services.asset_service import AssetServiceAsyncClient + from .types.asset_service import AnalyzeIamPolicyRequest from .types.asset_service import AnalyzeIamPolicyResponse from .types.asset_service import ExportIamPolicyAnalysisRequest @@ -24,14 +25,14 @@ from .types.asset_service import IamPolicyAnalysisQuery from .types.assets import IamPolicyAnalysisResult - __all__ = ( + "AssetServiceAsyncClient", "AnalyzeIamPolicyRequest", "AnalyzeIamPolicyResponse", + "AssetServiceClient", "ExportIamPolicyAnalysisRequest", "ExportIamPolicyAnalysisResponse", "IamPolicyAnalysisOutputConfig", "IamPolicyAnalysisQuery", "IamPolicyAnalysisResult", - "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p4beta1/gapic_metadata.json b/google/cloud/asset_v1p4beta1/gapic_metadata.json new file mode 100644 index 00000000..23a2f8a3 --- /dev/null +++ b/google/cloud/asset_v1p4beta1/gapic_metadata.json @@ -0,0 +1,43 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p4beta1", + "protoPackage": "google.cloud.asset.v1p4beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "ExportIamPolicyAnalysis": { + "methods": [ + "export_iam_policy_analysis" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "AnalyzeIamPolicy": { + "methods": [ + "analyze_iam_policy" + ] + }, + "ExportIamPolicyAnalysis": { + "methods": [ + "export_iam_policy_analysis" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/asset_v1p4beta1/services/__init__.py b/google/cloud/asset_v1p4beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/asset_v1p4beta1/services/__init__.py +++ b/google/cloud/asset_v1p4beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py index ec3c27d2..cb995a56 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AssetServiceClient from .async_client import AssetServiceAsyncClient diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py index d4267794..d3a68933 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,17 +20,16 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_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_v1p4beta1.types import asset_service from google.cloud.asset_v1p4beta1.types import assets - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .client import AssetServiceClient @@ -52,20 +49,16 @@ class AssetServiceAsyncClient: 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 @@ -73,7 +66,8 @@ class AssetServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -88,7 +82,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -105,7 +99,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AssetServiceTransport: The transport used by the client instance. @@ -119,12 +113,12 @@ def transport(self) -> AssetServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -156,7 +150,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AssetServiceClient( credentials=credentials, transport=transport, @@ -181,7 +174,6 @@ async def analyze_iam_policy( request (:class:`google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest`): The request object. A request message for [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -195,7 +187,6 @@ async def analyze_iam_policy( """ # Create or coerce a protobuf request object. - request = asset_service.AnalyzeIamPolicyRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -206,7 +197,9 @@ async def analyze_iam_policy( initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=300.0, ), default_timeout=300.0, @@ -245,7 +238,6 @@ async def export_iam_policy_analysis( request (:class:`google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest`): The request object. A request message for [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -263,7 +255,6 @@ async def export_iam_policy_analysis( """ # Create or coerce a protobuf request object. - request = asset_service.ExportIamPolicyAnalysisRequest(request) # Wrap the RPC method; this adds retry and timeout information, diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/client.py b/google/cloud/asset_v1p4beta1/services/asset_service/client.py index f5a39adb..bf10ed02 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/client.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -36,7 +34,6 @@ from google.api_core import operation_async # type: ignore from google.cloud.asset_v1p4beta1.types import asset_service from google.cloud.asset_v1p4beta1.types import assets - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class AssetServiceClientMeta(type): _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -78,7 +75,8 @@ class AssetServiceClient(metaclass=AssetServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -112,7 +110,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -129,7 +128,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -148,16 +147,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AssetServiceTransport: The transport used by the client instance. + AssetServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -170,7 +170,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -181,7 +181,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -192,7 +192,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -203,7 +203,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -217,12 +217,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -277,9 +277,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -291,12 +292,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -311,8 +314,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -344,7 +347,6 @@ def analyze_iam_policy( request (google.cloud.asset_v1p4beta1.types.AnalyzeIamPolicyRequest): The request object. A request message for [AssetService.AnalyzeIamPolicy][google.cloud.asset.v1p4beta1.AssetService.AnalyzeIamPolicy]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -358,7 +360,6 @@ def analyze_iam_policy( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a asset_service.AnalyzeIamPolicyRequest. # There's no risk of modifying the input as we've already verified @@ -402,7 +403,6 @@ def export_iam_policy_analysis( request (google.cloud.asset_v1p4beta1.types.ExportIamPolicyAnalysisRequest): The request object. A request message for [AssetService.ExportIamPolicyAnalysis][google.cloud.asset.v1p4beta1.AssetService.ExportIamPolicyAnalysis]. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -420,7 +420,6 @@ def export_iam_policy_analysis( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a asset_service.ExportIamPolicyAnalysisRequest. # There's no risk of modifying the input as we've already verified 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 c077c192..9158fc25 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py index 8702f39f..65d21b3f 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,21 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.asset_v1p4beta1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( @@ -37,27 +36,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudasset.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -66,7 +79,7 @@ def __init__( 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. + scopes (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): @@ -80,29 +93,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -112,7 +172,9 @@ def _prep_wrapped_messages(self, client_info): initial=0.1, maximum=60.0, multiplier=1.3, - predicate=retries.if_exception_type(exceptions.ServiceUnavailable,), + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), deadline=300.0, ), default_timeout=300.0, @@ -133,11 +195,11 @@ def operations_client(self) -> operations_v1.OperationsClient: @property def analyze_iam_policy( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.AnalyzeIamPolicyRequest], - typing.Union[ + Union[ asset_service.AnalyzeIamPolicyResponse, - typing.Awaitable[asset_service.AnalyzeIamPolicyResponse], + Awaitable[asset_service.AnalyzeIamPolicyResponse], ], ]: raise NotImplementedError() @@ -145,9 +207,9 @@ def analyze_iam_policy( @property def export_iam_policy_analysis( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.ExportIamPolicyAnalysisRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], ]: raise NotImplementedError() 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 7d2c0298..e958a387 100644 --- a/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p4beta1/services/asset_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,22 +13,20 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union 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 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.asset_v1p4beta1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -66,7 +63,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -208,13 +206,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -272,7 +272,9 @@ def analyze_iam_policy( @property def export_iam_policy_analysis( self, - ) -> Callable[[asset_service.ExportIamPolicyAnalysisRequest], operations.Operation]: + ) -> Callable[ + [asset_service.ExportIamPolicyAnalysisRequest], operations_pb2.Operation + ]: r"""Return a callable for the export iam policy analysis method over gRPC. Exports IAM policy analysis based on the specified request. This @@ -295,7 +297,7 @@ def export_iam_policy_analysis( self._stubs["export_iam_policy_analysis"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis", request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_iam_policy_analysis"] 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 f61d756b..7005c0f4 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,23 +13,21 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.asset_v1p4beta1.types import asset_service -from google.longrunning import operations_pb2 as operations # type: ignore - +from google.longrunning import operations_pb2 # type: ignore from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AssetServiceGrpcTransport @@ -55,7 +52,7 @@ class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -82,13 +79,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -96,7 +95,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -110,7 +109,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -169,7 +169,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint @@ -280,7 +279,8 @@ def analyze_iam_policy( def export_iam_policy_analysis( self, ) -> Callable[ - [asset_service.ExportIamPolicyAnalysisRequest], Awaitable[operations.Operation] + [asset_service.ExportIamPolicyAnalysisRequest], + Awaitable[operations_pb2.Operation], ]: r"""Return a callable for the export iam policy analysis method over gRPC. @@ -304,7 +304,7 @@ def export_iam_policy_analysis( self._stubs["export_iam_policy_analysis"] = self.grpc_channel.unary_unary( "/google.cloud.asset.v1p4beta1.AssetService/ExportIamPolicyAnalysis", request_serializer=asset_service.ExportIamPolicyAnalysisRequest.serialize, - response_deserializer=operations.Operation.FromString, + response_deserializer=operations_pb2.Operation.FromString, ) return self._stubs["export_iam_policy_analysis"] diff --git a/google/cloud/asset_v1p4beta1/types/__init__.py b/google/cloud/asset_v1p4beta1/types/__init__.py index cfe344dd..19b3df43 100644 --- a/google/cloud/asset_v1p4beta1/types/__init__.py +++ b/google/cloud/asset_v1p4beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset_service import ( AnalyzeIamPolicyRequest, AnalyzeIamPolicyResponse, diff --git a/google/cloud/asset_v1p4beta1/types/asset_service.py b/google/cloud/asset_v1p4beta1/types/asset_service.py index 67002613..033c7e2e 100644 --- a/google/cloud/asset_v1p4beta1/types/asset_service.py +++ b/google/cloud/asset_v1p4beta1/types/asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.asset_v1p4beta1.types import assets -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore __protobuf__ = proto.module( @@ -37,7 +34,6 @@ class IamPolicyAnalysisQuery(proto.Message): r"""IAM policy analysis query message. - Attributes: parent (str): Required. The relative name of the root @@ -74,7 +70,7 @@ class ResourceSelector(proto.Message): . """ - full_resource_name = proto.Field(proto.STRING, number=1) + full_resource_name = proto.Field(proto.STRING, number=1,) class IdentitySelector(proto.Message): r"""Specifies an identity for which to determine resource access, @@ -88,7 +84,7 @@ class IdentitySelector(proto.Message): binding `__. """ - identity = proto.Field(proto.STRING, number=1) + identity = proto.Field(proto.STRING, number=1,) class AccessSelector(proto.Message): r"""Specifies roles and/or permissions to analyze, to determine @@ -104,16 +100,12 @@ class AccessSelector(proto.Message): result. """ - roles = proto.RepeatedField(proto.STRING, number=1) - - permissions = proto.RepeatedField(proto.STRING, number=2) - - parent = proto.Field(proto.STRING, number=1) + roles = proto.RepeatedField(proto.STRING, number=1,) + permissions = proto.RepeatedField(proto.STRING, number=2,) + parent = proto.Field(proto.STRING, number=1,) resource_selector = proto.Field(proto.MESSAGE, number=2, message=ResourceSelector,) - identity_selector = proto.Field(proto.MESSAGE, number=3, message=IdentitySelector,) - access_selector = proto.Field(proto.MESSAGE, number=4, message=AccessSelector,) @@ -130,7 +122,6 @@ class AnalyzeIamPolicyRequest(proto.Message): class Options(proto.Message): r"""Contains request options. - Attributes: expand_groups (bool): Optional. If true, the identities section of the result will @@ -215,26 +206,19 @@ class Options(proto.Message): Default is empty. """ - expand_groups = proto.Field(proto.BOOL, number=1) - - expand_roles = proto.Field(proto.BOOL, number=2) - - expand_resources = proto.Field(proto.BOOL, number=3) - - output_resource_edges = proto.Field(proto.BOOL, number=4) - - output_group_edges = proto.Field(proto.BOOL, number=5) - - analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6) - + expand_groups = proto.Field(proto.BOOL, number=1,) + expand_roles = proto.Field(proto.BOOL, number=2,) + expand_resources = proto.Field(proto.BOOL, number=3,) + output_resource_edges = proto.Field(proto.BOOL, number=4,) + output_group_edges = proto.Field(proto.BOOL, number=5,) + analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6,) execution_timeout = proto.Field( - proto.MESSAGE, number=7, message=duration.Duration, + proto.MESSAGE, number=7, message=duration_pb2.Duration, ) analysis_query = proto.Field( proto.MESSAGE, number=1, message="IamPolicyAnalysisQuery", ) - options = proto.Field(proto.MESSAGE, number=2, message=Options,) @@ -264,7 +248,6 @@ class AnalyzeIamPolicyResponse(proto.Message): class IamPolicyAnalysis(proto.Message): r"""An analysis message to group the query and results. - Attributes: analysis_query (google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisQuery): The analysis query. @@ -282,21 +265,16 @@ class IamPolicyAnalysis(proto.Message): analysis_query = proto.Field( proto.MESSAGE, number=1, message="IamPolicyAnalysisQuery", ) - analysis_results = proto.RepeatedField( proto.MESSAGE, number=2, message=assets.IamPolicyAnalysisResult, ) - - fully_explored = proto.Field(proto.BOOL, number=3) + fully_explored = proto.Field(proto.BOOL, number=3,) main_analysis = proto.Field(proto.MESSAGE, number=1, message=IamPolicyAnalysis,) - service_account_impersonation_analysis = proto.RepeatedField( proto.MESSAGE, number=2, message=IamPolicyAnalysis, ) - - fully_explored = proto.Field(proto.BOOL, number=3) - + fully_explored = proto.Field(proto.BOOL, number=3,) non_critical_errors = proto.RepeatedField( proto.MESSAGE, number=4, message=assets.IamPolicyAnalysisResult.AnalysisState, ) @@ -313,7 +291,6 @@ class IamPolicyAnalysisOutputConfig(proto.Message): class GcsDestination(proto.Message): r"""A Cloud Storage location. - Attributes: uri (str): Required. The uri of the Cloud Storage object. It's the same @@ -324,7 +301,7 @@ class GcsDestination(proto.Message): for more information. """ - uri = proto.Field(proto.STRING, number=1) + uri = proto.Field(proto.STRING, number=1,) gcs_destination = proto.Field( proto.MESSAGE, number=1, oneof="destination", message=GcsDestination, @@ -347,7 +324,6 @@ class ExportIamPolicyAnalysisRequest(proto.Message): class Options(proto.Message): r"""Contains request options. - Attributes: expand_groups (bool): Optional. If true, the identities section of the result will @@ -418,24 +394,17 @@ class Options(proto.Message): Default is false. """ - expand_groups = proto.Field(proto.BOOL, number=1) - - expand_roles = proto.Field(proto.BOOL, number=2) - - expand_resources = proto.Field(proto.BOOL, number=3) - - output_resource_edges = proto.Field(proto.BOOL, number=4) - - output_group_edges = proto.Field(proto.BOOL, number=5) - - analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6) + expand_groups = proto.Field(proto.BOOL, number=1,) + expand_roles = proto.Field(proto.BOOL, number=2,) + expand_resources = proto.Field(proto.BOOL, number=3,) + output_resource_edges = proto.Field(proto.BOOL, number=4,) + output_group_edges = proto.Field(proto.BOOL, number=5,) + analyze_service_account_impersonation = proto.Field(proto.BOOL, number=6,) analysis_query = proto.Field( proto.MESSAGE, number=1, message="IamPolicyAnalysisQuery", ) - options = proto.Field(proto.MESSAGE, number=2, message=Options,) - output_config = proto.Field( proto.MESSAGE, number=3, message="IamPolicyAnalysisOutputConfig", ) diff --git a/google/cloud/asset_v1p4beta1/types/assets.py b/google/cloud/asset_v1p4beta1/types/assets.py index 92609db9..2374dfae 100644 --- a/google/cloud/asset_v1p4beta1/types/assets.py +++ b/google/cloud/asset_v1p4beta1/types/assets.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # 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.rpc import code_pb2 as gr_code # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.rpc import code_pb2 # type: ignore __protobuf__ = proto.module( @@ -74,13 +71,11 @@ class AnalysisState(proto.Message): of failure. """ - code = proto.Field(proto.ENUM, number=1, enum=gr_code.Code,) - - cause = proto.Field(proto.STRING, number=2) + code = proto.Field(proto.ENUM, number=1, enum=code_pb2.Code,) + cause = proto.Field(proto.STRING, number=2,) class Resource(proto.Message): r"""A GCP resource that appears in an access control list. - Attributes: full_resource_name (str): The `full resource @@ -89,15 +84,13 @@ class Resource(proto.Message): The analysis state of this resource node. """ - full_resource_name = proto.Field(proto.STRING, number=1) - + full_resource_name = proto.Field(proto.STRING, number=1,) analysis_state = proto.Field( proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.AnalysisState", ) class Access(proto.Message): r"""A role or permission that appears in an access control list. - Attributes: role (str): The role. @@ -107,17 +100,14 @@ class Access(proto.Message): The analysis state of this access node. """ - role = proto.Field(proto.STRING, number=1, oneof="oneof_access") - - permission = proto.Field(proto.STRING, number=2, oneof="oneof_access") - + role = proto.Field(proto.STRING, number=1, oneof="oneof_access",) + permission = proto.Field(proto.STRING, number=2, oneof="oneof_access",) analysis_state = proto.Field( proto.MESSAGE, number=3, message="IamPolicyAnalysisResult.AnalysisState", ) class Edge(proto.Message): r"""A directional edge. - Attributes: source_node (str): The source node of the edge. @@ -125,13 +115,11 @@ class Edge(proto.Message): The target node of the edge. """ - source_node = proto.Field(proto.STRING, number=1) - - target_node = proto.Field(proto.STRING, number=2) + source_node = proto.Field(proto.STRING, number=1,) + target_node = proto.Field(proto.STRING, number=2,) class Identity(proto.Message): r"""An identity that appears in an access control list. - Attributes: name (str): The identity name in any form of members appear in `IAM @@ -150,8 +138,7 @@ class Identity(proto.Message): The analysis state of this identity node. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) analysis_state = proto.Field( proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.AnalysisState", ) @@ -203,18 +190,15 @@ class AccessControlList(proto.Message): resources = proto.RepeatedField( proto.MESSAGE, number=1, message="IamPolicyAnalysisResult.Resource", ) - accesses = proto.RepeatedField( proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.Access", ) - resource_edges = proto.RepeatedField( proto.MESSAGE, number=3, message="IamPolicyAnalysisResult.Edge", ) class IdentityList(proto.Message): r""" - Attributes: identities (Sequence[google.cloud.asset_v1p4beta1.types.IamPolicyAnalysisResult.Identity]): Only the identities that match one of the following @@ -240,22 +224,17 @@ class IdentityList(proto.Message): identities = proto.RepeatedField( proto.MESSAGE, number=1, message="IamPolicyAnalysisResult.Identity", ) - group_edges = proto.RepeatedField( proto.MESSAGE, number=2, message="IamPolicyAnalysisResult.Edge", ) - attached_resource_full_name = proto.Field(proto.STRING, number=1) - - iam_binding = proto.Field(proto.MESSAGE, number=2, message=policy.Binding,) - + attached_resource_full_name = proto.Field(proto.STRING, number=1,) + iam_binding = proto.Field(proto.MESSAGE, number=2, message=policy_pb2.Binding,) access_control_lists = proto.RepeatedField( proto.MESSAGE, number=3, message=AccessControlList, ) - identity_list = proto.Field(proto.MESSAGE, number=4, message=IdentityList,) - - fully_explored = proto.Field(proto.BOOL, number=5) + fully_explored = proto.Field(proto.BOOL, number=5,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p5beta1/__init__.py b/google/cloud/asset_v1p5beta1/__init__.py index e4ca4004..59a33bb0 100644 --- a/google/cloud/asset_v1p5beta1/__init__.py +++ b/google/cloud/asset_v1p5beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -16,18 +15,20 @@ # from .services.asset_service import AssetServiceClient -from .types.asset_service import ContentType +from .services.asset_service import AssetServiceAsyncClient + from .types.asset_service import ListAssetsRequest from .types.asset_service import ListAssetsResponse +from .types.asset_service import ContentType from .types.assets import Asset from .types.assets import Resource - __all__ = ( + "AssetServiceAsyncClient", "Asset", + "AssetServiceClient", "ContentType", "ListAssetsRequest", "ListAssetsResponse", "Resource", - "AssetServiceClient", ) diff --git a/google/cloud/asset_v1p5beta1/gapic_metadata.json b/google/cloud/asset_v1p5beta1/gapic_metadata.json new file mode 100644 index 00000000..3d280aa7 --- /dev/null +++ b/google/cloud/asset_v1p5beta1/gapic_metadata.json @@ -0,0 +1,33 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.asset_v1p5beta1", + "protoPackage": "google.cloud.asset.v1p5beta1", + "schema": "1.0", + "services": { + "AssetService": { + "clients": { + "grpc": { + "libraryClient": "AssetServiceClient", + "rpcs": { + "ListAssets": { + "methods": [ + "list_assets" + ] + } + } + }, + "grpc-async": { + "libraryClient": "AssetServiceAsyncClient", + "rpcs": { + "ListAssets": { + "methods": [ + "list_assets" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/asset_v1p5beta1/services/__init__.py b/google/cloud/asset_v1p5beta1/services/__init__.py index 42ffdf2b..4de65971 100644 --- a/google/cloud/asset_v1p5beta1/services/__init__.py +++ b/google/cloud/asset_v1p5beta1/services/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py b/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py index ec3c27d2..cb995a56 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .client import AssetServiceClient from .async_client import AssetServiceAsyncClient diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py b/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py index 537bc1d9..2c791571 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/async_client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict import functools import re @@ -22,16 +20,15 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.asset_v1p5beta1.services.asset_service import pagers from google.cloud.asset_v1p5beta1.types import asset_service from google.cloud.asset_v1p5beta1.types import assets - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport from .client import AssetServiceClient @@ -53,20 +50,16 @@ class AssetServiceAsyncClient: 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 @@ -74,7 +67,8 @@ class AssetServiceAsyncClient: @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -89,7 +83,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -106,7 +100,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: AssetServiceTransport: The transport used by the client instance. @@ -120,12 +114,12 @@ def transport(self) -> AssetServiceTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -157,7 +151,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = AssetServiceClient( credentials=credentials, transport=transport, @@ -179,7 +172,6 @@ async def list_assets( Args: request (:class:`google.cloud.asset_v1p5beta1.types.ListAssetsRequest`): The request object. ListAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -195,7 +187,6 @@ async def list_assets( """ # Create or coerce a protobuf request object. - request = asset_service.ListAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -207,7 +198,8 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/client.py b/google/cloud/asset_v1p5beta1/services/asset_service/client.py index 64df55d1..1c2a7205 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/client.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/client.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from distutils import util import os @@ -23,10 +21,10 @@ 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 exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport import mtls # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore @@ -35,7 +33,6 @@ from google.cloud.asset_v1p5beta1.services.asset_service import pagers from google.cloud.asset_v1p5beta1.types import asset_service from google.cloud.asset_v1p5beta1.types import assets - from .transports.base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import AssetServiceGrpcTransport from .transports.grpc_asyncio import AssetServiceGrpcAsyncIOTransport @@ -54,7 +51,7 @@ class AssetServiceClientMeta(type): _transport_registry["grpc_asyncio"] = AssetServiceGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[AssetServiceTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -77,7 +74,8 @@ class AssetServiceClient(metaclass=AssetServiceClientMeta): @staticmethod def _get_default_mtls_endpoint(api_endpoint): - """Convert api endpoint to mTLS endpoint. + """Converts api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. Args: @@ -111,7 +109,8 @@ def _get_default_mtls_endpoint(api_endpoint): @classmethod def from_service_account_info(cls, info: dict, *args, **kwargs): - """Creates an instance of this client using the provided credentials info. + """Creates an instance of this client using the provided credentials + info. Args: info (dict): The service account private key info. @@ -128,7 +127,7 @@ def from_service_account_info(cls, info: dict, *args, **kwargs): @classmethod def from_service_account_file(cls, filename: str, *args, **kwargs): """Creates an instance of this client using the provided credentials - file. + file. Args: filename (str): The path to the service account private key json @@ -147,21 +146,22 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> AssetServiceTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - AssetServiceTransport: The transport used by the client instance. + AssetServiceTransport: The transport used by the client + instance. """ return self._transport @staticmethod def asset_path() -> str: - """Return a fully-qualified asset string.""" + """Returns a fully-qualified asset string.""" return "*".format() @staticmethod def common_billing_account_path(billing_account: str,) -> str: - """Return a fully-qualified billing_account string.""" + """Returns a fully-qualified billing_account string.""" return "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -174,7 +174,7 @@ def parse_common_billing_account_path(path: str) -> Dict[str, str]: @staticmethod def common_folder_path(folder: str,) -> str: - """Return a fully-qualified folder string.""" + """Returns a fully-qualified folder string.""" return "folders/{folder}".format(folder=folder,) @staticmethod @@ -185,7 +185,7 @@ def parse_common_folder_path(path: str) -> Dict[str, str]: @staticmethod def common_organization_path(organization: str,) -> str: - """Return a fully-qualified organization string.""" + """Returns a fully-qualified organization string.""" return "organizations/{organization}".format(organization=organization,) @staticmethod @@ -196,7 +196,7 @@ def parse_common_organization_path(path: str) -> Dict[str, str]: @staticmethod def common_project_path(project: str,) -> str: - """Return a fully-qualified project string.""" + """Returns a fully-qualified project string.""" return "projects/{project}".format(project=project,) @staticmethod @@ -207,7 +207,7 @@ def parse_common_project_path(path: str) -> Dict[str, str]: @staticmethod def common_location_path(project: str, location: str,) -> str: - """Return a fully-qualified location string.""" + """Returns a fully-qualified location string.""" return "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -221,12 +221,12 @@ def parse_common_location_path(path: str) -> Dict[str, str]: def __init__( self, *, - credentials: Optional[credentials.Credentials] = None, + credentials: Optional[ga_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. + """Instantiates the asset service client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -281,9 +281,10 @@ def __init__( client_cert_source_func = client_options.client_cert_source else: is_mtls = mtls.has_default_client_cert_source() - client_cert_source_func = ( - mtls.default_client_cert_source() if is_mtls else None - ) + if is_mtls: + client_cert_source_func = mtls.default_client_cert_source() + else: + client_cert_source_func = None # Figure out which api endpoint to use. if client_options.api_endpoint is not None: @@ -295,12 +296,14 @@ def __init__( 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 - ) + if is_mtls: + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = self.DEFAULT_ENDPOINT else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted " + "values: never, auto, always" ) # Save or instantiate the transport. @@ -315,8 +318,8 @@ def __init__( ) if client_options.scopes: raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." + "When providing a transport instance, provide its scopes " + "directly." ) self._transport = transport else: @@ -345,7 +348,6 @@ def list_assets( Args: request (google.cloud.asset_v1p5beta1.types.ListAssetsRequest): The request object. ListAssets request. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -361,7 +363,6 @@ def list_assets( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a asset_service.ListAssetsRequest. # There's no risk of modifying the input as we've already verified diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py b/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py index ddd260b9..497095bf 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/pagers.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from typing import ( Any, AsyncIterable, @@ -118,7 +116,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and 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 c077c192..9158fc25 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from collections import OrderedDict from typing import Dict, Type diff --git a/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py b/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py index 0eedae11..1c877d77 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/base.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,20 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import abc -import typing +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union +import packaging.version import pkg_resources -from google import auth # type: ignore -from google.api_core import exceptions # type: ignore +import google.auth # type: ignore +import google.api_core # type: ignore +from google.api_core import exceptions as core_exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.asset_v1p5beta1.types import asset_service - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-asset",).version, @@ -35,27 +34,41 @@ except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +try: + # google.auth.__version__ was added in 1.26.0 + _GOOGLE_AUTH_VERSION = google.auth.__version__ +except AttributeError: + try: # try pkg_resources if it is available + _GOOGLE_AUTH_VERSION = pkg_resources.get_distribution("google-auth").version + except pkg_resources.DistributionNotFound: # pragma: NO COVER + _GOOGLE_AUTH_VERSION = None + +_API_CORE_VERSION = google.api_core.__version__ + class AssetServiceTransport(abc.ABC): """Abstract transport class for AssetService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudasset.googleapis.com" + 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, + host: str = DEFAULT_HOST, + credentials: ga_credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: 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. + 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 @@ -64,7 +77,7 @@ def __init__( 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. + scopes (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): @@ -78,29 +91,76 @@ def __init__( host += ":443" self._host = host + scopes_kwargs = self._get_scopes_kwargs(self._host, scopes) + # Save the scopes. self._scopes = scopes or self.AUTH_SCOPES # If no credentials are provided, then determine the appropriate # defaults. if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( + raise core_exceptions.DuplicateCredentialArgs( "'credentials_file' and 'credentials' are mutually exclusive" ) if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id ) elif credentials is None: - credentials, _ = auth.default( - scopes=self._scopes, quota_project_id=quota_project_id + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id ) # Save the credentials. self._credentials = credentials + # TODO(busunkim): These two class methods are in the base transport + # to avoid duplicating code across the transport classes. These functions + # should be deleted once the minimum required versions of google-api-core + # and google-auth are increased. + + # TODO: Remove this function once google-auth >= 1.25.0 is required + @classmethod + def _get_scopes_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Optional[Sequence[str]]]: + """Returns scopes kwargs to pass to google-auth methods depending on the google-auth version""" + + scopes_kwargs = {} + + if _GOOGLE_AUTH_VERSION and ( + packaging.version.parse(_GOOGLE_AUTH_VERSION) + >= packaging.version.parse("1.25.0") + ): + scopes_kwargs = {"scopes": scopes, "default_scopes": cls.AUTH_SCOPES} + else: + scopes_kwargs = {"scopes": scopes or cls.AUTH_SCOPES} + + return scopes_kwargs + + # TODO: Remove this function once google-api-core >= 1.26.0 is required + @classmethod + def _get_self_signed_jwt_kwargs( + cls, host: str, scopes: Optional[Sequence[str]] + ) -> Dict[str, Union[Optional[Sequence[str]], str]]: + """Returns kwargs to pass to grpc_helpers.create_channel depending on the google-api-core version""" + + self_signed_jwt_kwargs: Dict[str, Union[Optional[Sequence[str]], str]] = {} + + if _API_CORE_VERSION and ( + packaging.version.parse(_API_CORE_VERSION) + >= packaging.version.parse("1.26.0") + ): + self_signed_jwt_kwargs["default_scopes"] = cls.AUTH_SCOPES + self_signed_jwt_kwargs["scopes"] = scopes + self_signed_jwt_kwargs["default_host"] = cls.DEFAULT_HOST + else: + self_signed_jwt_kwargs["scopes"] = scopes or cls.AUTH_SCOPES + + return self_signed_jwt_kwargs + def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { @@ -111,7 +171,8 @@ def _prep_wrapped_messages(self, client_info): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -123,11 +184,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_assets( self, - ) -> typing.Callable[ + ) -> Callable[ [asset_service.ListAssetsRequest], - typing.Union[ + Union[ asset_service.ListAssetsResponse, - typing.Awaitable[asset_service.ListAssetsResponse], + Awaitable[asset_service.ListAssetsResponse], ], ]: raise NotImplementedError() 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 b135deaa..409c71bd 100644 --- a/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py +++ b/google/cloud/asset_v1p5beta1/services/asset_service/transports/grpc.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,20 +13,18 @@ # 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 typing import Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import grpc_helpers # type: ignore from google.api_core import gapic_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from google.cloud.asset_v1p5beta1.types import asset_service - from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO @@ -50,7 +47,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Sequence[str] = None, channel: grpc.Channel = None, @@ -64,7 +61,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -174,7 +172,7 @@ def __init__( def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: str = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -205,13 +203,15 @@ def create_channel( google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` and ``credentials_file`` are passed. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) 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 2df9b35f..41d9136c 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 @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,21 +13,19 @@ # 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union from google.api_core import gapic_v1 # type: ignore from google.api_core import grpc_helpers_async # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +import packaging.version import grpc # type: ignore from grpc.experimental import aio # type: ignore from google.cloud.asset_v1p5beta1.types import asset_service - from .base import AssetServiceTransport, DEFAULT_CLIENT_INFO from .grpc import AssetServiceGrpcTransport @@ -53,7 +50,7 @@ class AssetServiceGrpcAsyncIOTransport(AssetServiceTransport): def create_channel( cls, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -80,13 +77,15 @@ def create_channel( Returns: aio.Channel: A gRPC AsyncIO channel object. """ - scopes = scopes or cls.AUTH_SCOPES + + self_signed_jwt_kwargs = cls._get_self_signed_jwt_kwargs(host, scopes) + return grpc_helpers_async.create_channel( host, credentials=credentials, credentials_file=credentials_file, - scopes=scopes, quota_project_id=quota_project_id, + **self_signed_jwt_kwargs, **kwargs, ) @@ -94,7 +93,7 @@ def __init__( self, *, host: str = "cloudasset.googleapis.com", - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, channel: aio.Channel = None, @@ -108,7 +107,8 @@ def __init__( """Instantiate the transport. Args: - host (Optional[str]): The hostname to connect to. + 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 @@ -166,7 +166,6 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel self._ssl_channel_credentials = None - else: if api_mtls_endpoint: host = api_mtls_endpoint diff --git a/google/cloud/asset_v1p5beta1/types/__init__.py b/google/cloud/asset_v1p5beta1/types/__init__.py index 656ff62a..d26c148b 100644 --- a/google/cloud/asset_v1p5beta1/types/__init__.py +++ b/google/cloud/asset_v1p5beta1/types/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,7 +13,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - from .asset_service import ( ListAssetsRequest, ListAssetsResponse, diff --git a/google/cloud/asset_v1p5beta1/types/asset_service.py b/google/cloud/asset_v1p5beta1/types/asset_service.py index 6dc79759..7b1ce49e 100644 --- a/google/cloud/asset_v1p5beta1/types/asset_service.py +++ b/google/cloud/asset_v1p5beta1/types/asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,12 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - from google.cloud.asset_v1p5beta1.types import assets as gca_assets -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore __protobuf__ = proto.module( @@ -39,7 +36,6 @@ class ContentType(proto.Enum): class ListAssetsRequest(proto.Message): r"""ListAssets request. - Attributes: parent (str): Required. Name of the organization or project the assets @@ -77,22 +73,16 @@ class ListAssetsRequest(proto.Message): of assets. """ - 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) - + parent = proto.Field(proto.STRING, number=1,) + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + asset_types = proto.RepeatedField(proto.STRING, number=3,) content_type = proto.Field(proto.ENUM, number=4, enum="ContentType",) - - page_size = proto.Field(proto.INT32, number=5) - - page_token = proto.Field(proto.STRING, number=6) + page_size = proto.Field(proto.INT32, number=5,) + page_token = proto.Field(proto.STRING, number=6,) class ListAssetsResponse(proto.Message): r"""ListAssets response. - Attributes: read_time (google.protobuf.timestamp_pb2.Timestamp): Time the snapshot was taken. @@ -107,11 +97,9 @@ class ListAssetsResponse(proto.Message): def raw_page(self): return self - read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - + read_time = proto.Field(proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp,) assets = proto.RepeatedField(proto.MESSAGE, number=2, message=gca_assets.Asset,) - - next_page_token = proto.Field(proto.STRING, number=3) + next_page_token = proto.Field(proto.STRING, number=3,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/asset_v1p5beta1/types/assets.py b/google/cloud/asset_v1p5beta1/types/assets.py index 8f62070c..79d70d6d 100644 --- a/google/cloud/asset_v1p5beta1/types/assets.py +++ b/google/cloud/asset_v1p5beta1/types/assets.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,16 +13,14 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import proto # type: ignore - -from google.cloud.orgpolicy.v1 import orgpolicy_pb2 as orgpolicy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.identity.accesscontextmanager.v1 import access_level_pb2 as giav_access_level # type: ignore -from google.identity.accesscontextmanager.v1 import access_policy_pb2 as giav_access_policy # type: ignore -from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 as giav_service_perimeter # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore +from google.cloud.orgpolicy.v1 import orgpolicy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_level_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import access_policy_pb2 # type: ignore +from google.identity.accesscontextmanager.v1 import service_perimeter_pb2 # type: ignore +from google.protobuf import struct_pb2 # type: ignore __protobuf__ = proto.module( @@ -74,43 +71,36 @@ class Asset(proto.Message): "organizations/1234"] """ - name = proto.Field(proto.STRING, number=1) - - asset_type = proto.Field(proto.STRING, number=2) - + 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,) - - org_policy = proto.RepeatedField(proto.MESSAGE, number=6, message=orgpolicy.Policy,) - + iam_policy = proto.Field(proto.MESSAGE, number=4, message=policy_pb2.Policy,) + org_policy = proto.RepeatedField( + proto.MESSAGE, number=6, message=orgpolicy_pb2.Policy, + ) access_policy = proto.Field( proto.MESSAGE, number=7, oneof="access_context_policy", - message=giav_access_policy.AccessPolicy, + message=access_policy_pb2.AccessPolicy, ) - access_level = proto.Field( proto.MESSAGE, number=8, oneof="access_context_policy", - message=giav_access_level.AccessLevel, + message=access_level_pb2.AccessLevel, ) - service_perimeter = proto.Field( proto.MESSAGE, number=9, oneof="access_context_policy", - message=giav_service_perimeter.ServicePerimeter, + message=service_perimeter_pb2.ServicePerimeter, ) - - ancestors = proto.RepeatedField(proto.STRING, number=10) + ancestors = proto.RepeatedField(proto.STRING, number=10,) class Resource(proto.Message): r"""Representation of a cloud resource. - Attributes: version (str): The API version. Example: "v1". @@ -151,17 +141,12 @@ class Resource(proto.Message): 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,) + 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_pb2.Struct,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/owlbot.py b/owlbot.py index 78147271..4dddc69a 100644 --- a/owlbot.py +++ b/owlbot.py @@ -28,16 +28,22 @@ # Fix import of 'osconfig' type s.replace( library / f"google/cloud/asset_{library.name}/types/assets.py", - f"from google\.cloud\.osconfig\.{library.name} import inventory_pb2 as inventory", + f"from google\.cloud\.osconfig\.{library.name} import inventory_pb2", f"from google.cloud.osconfig_{library.name} import Inventory" ) s.replace( library / f"google/cloud/asset_{library.name}/types/assets.py", - "message=inventory\.Inventory,", + "message=inventory_pb2\.Inventory,", "message=Inventory," ) + s.replace( + library / f"google/cloud/asset_{library.name}/types/assets.py", + "google\.cloud\.osconfig\.v1\.inventory_pb2\.Inventory", + "google.cloud.osconfig_v1.Inventory" + ) + # Remove broken `parse_asset_path` method # The resource pattern is '*' which breaks the regex match s.replace( @@ -86,4 +92,4 @@ def parse_asset_path.*?@staticmethod""", # https://github.com/googleapis/gapic-generator-python/issues/525 s.replace("noxfile.py", '[\"\']-W[\"\']', '# "-W"') -s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file +s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/scripts/fixup_asset_v1_keywords.py b/scripts/fixup_asset_v1_keywords.py index b6738f86..b0cdcf3f 100644 --- a/scripts/fixup_asset_v1_keywords.py +++ b/scripts/fixup_asset_v1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,18 +39,17 @@ def partition( class assetCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_iam_policy': ('analysis_query', 'execution_timeout', ), - 'analyze_iam_policy_longrunning': ('analysis_query', 'output_config', ), - 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', ), - 'create_feed': ('parent', 'feed_id', 'feed', ), - 'delete_feed': ('name', ), - 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', ), - 'get_feed': ('name', ), - 'list_feeds': ('parent', ), - 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), - 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), - 'update_feed': ('feed', 'update_mask', ), - + 'analyze_iam_policy': ('analysis_query', 'execution_timeout', ), + 'analyze_iam_policy_longrunning': ('analysis_query', 'output_config', ), + 'batch_get_assets_history': ('parent', 'asset_names', 'content_type', 'read_time_window', ), + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'delete_feed': ('name', ), + 'export_assets': ('parent', 'output_config', 'read_time', 'asset_types', 'content_type', ), + 'get_feed': ('name', ), + 'list_feeds': ('parent', ), + 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), + 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), + 'update_feed': ('feed', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -83,7 +80,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_asset_v1p1beta1_keywords.py b/scripts/fixup_asset_v1p1beta1_keywords.py index 125f85e7..dc77c201 100644 --- a/scripts/fixup_asset_v1p1beta1_keywords.py +++ b/scripts/fixup_asset_v1p1beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,9 +39,8 @@ def partition( class assetCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), - 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), - + 'search_all_iam_policies': ('scope', 'query', 'page_size', 'page_token', ), + 'search_all_resources': ('scope', 'query', 'asset_types', 'page_size', 'page_token', 'order_by', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -74,7 +71,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_asset_v1p2beta1_keywords.py b/scripts/fixup_asset_v1p2beta1_keywords.py index d2e7d9a4..cb36113c 100644 --- a/scripts/fixup_asset_v1p2beta1_keywords.py +++ b/scripts/fixup_asset_v1p2beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,12 +39,11 @@ def partition( class assetCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_feed': ('parent', 'feed_id', 'feed', ), - 'delete_feed': ('name', ), - 'get_feed': ('name', ), - 'list_feeds': ('parent', ), - 'update_feed': ('feed', 'update_mask', ), - + 'create_feed': ('parent', 'feed_id', 'feed', ), + 'delete_feed': ('name', ), + 'get_feed': ('name', ), + 'list_feeds': ('parent', ), + 'update_feed': ('feed', 'update_mask', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -77,7 +74,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_asset_v1p4beta1_keywords.py b/scripts/fixup_asset_v1p4beta1_keywords.py index fa32405d..b3ee3fcb 100644 --- a/scripts/fixup_asset_v1p4beta1_keywords.py +++ b/scripts/fixup_asset_v1p4beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,9 +39,8 @@ def partition( class assetCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'analyze_iam_policy': ('analysis_query', 'options', ), - 'export_iam_policy_analysis': ('analysis_query', 'output_config', 'options', ), - + 'analyze_iam_policy': ('analysis_query', 'options', ), + 'export_iam_policy_analysis': ('analysis_query', 'output_config', 'options', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -74,7 +71,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/scripts/fixup_asset_v1p5beta1_keywords.py b/scripts/fixup_asset_v1p5beta1_keywords.py index 4d718d46..9eb4f0f8 100644 --- a/scripts/fixup_asset_v1p5beta1_keywords.py +++ b/scripts/fixup_asset_v1p5beta1_keywords.py @@ -1,6 +1,5 @@ #! /usr/bin/env python3 # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,7 +14,6 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import argparse import os import libcst as cst @@ -41,8 +39,7 @@ def partition( class assetCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), - + 'list_assets': ('parent', 'read_time', 'asset_types', 'content_type', 'page_size', 'page_token', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: @@ -73,7 +70,7 @@ def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: value=cst.Dict([ cst.DictElement( cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) +cst.Element(value=arg.value) ) # Note: the args + kwargs looks silly, but keep in mind that # the control parameters had to be stripped out, and that diff --git a/setup.py b/setup.py index 60ffa0f1..731f07b1 100644 --- a/setup.py +++ b/setup.py @@ -34,6 +34,7 @@ "google-cloud-org-policy>=0.1.2, <0.4.0", "google-cloud-os-config >= 1.0.0, <2.0.0dev", "proto-plus >= 1.10.0", + "packaging >= 14.3", ] extras = {"libcst": "libcst >= 0.2.5"} diff --git a/testing/constraints-3.6.txt b/testing/constraints-3.6.txt index 206057ed..1d8ebd1b 100644 --- a/testing/constraints-3.6.txt +++ b/testing/constraints-3.6.txt @@ -12,3 +12,5 @@ google-cloud-org-policy==0.1.2 google-cloud-os-config==1.0.0 proto-plus==1.10.0 libcst==0.2.5 +packaging==14.3 +google-auth==1.24.0 # TODO: remove when google-auth>=1.25.0 is required transitively through google-api-core diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/gapic/__init__.py b/tests/unit/gapic/__init__.py new file mode 100644 index 00000000..4de65971 --- /dev/null +++ b/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- 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/tests/unit/gapic/asset_v1/__init__.py b/tests/unit/gapic/asset_v1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/asset_v1/__init__.py +++ b/tests/unit/gapic/asset_v1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/asset_v1/test_asset_service.py b/tests/unit/gapic/asset_v1/test_asset_service.py index ed73b1f9..87fadf1a 100644 --- a/tests/unit/gapic/asset_v1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1/test_asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,29 +23,59 @@ 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 exceptions as core_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 import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.asset_v1.services.asset_service import AssetServiceAsyncClient from google.cloud.asset_v1.services.asset_service import AssetServiceClient from google.cloud.asset_v1.services.asset_service import pagers from google.cloud.asset_v1.services.asset_service import transports +from google.cloud.asset_v1.services.asset_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.asset_v1.services.asset_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.asset_v1.types import asset_service from google.cloud.asset_v1.types import assets from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import expr_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -92,7 +121,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -107,7 +136,7 @@ def test_asset_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -158,7 +187,7 @@ def test_asset_service_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -442,7 +471,7 @@ def test_export_assets( transport: str = "grpc", request_type=asset_service.ExportAssetsRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -453,13 +482,11 @@ def test_export_assets( 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. @@ -474,7 +501,7 @@ def test_export_assets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -482,7 +509,6 @@ def test_export_assets_empty_call(): client.export_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ExportAssetsRequest() @@ -491,7 +517,7 @@ async def test_export_assets_async( transport: str = "grpc_asyncio", request_type=asset_service.ExportAssetsRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -504,13 +530,11 @@ async def test_export_assets_async( 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. @@ -523,17 +547,17 @@ async def test_export_assets_async_from_dict(): def test_export_assets_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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. @@ -548,11 +572,12 @@ def test_export_assets_field_headers(): @pytest.mark.asyncio async def test_export_assets_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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. @@ -560,7 +585,6 @@ async def test_export_assets_field_headers_async(): 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. @@ -577,7 +601,7 @@ def test_batch_get_assets_history( transport: str = "grpc", request_type=asset_service.BatchGetAssetsHistoryRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -590,17 +614,14 @@ def test_batch_get_assets_history( ) 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) @@ -612,7 +633,7 @@ def test_batch_get_assets_history_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -622,7 +643,6 @@ def test_batch_get_assets_history_empty_call(): client.batch_get_assets_history() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.BatchGetAssetsHistoryRequest() @@ -632,7 +652,7 @@ async def test_batch_get_assets_history_async( request_type=asset_service.BatchGetAssetsHistoryRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -647,13 +667,11 @@ async def test_batch_get_assets_history_async( 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. @@ -666,11 +684,12 @@ async def test_batch_get_assets_history_async_from_dict(): def test_batch_get_assets_history_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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. @@ -678,7 +697,6 @@ def test_batch_get_assets_history_field_headers(): 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. @@ -693,11 +711,12 @@ def test_batch_get_assets_history_field_headers(): @pytest.mark.asyncio async def test_batch_get_assets_history_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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. @@ -707,7 +726,6 @@ async def test_batch_get_assets_history_field_headers_async(): 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. @@ -724,7 +742,7 @@ def test_create_feed( transport: str = "grpc", request_type=asset_service.CreateFeedRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -740,25 +758,18 @@ def test_create_feed( asset_types=["asset_types_value"], content_type=asset_service.ContentType.RESOURCE, ) - response = client.create_feed(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.CreateFeedRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -770,7 +781,7 @@ def test_create_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -778,7 +789,6 @@ def test_create_feed_empty_call(): client.create_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() @@ -787,7 +797,7 @@ async def test_create_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.CreateFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -805,24 +815,18 @@ async def test_create_feed_async( content_type=asset_service.ContentType.RESOURCE, ) ) - response = await client.create_feed(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.CreateFeedRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -832,17 +836,17 @@ async def test_create_feed_async_from_dict(): def test_create_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.CreateFeedRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: call.return_value = asset_service.Feed() - client.create_feed(request) # Establish that the underlying gRPC stub method was called. @@ -857,17 +861,17 @@ def test_create_feed_field_headers(): @pytest.mark.asyncio async def test_create_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.CreateFeedRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.create_feed(request) # Establish that the underlying gRPC stub method was called. @@ -881,13 +885,12 @@ async def test_create_feed_field_headers_async(): def test_create_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_feed(parent="parent_value",) @@ -896,12 +899,11 @@ def test_create_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_create_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -913,7 +915,7 @@ def test_create_feed_flattened_error(): @pytest.mark.asyncio async def test_create_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: @@ -929,13 +931,12 @@ async def test_create_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_create_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -947,7 +948,7 @@ async def test_create_feed_flattened_error_async(): def test_get_feed(transport: str = "grpc", request_type=asset_service.GetFeedRequest): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -963,25 +964,18 @@ def test_get_feed(transport: str = "grpc", request_type=asset_service.GetFeedReq asset_types=["asset_types_value"], content_type=asset_service.ContentType.RESOURCE, ) - response = client.get_feed(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.GetFeedRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -993,7 +987,7 @@ def test_get_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1001,7 +995,6 @@ def test_get_feed_empty_call(): client.get_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() @@ -1010,7 +1003,7 @@ async def test_get_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.GetFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1028,24 +1021,18 @@ async def test_get_feed_async( content_type=asset_service.ContentType.RESOURCE, ) ) - response = await client.get_feed(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.GetFeedRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -1055,17 +1042,17 @@ async def test_get_feed_async_from_dict(): def test_get_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.GetFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: call.return_value = asset_service.Feed() - client.get_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1080,17 +1067,17 @@ def test_get_feed_field_headers(): @pytest.mark.asyncio async def test_get_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.GetFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.get_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1104,13 +1091,12 @@ async def test_get_feed_field_headers_async(): def test_get_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_feed(name="name_value",) @@ -1119,12 +1105,11 @@ def test_get_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1136,7 +1121,7 @@ def test_get_feed_flattened_error(): @pytest.mark.asyncio async def test_get_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: @@ -1152,13 +1137,12 @@ async def test_get_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1172,7 +1156,7 @@ def test_list_feeds( transport: str = "grpc", request_type=asset_service.ListFeedsRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1183,17 +1167,14 @@ def test_list_feeds( with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.ListFeedsResponse() - response = client.list_feeds(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.ListFeedsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) @@ -1205,7 +1186,7 @@ def test_list_feeds_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1213,7 +1194,6 @@ def test_list_feeds_empty_call(): client.list_feeds() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() @@ -1222,7 +1202,7 @@ async def test_list_feeds_async( transport: str = "grpc_asyncio", request_type=asset_service.ListFeedsRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1235,13 +1215,11 @@ async def test_list_feeds_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.ListFeedsResponse() ) - response = await client.list_feeds(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.ListFeedsRequest() # Establish that the response is the type that we expect. @@ -1254,17 +1232,17 @@ async def test_list_feeds_async_from_dict(): def test_list_feeds_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.ListFeedsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: call.return_value = asset_service.ListFeedsResponse() - client.list_feeds(request) # Establish that the underlying gRPC stub method was called. @@ -1279,11 +1257,12 @@ def test_list_feeds_field_headers(): @pytest.mark.asyncio async def test_list_feeds_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.ListFeedsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1291,7 +1270,6 @@ async def test_list_feeds_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.ListFeedsResponse() ) - await client.list_feeds(request) # Establish that the underlying gRPC stub method was called. @@ -1305,13 +1283,12 @@ async def test_list_feeds_field_headers_async(): def test_list_feeds_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.ListFeedsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_feeds(parent="parent_value",) @@ -1320,12 +1297,11 @@ def test_list_feeds_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_feeds_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1337,7 +1313,7 @@ def test_list_feeds_flattened_error(): @pytest.mark.asyncio async def test_list_feeds_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: @@ -1355,13 +1331,12 @@ async def test_list_feeds_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_feeds_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1375,7 +1350,7 @@ def test_update_feed( transport: str = "grpc", request_type=asset_service.UpdateFeedRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1391,25 +1366,18 @@ def test_update_feed( asset_types=["asset_types_value"], content_type=asset_service.ContentType.RESOURCE, ) - response = client.update_feed(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.UpdateFeedRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -1421,7 +1389,7 @@ def test_update_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1429,7 +1397,6 @@ def test_update_feed_empty_call(): client.update_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() @@ -1438,7 +1405,7 @@ async def test_update_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.UpdateFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1456,24 +1423,18 @@ async def test_update_feed_async( content_type=asset_service.ContentType.RESOURCE, ) ) - response = await client.update_feed(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.UpdateFeedRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -1483,17 +1444,17 @@ async def test_update_feed_async_from_dict(): def test_update_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.UpdateFeedRequest() + request.feed.name = "feed.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: call.return_value = asset_service.Feed() - client.update_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1508,17 +1469,17 @@ def test_update_feed_field_headers(): @pytest.mark.asyncio async def test_update_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.UpdateFeedRequest() + request.feed.name = "feed.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.update_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1532,13 +1493,12 @@ async def test_update_feed_field_headers_async(): def test_update_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_feed(feed=asset_service.Feed(name="name_value"),) @@ -1547,12 +1507,11 @@ def test_update_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].feed == asset_service.Feed(name="name_value") def test_update_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1565,7 +1524,7 @@ def test_update_feed_flattened_error(): @pytest.mark.asyncio async def test_update_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: @@ -1581,13 +1540,12 @@ async def test_update_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].feed == asset_service.Feed(name="name_value") @pytest.mark.asyncio async def test_update_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1602,7 +1560,7 @@ def test_delete_feed( transport: str = "grpc", request_type=asset_service.DeleteFeedRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1613,13 +1571,11 @@ def test_delete_feed( with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_feed(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.DeleteFeedRequest() # Establish that the response is the type that we expect. @@ -1634,7 +1590,7 @@ def test_delete_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1642,7 +1598,6 @@ def test_delete_feed_empty_call(): client.delete_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() @@ -1651,7 +1606,7 @@ async def test_delete_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.DeleteFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1662,13 +1617,11 @@ async def test_delete_feed_async( with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_feed(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.DeleteFeedRequest() # Establish that the response is the type that we expect. @@ -1681,17 +1634,17 @@ async def test_delete_feed_async_from_dict(): def test_delete_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.DeleteFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: call.return_value = None - client.delete_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1706,17 +1659,17 @@ def test_delete_feed_field_headers(): @pytest.mark.asyncio async def test_delete_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.DeleteFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1730,13 +1683,12 @@ async def test_delete_feed_field_headers_async(): def test_delete_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_feed(name="name_value",) @@ -1745,12 +1697,11 @@ def test_delete_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1762,7 +1713,7 @@ def test_delete_feed_flattened_error(): @pytest.mark.asyncio async def test_delete_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: @@ -1778,13 +1729,12 @@ async def test_delete_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1798,7 +1748,7 @@ def test_search_all_resources( transport: str = "grpc", request_type=asset_service.SearchAllResourcesRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1813,19 +1763,15 @@ def test_search_all_resources( call.return_value = asset_service.SearchAllResourcesResponse( next_page_token="next_page_token_value", ) - response = client.search_all_resources(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.SearchAllResourcesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesPager) - assert response.next_page_token == "next_page_token_value" @@ -1837,7 +1783,7 @@ def test_search_all_resources_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1847,7 +1793,6 @@ def test_search_all_resources_empty_call(): client.search_all_resources() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() @@ -1857,7 +1802,7 @@ async def test_search_all_resources_async( request_type=asset_service.SearchAllResourcesRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1874,18 +1819,15 @@ async def test_search_all_resources_async( next_page_token="next_page_token_value", ) ) - response = await client.search_all_resources(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.SearchAllResourcesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAllResourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1895,11 +1837,12 @@ async def test_search_all_resources_async_from_dict(): def test_search_all_resources_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.SearchAllResourcesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1907,7 +1850,6 @@ def test_search_all_resources_field_headers(): type(client.transport.search_all_resources), "__call__" ) as call: call.return_value = asset_service.SearchAllResourcesResponse() - client.search_all_resources(request) # Establish that the underlying gRPC stub method was called. @@ -1922,11 +1864,12 @@ def test_search_all_resources_field_headers(): @pytest.mark.asyncio async def test_search_all_resources_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.SearchAllResourcesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1936,7 +1879,6 @@ async def test_search_all_resources_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.SearchAllResourcesResponse() ) - await client.search_all_resources(request) # Establish that the underlying gRPC stub method was called. @@ -1950,7 +1892,7 @@ async def test_search_all_resources_field_headers_async(): def test_search_all_resources_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1958,7 +1900,6 @@ def test_search_all_resources_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = asset_service.SearchAllResourcesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_all_resources( @@ -1969,16 +1910,13 @@ def test_search_all_resources_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" - assert args[0].asset_types == ["asset_types_value"] def test_search_all_resources_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1993,7 +1931,7 @@ def test_search_all_resources_flattened_error(): @pytest.mark.asyncio async def test_search_all_resources_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2015,17 +1953,14 @@ async def test_search_all_resources_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" - assert args[0].asset_types == ["asset_types_value"] @pytest.mark.asyncio async def test_search_all_resources_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2039,7 +1974,7 @@ async def test_search_all_resources_flattened_error_async(): def test_search_all_resources_pager(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2081,7 +2016,7 @@ def test_search_all_resources_pager(): def test_search_all_resources_pages(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2115,7 +2050,7 @@ def test_search_all_resources_pages(): @pytest.mark.asyncio async def test_search_all_resources_async_pager(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2156,7 +2091,7 @@ async def test_search_all_resources_async_pager(): @pytest.mark.asyncio async def test_search_all_resources_async_pages(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2196,7 +2131,7 @@ def test_search_all_iam_policies( transport: str = "grpc", request_type=asset_service.SearchAllIamPoliciesRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2211,19 +2146,15 @@ def test_search_all_iam_policies( call.return_value = asset_service.SearchAllIamPoliciesResponse( next_page_token="next_page_token_value", ) - response = client.search_all_iam_policies(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.SearchAllIamPoliciesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesPager) - assert response.next_page_token == "next_page_token_value" @@ -2235,7 +2166,7 @@ def test_search_all_iam_policies_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2245,7 +2176,6 @@ def test_search_all_iam_policies_empty_call(): client.search_all_iam_policies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() @@ -2255,7 +2185,7 @@ async def test_search_all_iam_policies_async( request_type=asset_service.SearchAllIamPoliciesRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2272,18 +2202,15 @@ async def test_search_all_iam_policies_async( next_page_token="next_page_token_value", ) ) - response = await client.search_all_iam_policies(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.SearchAllIamPoliciesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -2293,11 +2220,12 @@ async def test_search_all_iam_policies_async_from_dict(): def test_search_all_iam_policies_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.SearchAllIamPoliciesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2305,7 +2233,6 @@ def test_search_all_iam_policies_field_headers(): type(client.transport.search_all_iam_policies), "__call__" ) as call: call.return_value = asset_service.SearchAllIamPoliciesResponse() - client.search_all_iam_policies(request) # Establish that the underlying gRPC stub method was called. @@ -2320,11 +2247,12 @@ def test_search_all_iam_policies_field_headers(): @pytest.mark.asyncio async def test_search_all_iam_policies_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.SearchAllIamPoliciesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2334,7 +2262,6 @@ async def test_search_all_iam_policies_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.SearchAllIamPoliciesResponse() ) - await client.search_all_iam_policies(request) # Establish that the underlying gRPC stub method was called. @@ -2348,7 +2275,7 @@ async def test_search_all_iam_policies_field_headers_async(): def test_search_all_iam_policies_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2356,7 +2283,6 @@ def test_search_all_iam_policies_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = asset_service.SearchAllIamPoliciesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_all_iam_policies( @@ -2367,14 +2293,12 @@ def test_search_all_iam_policies_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" def test_search_all_iam_policies_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2388,7 +2312,7 @@ def test_search_all_iam_policies_flattened_error(): @pytest.mark.asyncio async def test_search_all_iam_policies_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2410,15 +2334,13 @@ async def test_search_all_iam_policies_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" @pytest.mark.asyncio async def test_search_all_iam_policies_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2431,7 +2353,7 @@ async def test_search_all_iam_policies_flattened_error_async(): def test_search_all_iam_policies_pager(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2476,7 +2398,7 @@ def test_search_all_iam_policies_pager(): def test_search_all_iam_policies_pages(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2513,7 +2435,7 @@ def test_search_all_iam_policies_pages(): @pytest.mark.asyncio async def test_search_all_iam_policies_async_pager(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2557,7 +2479,7 @@ async def test_search_all_iam_policies_async_pager(): @pytest.mark.asyncio async def test_search_all_iam_policies_async_pages(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2600,7 +2522,7 @@ def test_analyze_iam_policy( transport: str = "grpc", request_type=asset_service.AnalyzeIamPolicyRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2613,19 +2535,15 @@ def test_analyze_iam_policy( ) as call: # Designate an appropriate return value for the call. call.return_value = asset_service.AnalyzeIamPolicyResponse(fully_explored=True,) - response = client.analyze_iam_policy(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.AnalyzeIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True @@ -2637,7 +2555,7 @@ def test_analyze_iam_policy_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2647,7 +2565,6 @@ def test_analyze_iam_policy_empty_call(): client.analyze_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyRequest() @@ -2656,7 +2573,7 @@ async def test_analyze_iam_policy_async( transport: str = "grpc_asyncio", request_type=asset_service.AnalyzeIamPolicyRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2671,18 +2588,15 @@ async def test_analyze_iam_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.AnalyzeIamPolicyResponse(fully_explored=True,) ) - response = await client.analyze_iam_policy(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.AnalyzeIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True @@ -2692,11 +2606,12 @@ async def test_analyze_iam_policy_async_from_dict(): def test_analyze_iam_policy_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.AnalyzeIamPolicyRequest() + request.analysis_query.scope = "analysis_query.scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2704,7 +2619,6 @@ def test_analyze_iam_policy_field_headers(): type(client.transport.analyze_iam_policy), "__call__" ) as call: call.return_value = asset_service.AnalyzeIamPolicyResponse() - client.analyze_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2722,11 +2636,12 @@ def test_analyze_iam_policy_field_headers(): @pytest.mark.asyncio async def test_analyze_iam_policy_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.AnalyzeIamPolicyRequest() + request.analysis_query.scope = "analysis_query.scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2736,7 +2651,6 @@ async def test_analyze_iam_policy_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.AnalyzeIamPolicyResponse() ) - await client.analyze_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2757,7 +2671,7 @@ def test_analyze_iam_policy_longrunning( request_type=asset_service.AnalyzeIamPolicyLongrunningRequest, ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2770,13 +2684,11 @@ def test_analyze_iam_policy_longrunning( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.analyze_iam_policy_longrunning(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.AnalyzeIamPolicyLongrunningRequest() # Establish that the response is the type that we expect. @@ -2791,7 +2703,7 @@ def test_analyze_iam_policy_longrunning_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2801,7 +2713,6 @@ def test_analyze_iam_policy_longrunning_empty_call(): client.analyze_iam_policy_longrunning() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyLongrunningRequest() @@ -2811,7 +2722,7 @@ async def test_analyze_iam_policy_longrunning_async( request_type=asset_service.AnalyzeIamPolicyLongrunningRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2826,13 +2737,11 @@ async def test_analyze_iam_policy_longrunning_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.analyze_iam_policy_longrunning(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.AnalyzeIamPolicyLongrunningRequest() # Establish that the response is the type that we expect. @@ -2845,11 +2754,12 @@ async def test_analyze_iam_policy_longrunning_async_from_dict(): def test_analyze_iam_policy_longrunning_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.AnalyzeIamPolicyLongrunningRequest() + request.analysis_query.scope = "analysis_query.scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2857,7 +2767,6 @@ def test_analyze_iam_policy_longrunning_field_headers(): type(client.transport.analyze_iam_policy_longrunning), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.analyze_iam_policy_longrunning(request) # Establish that the underlying gRPC stub method was called. @@ -2875,11 +2784,12 @@ def test_analyze_iam_policy_longrunning_field_headers(): @pytest.mark.asyncio async def test_analyze_iam_policy_longrunning_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.AnalyzeIamPolicyLongrunningRequest() + request.analysis_query.scope = "analysis_query.scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2889,7 +2799,6 @@ async def test_analyze_iam_policy_longrunning_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.analyze_iam_policy_longrunning(request) # Establish that the underlying gRPC stub method was called. @@ -2908,16 +2817,16 @@ async def test_analyze_iam_policy_longrunning_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -2927,7 +2836,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -2938,7 +2847,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AssetServiceClient(transport=transport) assert client.transport is transport @@ -2947,13 +2856,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -2968,23 +2877,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = AssetServiceClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -2996,7 +2905,7 @@ def test_asset_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3024,15 +2933,37 @@ def test_asset_service_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3045,19 +2976,33 @@ def test_asset_service_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.asset_v1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AssetServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -3065,26 +3010,162 @@ def test_asset_service_auth_adc(): ) -def test_asset_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_asset_service_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_asset_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], ) def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -3123,7 +3204,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_asset_service_host_no_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com" ), @@ -3133,7 +3214,7 @@ def test_asset_service_host_no_port(): def test_asset_service_host_with_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com:8000" ), @@ -3184,9 +3265,9 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -3259,7 +3340,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): def test_asset_service_grpc_lro_client(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -3272,7 +3353,7 @@ def test_asset_service_grpc_lro_client(): def test_asset_service_grpc_lro_async_client(): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -3284,7 +3365,6 @@ def test_asset_service_grpc_lro_async_client(): def test_asset_path(): - expected = "*".format() actual = AssetServiceClient.asset_path() assert expected == actual @@ -3293,7 +3373,6 @@ def test_asset_path(): def test_feed_path(): project = "squid" feed = "clam" - expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) actual = AssetServiceClient.feed_path(project, feed) assert expected == actual @@ -3313,7 +3392,6 @@ def test_parse_feed_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -3334,7 +3412,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = AssetServiceClient.common_folder_path(folder) assert expected == actual @@ -3353,7 +3430,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = AssetServiceClient.common_organization_path(organization) assert expected == actual @@ -3372,7 +3448,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = AssetServiceClient.common_project_path(project) assert expected == actual @@ -3392,7 +3467,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -3419,7 +3493,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AssetServiceTransport, "_prep_wrapped_messages" ) as prep: client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3428,6 +3502,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AssetServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/asset_v1p1beta1/__init__.py b/tests/unit/gapic/asset_v1p1beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/asset_v1p1beta1/__init__.py +++ b/tests/unit/gapic/asset_v1p1beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py index c98df4a7..86324791 100644 --- a/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p1beta1/test_asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,21 +23,51 @@ 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 exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.asset_v1p1beta1.services.asset_service import AssetServiceAsyncClient from google.cloud.asset_v1p1beta1.services.asset_service import AssetServiceClient from google.cloud.asset_v1p1beta1.services.asset_service import pagers from google.cloud.asset_v1p1beta1.services.asset_service import transports +from google.cloud.asset_v1p1beta1.services.asset_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.asset_v1p1beta1.services.asset_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.asset_v1p1beta1.types import asset_service from google.cloud.asset_v1p1beta1.types import assets from google.oauth2 import service_account +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -99,7 +128,7 @@ def test_asset_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -150,7 +179,7 @@ def test_asset_service_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -434,7 +463,7 @@ def test_search_all_resources( transport: str = "grpc", request_type=asset_service.SearchAllResourcesRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -449,19 +478,15 @@ def test_search_all_resources( call.return_value = asset_service.SearchAllResourcesResponse( next_page_token="next_page_token_value", ) - response = client.search_all_resources(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.SearchAllResourcesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllResourcesPager) - assert response.next_page_token == "next_page_token_value" @@ -473,7 +498,7 @@ def test_search_all_resources_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -483,7 +508,6 @@ def test_search_all_resources_empty_call(): client.search_all_resources() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllResourcesRequest() @@ -493,7 +517,7 @@ async def test_search_all_resources_async( request_type=asset_service.SearchAllResourcesRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -510,18 +534,15 @@ async def test_search_all_resources_async( next_page_token="next_page_token_value", ) ) - response = await client.search_all_resources(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.SearchAllResourcesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAllResourcesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -531,11 +552,12 @@ async def test_search_all_resources_async_from_dict(): def test_search_all_resources_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.SearchAllResourcesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -543,7 +565,6 @@ def test_search_all_resources_field_headers(): type(client.transport.search_all_resources), "__call__" ) as call: call.return_value = asset_service.SearchAllResourcesResponse() - client.search_all_resources(request) # Establish that the underlying gRPC stub method was called. @@ -558,11 +579,12 @@ def test_search_all_resources_field_headers(): @pytest.mark.asyncio async def test_search_all_resources_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.SearchAllResourcesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -572,7 +594,6 @@ async def test_search_all_resources_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.SearchAllResourcesResponse() ) - await client.search_all_resources(request) # Establish that the underlying gRPC stub method was called. @@ -586,7 +607,7 @@ async def test_search_all_resources_field_headers_async(): def test_search_all_resources_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -594,7 +615,6 @@ def test_search_all_resources_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = asset_service.SearchAllResourcesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_all_resources( @@ -605,16 +625,13 @@ def test_search_all_resources_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" - assert args[0].asset_types == ["asset_types_value"] def test_search_all_resources_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -629,7 +646,7 @@ def test_search_all_resources_flattened_error(): @pytest.mark.asyncio async def test_search_all_resources_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -651,17 +668,14 @@ async def test_search_all_resources_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" - assert args[0].asset_types == ["asset_types_value"] @pytest.mark.asyncio async def test_search_all_resources_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -675,7 +689,7 @@ async def test_search_all_resources_flattened_error_async(): def test_search_all_resources_pager(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -720,7 +734,7 @@ def test_search_all_resources_pager(): def test_search_all_resources_pages(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -757,7 +771,7 @@ def test_search_all_resources_pages(): @pytest.mark.asyncio async def test_search_all_resources_async_pager(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -801,7 +815,7 @@ async def test_search_all_resources_async_pager(): @pytest.mark.asyncio async def test_search_all_resources_async_pages(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -844,7 +858,7 @@ def test_search_all_iam_policies( transport: str = "grpc", request_type=asset_service.SearchAllIamPoliciesRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -859,19 +873,15 @@ def test_search_all_iam_policies( call.return_value = asset_service.SearchAllIamPoliciesResponse( next_page_token="next_page_token_value", ) - response = client.search_all_iam_policies(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.SearchAllIamPoliciesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchAllIamPoliciesPager) - assert response.next_page_token == "next_page_token_value" @@ -883,7 +893,7 @@ def test_search_all_iam_policies_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -893,7 +903,6 @@ def test_search_all_iam_policies_empty_call(): client.search_all_iam_policies() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.SearchAllIamPoliciesRequest() @@ -903,7 +912,7 @@ async def test_search_all_iam_policies_async( request_type=asset_service.SearchAllIamPoliciesRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -920,18 +929,15 @@ async def test_search_all_iam_policies_async( next_page_token="next_page_token_value", ) ) - response = await client.search_all_iam_policies(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.SearchAllIamPoliciesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.SearchAllIamPoliciesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -941,11 +947,12 @@ async def test_search_all_iam_policies_async_from_dict(): def test_search_all_iam_policies_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.SearchAllIamPoliciesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -953,7 +960,6 @@ def test_search_all_iam_policies_field_headers(): type(client.transport.search_all_iam_policies), "__call__" ) as call: call.return_value = asset_service.SearchAllIamPoliciesResponse() - client.search_all_iam_policies(request) # Establish that the underlying gRPC stub method was called. @@ -968,11 +974,12 @@ def test_search_all_iam_policies_field_headers(): @pytest.mark.asyncio async def test_search_all_iam_policies_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.SearchAllIamPoliciesRequest() + request.scope = "scope/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -982,7 +989,6 @@ async def test_search_all_iam_policies_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.SearchAllIamPoliciesResponse() ) - await client.search_all_iam_policies(request) # Establish that the underlying gRPC stub method was called. @@ -996,7 +1002,7 @@ async def test_search_all_iam_policies_field_headers_async(): def test_search_all_iam_policies_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1004,7 +1010,6 @@ def test_search_all_iam_policies_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = asset_service.SearchAllIamPoliciesResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.search_all_iam_policies( @@ -1015,14 +1020,12 @@ def test_search_all_iam_policies_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" def test_search_all_iam_policies_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1036,7 +1039,7 @@ def test_search_all_iam_policies_flattened_error(): @pytest.mark.asyncio async def test_search_all_iam_policies_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1058,15 +1061,13 @@ async def test_search_all_iam_policies_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].scope == "scope_value" - assert args[0].query == "query_value" @pytest.mark.asyncio async def test_search_all_iam_policies_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1079,7 +1080,7 @@ async def test_search_all_iam_policies_flattened_error_async(): def test_search_all_iam_policies_pager(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1124,7 +1125,7 @@ def test_search_all_iam_policies_pager(): def test_search_all_iam_policies_pages(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1161,7 +1162,7 @@ def test_search_all_iam_policies_pages(): @pytest.mark.asyncio async def test_search_all_iam_policies_async_pager(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1205,7 +1206,7 @@ async def test_search_all_iam_policies_async_pager(): @pytest.mark.asyncio async def test_search_all_iam_policies_async_pages(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1247,16 +1248,16 @@ async def test_search_all_iam_policies_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -1266,7 +1267,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -1277,7 +1278,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AssetServiceClient(transport=transport) assert client.transport is transport @@ -1286,13 +1287,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1307,23 +1308,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = AssetServiceClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1335,7 +1336,7 @@ def test_asset_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1349,15 +1350,37 @@ def test_asset_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1370,19 +1393,33 @@ def test_asset_service_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.asset_v1p1beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AssetServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1390,26 +1427,162 @@ def test_asset_service_auth_adc(): ) -def test_asset_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_asset_service_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_asset_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], ) def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1448,7 +1621,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_asset_service_host_no_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com" ), @@ -1458,7 +1631,7 @@ def test_asset_service_host_no_port(): def test_asset_service_host_with_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com:8000" ), @@ -1509,9 +1682,9 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1584,7 +1757,6 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1605,7 +1777,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AssetServiceClient.common_folder_path(folder) assert expected == actual @@ -1624,7 +1795,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AssetServiceClient.common_organization_path(organization) assert expected == actual @@ -1643,7 +1813,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AssetServiceClient.common_project_path(project) assert expected == actual @@ -1663,7 +1832,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1690,7 +1858,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AssetServiceTransport, "_prep_wrapped_messages" ) as prep: client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1699,6 +1867,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AssetServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/asset_v1p2beta1/__init__.py b/tests/unit/gapic/asset_v1p2beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/asset_v1p2beta1/__init__.py +++ b/tests/unit/gapic/asset_v1p2beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py index c787be79..8369ff2f 100644 --- a/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p2beta1/test_asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,20 +23,50 @@ 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 exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.asset_v1p2beta1.services.asset_service import AssetServiceAsyncClient from google.cloud.asset_v1p2beta1.services.asset_service import AssetServiceClient from google.cloud.asset_v1p2beta1.services.asset_service import transports +from google.cloud.asset_v1p2beta1.services.asset_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.asset_v1p2beta1.services.asset_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.asset_v1p2beta1.types import asset_service from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import field_mask_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -83,7 +112,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -98,7 +127,7 @@ def test_asset_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -149,7 +178,7 @@ def test_asset_service_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -433,7 +462,7 @@ def test_create_feed( transport: str = "grpc", request_type=asset_service.CreateFeedRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -449,25 +478,18 @@ def test_create_feed( asset_types=["asset_types_value"], content_type=asset_service.ContentType.RESOURCE, ) - response = client.create_feed(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.CreateFeedRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -479,7 +501,7 @@ def test_create_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -487,7 +509,6 @@ def test_create_feed_empty_call(): client.create_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.CreateFeedRequest() @@ -496,7 +517,7 @@ async def test_create_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.CreateFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -514,24 +535,18 @@ async def test_create_feed_async( content_type=asset_service.ContentType.RESOURCE, ) ) - response = await client.create_feed(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.CreateFeedRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -541,17 +556,17 @@ async def test_create_feed_async_from_dict(): def test_create_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.CreateFeedRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: call.return_value = asset_service.Feed() - client.create_feed(request) # Establish that the underlying gRPC stub method was called. @@ -566,17 +581,17 @@ def test_create_feed_field_headers(): @pytest.mark.asyncio async def test_create_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.CreateFeedRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.create_feed(request) # Establish that the underlying gRPC stub method was called. @@ -590,13 +605,12 @@ async def test_create_feed_field_headers_async(): def test_create_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_feed(parent="parent_value",) @@ -605,12 +619,11 @@ def test_create_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_create_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -622,7 +635,7 @@ def test_create_feed_flattened_error(): @pytest.mark.asyncio async def test_create_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_feed), "__call__") as call: @@ -638,13 +651,12 @@ async def test_create_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_create_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -656,7 +668,7 @@ async def test_create_feed_flattened_error_async(): def test_get_feed(transport: str = "grpc", request_type=asset_service.GetFeedRequest): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -672,25 +684,18 @@ def test_get_feed(transport: str = "grpc", request_type=asset_service.GetFeedReq asset_types=["asset_types_value"], content_type=asset_service.ContentType.RESOURCE, ) - response = client.get_feed(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.GetFeedRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -702,7 +707,7 @@ def test_get_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -710,7 +715,6 @@ def test_get_feed_empty_call(): client.get_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.GetFeedRequest() @@ -719,7 +723,7 @@ async def test_get_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.GetFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -737,24 +741,18 @@ async def test_get_feed_async( content_type=asset_service.ContentType.RESOURCE, ) ) - response = await client.get_feed(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.GetFeedRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -764,17 +762,17 @@ async def test_get_feed_async_from_dict(): def test_get_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.GetFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: call.return_value = asset_service.Feed() - client.get_feed(request) # Establish that the underlying gRPC stub method was called. @@ -789,17 +787,17 @@ def test_get_feed_field_headers(): @pytest.mark.asyncio async def test_get_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.GetFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.get_feed(request) # Establish that the underlying gRPC stub method was called. @@ -813,13 +811,12 @@ async def test_get_feed_field_headers_async(): def test_get_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_feed(name="name_value",) @@ -828,12 +825,11 @@ def test_get_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -845,7 +841,7 @@ def test_get_feed_flattened_error(): @pytest.mark.asyncio async def test_get_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_feed), "__call__") as call: @@ -861,13 +857,12 @@ async def test_get_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_get_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -881,7 +876,7 @@ def test_list_feeds( transport: str = "grpc", request_type=asset_service.ListFeedsRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -892,17 +887,14 @@ def test_list_feeds( with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.ListFeedsResponse() - response = client.list_feeds(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.ListFeedsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.ListFeedsResponse) @@ -914,7 +906,7 @@ def test_list_feeds_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -922,7 +914,6 @@ def test_list_feeds_empty_call(): client.list_feeds() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListFeedsRequest() @@ -931,7 +922,7 @@ async def test_list_feeds_async( transport: str = "grpc_asyncio", request_type=asset_service.ListFeedsRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -944,13 +935,11 @@ async def test_list_feeds_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.ListFeedsResponse() ) - response = await client.list_feeds(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.ListFeedsRequest() # Establish that the response is the type that we expect. @@ -963,17 +952,17 @@ async def test_list_feeds_async_from_dict(): def test_list_feeds_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.ListFeedsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: call.return_value = asset_service.ListFeedsResponse() - client.list_feeds(request) # Establish that the underlying gRPC stub method was called. @@ -988,11 +977,12 @@ def test_list_feeds_field_headers(): @pytest.mark.asyncio async def test_list_feeds_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.ListFeedsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1000,7 +990,6 @@ async def test_list_feeds_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.ListFeedsResponse() ) - await client.list_feeds(request) # Establish that the underlying gRPC stub method was called. @@ -1014,13 +1003,12 @@ async def test_list_feeds_field_headers_async(): def test_list_feeds_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.ListFeedsResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_feeds(parent="parent_value",) @@ -1029,12 +1017,11 @@ def test_list_feeds_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_feeds_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1046,7 +1033,7 @@ def test_list_feeds_flattened_error(): @pytest.mark.asyncio async def test_list_feeds_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_feeds), "__call__") as call: @@ -1064,13 +1051,12 @@ async def test_list_feeds_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" @pytest.mark.asyncio async def test_list_feeds_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1084,7 +1070,7 @@ def test_update_feed( transport: str = "grpc", request_type=asset_service.UpdateFeedRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1100,25 +1086,18 @@ def test_update_feed( asset_types=["asset_types_value"], content_type=asset_service.ContentType.RESOURCE, ) - response = client.update_feed(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.UpdateFeedRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -1130,7 +1109,7 @@ def test_update_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1138,7 +1117,6 @@ def test_update_feed_empty_call(): client.update_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.UpdateFeedRequest() @@ -1147,7 +1125,7 @@ async def test_update_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.UpdateFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1165,24 +1143,18 @@ async def test_update_feed_async( content_type=asset_service.ContentType.RESOURCE, ) ) - response = await client.update_feed(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.UpdateFeedRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.Feed) - assert response.name == "name_value" - assert response.asset_names == ["asset_names_value"] - assert response.asset_types == ["asset_types_value"] - assert response.content_type == asset_service.ContentType.RESOURCE @@ -1192,17 +1164,17 @@ async def test_update_feed_async_from_dict(): def test_update_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.UpdateFeedRequest() + request.feed.name = "feed.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: call.return_value = asset_service.Feed() - client.update_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1217,17 +1189,17 @@ def test_update_feed_field_headers(): @pytest.mark.asyncio async def test_update_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.UpdateFeedRequest() + request.feed.name = "feed.name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(asset_service.Feed()) - await client.update_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1241,13 +1213,12 @@ async def test_update_feed_field_headers_async(): def test_update_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = asset_service.Feed() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_feed(feed=asset_service.Feed(name="name_value"),) @@ -1256,12 +1227,11 @@ def test_update_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].feed == asset_service.Feed(name="name_value") def test_update_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1274,7 +1244,7 @@ def test_update_feed_flattened_error(): @pytest.mark.asyncio async def test_update_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_feed), "__call__") as call: @@ -1290,13 +1260,12 @@ async def test_update_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].feed == asset_service.Feed(name="name_value") @pytest.mark.asyncio async def test_update_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1311,7 +1280,7 @@ def test_delete_feed( transport: str = "grpc", request_type=asset_service.DeleteFeedRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1322,13 +1291,11 @@ def test_delete_feed( with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - response = client.delete_feed(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.DeleteFeedRequest() # Establish that the response is the type that we expect. @@ -1343,7 +1310,7 @@ def test_delete_feed_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1351,7 +1318,6 @@ def test_delete_feed_empty_call(): client.delete_feed() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.DeleteFeedRequest() @@ -1360,7 +1326,7 @@ async def test_delete_feed_async( transport: str = "grpc_asyncio", request_type=asset_service.DeleteFeedRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1371,13 +1337,11 @@ async def test_delete_feed_async( with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_feed(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.DeleteFeedRequest() # Establish that the response is the type that we expect. @@ -1390,17 +1354,17 @@ async def test_delete_feed_async_from_dict(): def test_delete_feed_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.DeleteFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: call.return_value = None - client.delete_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1415,17 +1379,17 @@ def test_delete_feed_field_headers(): @pytest.mark.asyncio async def test_delete_feed_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.DeleteFeedRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_feed(request) # Establish that the underlying gRPC stub method was called. @@ -1439,13 +1403,12 @@ async def test_delete_feed_field_headers_async(): def test_delete_feed_flattened(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = None - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.delete_feed(name="name_value",) @@ -1454,12 +1417,11 @@ def test_delete_feed_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_delete_feed_flattened_error(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1471,7 +1433,7 @@ def test_delete_feed_flattened_error(): @pytest.mark.asyncio async def test_delete_feed_flattened_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.delete_feed), "__call__") as call: @@ -1487,13 +1449,12 @@ async def test_delete_feed_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" @pytest.mark.asyncio async def test_delete_feed_flattened_error_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1506,16 +1467,16 @@ async def test_delete_feed_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -1525,7 +1486,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -1536,7 +1497,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AssetServiceClient(transport=transport) assert client.transport is transport @@ -1545,13 +1506,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1566,23 +1527,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = AssetServiceClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1594,7 +1555,7 @@ def test_asset_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1611,15 +1572,37 @@ def test_asset_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1632,19 +1615,33 @@ def test_asset_service_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.asset_v1p2beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AssetServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1652,26 +1649,162 @@ def test_asset_service_auth_adc(): ) -def test_asset_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_asset_service_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_asset_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], ) def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -1710,7 +1843,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_asset_service_host_no_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com" ), @@ -1720,7 +1853,7 @@ def test_asset_service_host_no_port(): def test_asset_service_host_with_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com:8000" ), @@ -1771,9 +1904,9 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1847,7 +1980,6 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): def test_feed_path(): project = "squid" feed = "clam" - expected = "projects/{project}/feeds/{feed}".format(project=project, feed=feed,) actual = AssetServiceClient.feed_path(project, feed) assert expected == actual @@ -1867,7 +1999,6 @@ def test_parse_feed_path(): def test_common_billing_account_path(): billing_account = "oyster" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1888,7 +2019,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "cuttlefish" - expected = "folders/{folder}".format(folder=folder,) actual = AssetServiceClient.common_folder_path(folder) assert expected == actual @@ -1907,7 +2037,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "winkle" - expected = "organizations/{organization}".format(organization=organization,) actual = AssetServiceClient.common_organization_path(organization) assert expected == actual @@ -1926,7 +2055,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "scallop" - expected = "projects/{project}".format(project=project,) actual = AssetServiceClient.common_project_path(project) assert expected == actual @@ -1946,7 +2074,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "squid" location = "clam" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1973,7 +2100,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AssetServiceTransport, "_prep_wrapped_messages" ) as prep: client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1982,6 +2109,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AssetServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/asset_v1p4beta1/__init__.py b/tests/unit/gapic/asset_v1p4beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/asset_v1p4beta1/__init__.py +++ b/tests/unit/gapic/asset_v1p4beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py index a53b106c..6d21bcbc 100644 --- a/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p4beta1/test_asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,25 +23,55 @@ 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 exceptions as core_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 import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceAsyncClient from google.cloud.asset_v1p4beta1.services.asset_service import AssetServiceClient from google.cloud.asset_v1p4beta1.services.asset_service import transports +from google.cloud.asset_v1p4beta1.services.asset_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.asset_v1p4beta1.services.asset_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.asset_v1p4beta1.types import asset_service from google.cloud.asset_v1p4beta1.types import assets from google.longrunning import operations_pb2 from google.oauth2 import service_account -from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import duration_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -103,7 +132,7 @@ def test_asset_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -154,7 +183,7 @@ def test_asset_service_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -438,7 +467,7 @@ def test_analyze_iam_policy( transport: str = "grpc", request_type=asset_service.AnalyzeIamPolicyRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -451,19 +480,15 @@ def test_analyze_iam_policy( ) as call: # Designate an appropriate return value for the call. call.return_value = asset_service.AnalyzeIamPolicyResponse(fully_explored=True,) - response = client.analyze_iam_policy(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.AnalyzeIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True @@ -475,7 +500,7 @@ def test_analyze_iam_policy_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -485,7 +510,6 @@ def test_analyze_iam_policy_empty_call(): client.analyze_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.AnalyzeIamPolicyRequest() @@ -494,7 +518,7 @@ async def test_analyze_iam_policy_async( transport: str = "grpc_asyncio", request_type=asset_service.AnalyzeIamPolicyRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -509,18 +533,15 @@ async def test_analyze_iam_policy_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.AnalyzeIamPolicyResponse(fully_explored=True,) ) - response = await client.analyze_iam_policy(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.AnalyzeIamPolicyRequest() # Establish that the response is the type that we expect. assert isinstance(response, asset_service.AnalyzeIamPolicyResponse) - assert response.fully_explored is True @@ -530,11 +551,12 @@ async def test_analyze_iam_policy_async_from_dict(): def test_analyze_iam_policy_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.AnalyzeIamPolicyRequest() + request.analysis_query.parent = "analysis_query.parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -542,7 +564,6 @@ def test_analyze_iam_policy_field_headers(): type(client.transport.analyze_iam_policy), "__call__" ) as call: call.return_value = asset_service.AnalyzeIamPolicyResponse() - client.analyze_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -560,11 +581,12 @@ def test_analyze_iam_policy_field_headers(): @pytest.mark.asyncio async def test_analyze_iam_policy_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.AnalyzeIamPolicyRequest() + request.analysis_query.parent = "analysis_query.parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -574,7 +596,6 @@ async def test_analyze_iam_policy_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.AnalyzeIamPolicyResponse() ) - await client.analyze_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -594,7 +615,7 @@ def test_export_iam_policy_analysis( transport: str = "grpc", request_type=asset_service.ExportIamPolicyAnalysisRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -607,13 +628,11 @@ def test_export_iam_policy_analysis( ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.export_iam_policy_analysis(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.ExportIamPolicyAnalysisRequest() # Establish that the response is the type that we expect. @@ -628,7 +647,7 @@ def test_export_iam_policy_analysis_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -638,7 +657,6 @@ def test_export_iam_policy_analysis_empty_call(): client.export_iam_policy_analysis() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ExportIamPolicyAnalysisRequest() @@ -648,7 +666,7 @@ async def test_export_iam_policy_analysis_async( request_type=asset_service.ExportIamPolicyAnalysisRequest, ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -663,13 +681,11 @@ async def test_export_iam_policy_analysis_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.export_iam_policy_analysis(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.ExportIamPolicyAnalysisRequest() # Establish that the response is the type that we expect. @@ -682,11 +698,12 @@ async def test_export_iam_policy_analysis_async_from_dict(): def test_export_iam_policy_analysis_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.ExportIamPolicyAnalysisRequest() + request.analysis_query.parent = "analysis_query.parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -694,7 +711,6 @@ def test_export_iam_policy_analysis_field_headers(): type(client.transport.export_iam_policy_analysis), "__call__" ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.export_iam_policy_analysis(request) # Establish that the underlying gRPC stub method was called. @@ -712,11 +728,12 @@ def test_export_iam_policy_analysis_field_headers(): @pytest.mark.asyncio async def test_export_iam_policy_analysis_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.ExportIamPolicyAnalysisRequest() + request.analysis_query.parent = "analysis_query.parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -726,7 +743,6 @@ async def test_export_iam_policy_analysis_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.export_iam_policy_analysis(request) # Establish that the underlying gRPC stub method was called. @@ -745,16 +761,16 @@ async def test_export_iam_policy_analysis_field_headers_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -764,7 +780,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -775,7 +791,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AssetServiceClient(transport=transport) assert client.transport is transport @@ -784,13 +800,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -805,23 +821,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = AssetServiceClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -833,7 +849,7 @@ def test_asset_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -852,15 +868,37 @@ def test_asset_service_base_transport(): transport.operations_client +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.asset_v1p4beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.asset_v1p4beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -873,19 +911,33 @@ def test_asset_service_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.asset_v1p4beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AssetServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -893,26 +945,162 @@ def test_asset_service_auth_adc(): ) -def test_asset_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_asset_service_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_asset_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], ) def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -951,7 +1139,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_asset_service_host_no_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com" ), @@ -961,7 +1149,7 @@ def test_asset_service_host_no_port(): def test_asset_service_host_with_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com:8000" ), @@ -1012,9 +1200,9 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1087,7 +1275,7 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): def test_asset_service_grpc_lro_client(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) transport = client.transport @@ -1100,7 +1288,7 @@ def test_asset_service_grpc_lro_client(): def test_asset_service_grpc_lro_async_client(): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport="grpc_asyncio", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc_asyncio", ) transport = client.transport @@ -1113,7 +1301,6 @@ def test_asset_service_grpc_lro_async_client(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1134,7 +1321,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AssetServiceClient.common_folder_path(folder) assert expected == actual @@ -1153,7 +1339,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AssetServiceClient.common_organization_path(organization) assert expected == actual @@ -1172,7 +1357,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AssetServiceClient.common_project_path(project) assert expected == actual @@ -1192,7 +1376,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1219,7 +1402,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AssetServiceTransport, "_prep_wrapped_messages" ) as prep: client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1228,6 +1411,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AssetServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/asset_v1p5beta1/__init__.py b/tests/unit/gapic/asset_v1p5beta1/__init__.py index 42ffdf2b..4de65971 100644 --- a/tests/unit/gapic/asset_v1p5beta1/__init__.py +++ b/tests/unit/gapic/asset_v1p5beta1/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py index 8d56a60f..55f017d4 100644 --- a/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py +++ b/tests/unit/gapic/asset_v1p5beta1/test_asset_service.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -14,9 +13,9 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import os import mock +import packaging.version import grpc from grpc.experimental import aio @@ -24,22 +23,52 @@ 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 exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async -from google.auth import credentials +from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.asset_v1p5beta1.services.asset_service import AssetServiceAsyncClient from google.cloud.asset_v1p5beta1.services.asset_service import AssetServiceClient from google.cloud.asset_v1p5beta1.services.asset_service import pagers from google.cloud.asset_v1p5beta1.services.asset_service import transports +from google.cloud.asset_v1p5beta1.services.asset_service.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.asset_v1p5beta1.services.asset_service.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.asset_v1p5beta1.types import asset_service from google.cloud.asset_v1p5beta1.types import assets from google.oauth2 import service_account -from google.protobuf import timestamp_pb2 as timestamp # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import google.auth + + +# TODO(busunkim): Once google-api-core >= 1.26.0 is required: +# - Delete all the api-core and auth "less than" test cases +# - Delete these pytest markers (Make the "greater than or equal to" tests the default). +requires_google_auth_lt_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) >= packaging.version.parse("1.25.0"), + reason="This test requires google-auth < 1.25.0", +) +requires_google_auth_gte_1_25_0 = pytest.mark.skipif( + packaging.version.parse(_GOOGLE_AUTH_VERSION) < packaging.version.parse("1.25.0"), + reason="This test requires google-auth >= 1.25.0", +) + +requires_api_core_lt_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) >= packaging.version.parse("1.26.0"), + reason="This test requires google-api-core < 1.26.0", +) + +requires_api_core_gte_1_26_0 = pytest.mark.skipif( + packaging.version.parse(_API_CORE_VERSION) < packaging.version.parse("1.26.0"), + reason="This test requires google-api-core >= 1.26.0", +) def client_cert_source_callback(): @@ -85,7 +114,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_info(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: @@ -100,7 +129,7 @@ def test_asset_service_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [AssetServiceClient, AssetServiceAsyncClient,]) def test_asset_service_client_from_service_account_file(client_class): - creds = credentials.AnonymousCredentials() + creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: @@ -151,7 +180,7 @@ def test_asset_service_client_client_options( ): # 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()) + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() @@ -435,7 +464,7 @@ def test_list_assets( transport: str = "grpc", request_type=asset_service.ListAssetsRequest ): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -448,19 +477,15 @@ def test_list_assets( call.return_value = asset_service.ListAssetsResponse( next_page_token="next_page_token_value", ) - response = client.list_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.ListAssetsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListAssetsPager) - assert response.next_page_token == "next_page_token_value" @@ -472,7 +497,7 @@ def test_list_assets_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -480,7 +505,6 @@ def test_list_assets_empty_call(): client.list_assets() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == asset_service.ListAssetsRequest() @@ -489,7 +513,7 @@ async def test_list_assets_async( transport: str = "grpc_asyncio", request_type=asset_service.ListAssetsRequest ): client = AssetServiceAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -502,18 +526,15 @@ async def test_list_assets_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.ListAssetsResponse(next_page_token="next_page_token_value",) ) - response = await client.list_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.ListAssetsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListAssetsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -523,17 +544,17 @@ async def test_list_assets_async_from_dict(): def test_list_assets_field_headers(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceClient(credentials=ga_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.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: call.return_value = asset_service.ListAssetsResponse() - client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -548,11 +569,12 @@ def test_list_assets_field_headers(): @pytest.mark.asyncio async def test_list_assets_field_headers_async(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = AssetServiceAsyncClient(credentials=ga_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.ListAssetsRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -560,7 +582,6 @@ async def test_list_assets_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( asset_service.ListAssetsResponse() ) - await client.list_assets(request) # Establish that the underlying gRPC stub method was called. @@ -574,7 +595,7 @@ async def test_list_assets_field_headers_async(): def test_list_assets_pager(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -606,7 +627,7 @@ def test_list_assets_pager(): def test_list_assets_pages(): - client = AssetServiceClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_assets), "__call__") as call: @@ -630,7 +651,7 @@ def test_list_assets_pages(): @pytest.mark.asyncio async def test_list_assets_async_pager(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -661,7 +682,7 @@ async def test_list_assets_async_pager(): @pytest.mark.asyncio async def test_list_assets_async_pages(): - client = AssetServiceAsyncClient(credentials=credentials.AnonymousCredentials,) + client = AssetServiceAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -690,16 +711,16 @@ async def test_list_assets_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -709,7 +730,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = AssetServiceClient( @@ -720,7 +741,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = AssetServiceClient(transport=transport) assert client.transport is transport @@ -729,13 +750,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.AssetServiceGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.AssetServiceGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -750,23 +771,23 @@ def test_transport_get_channel(): ) 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) + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_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(),) + client = AssetServiceClient(credentials=ga_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): + with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -778,7 +799,7 @@ def test_asset_service_base_transport(): ) as Transport: Transport.return_value = None transport = transports.AssetServiceTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -789,15 +810,37 @@ def test_asset_service_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 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" + google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - load_creds.return_value = (credentials.AnonymousCredentials(), None) + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.AssetServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_base_transport_with_credentials_file_old_google_auth(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -810,19 +853,33 @@ def test_asset_service_base_transport_with_credentials_file(): 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( + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.asset_v1p5beta1.services.asset_service.transports.AssetServiceTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.AssetServiceTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 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) + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + AssetServiceClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@requires_google_auth_lt_1_25_0 +def test_asset_service_auth_adc_old_google_auth(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) AssetServiceClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -830,26 +887,162 @@ def test_asset_service_auth_adc(): ) -def test_asset_service_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_asset_service_transport_auth_adc(transport_class): # 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" + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.AssetServiceGrpcTransport, + transports.AssetServiceGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_asset_service_transport_auth_adc_old_google_auth(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus") adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), quota_project_id="octopus", ) +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_asset_service_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="cloudasset.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_old_api_core( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus") + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.AssetServiceGrpcTransport, grpc_helpers), + (transports.AssetServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_asset_service_transport_create_channel_user_scopes( + transport_class, grpc_helpers +): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "cloudasset.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + scopes=["1", "2"], + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + @pytest.mark.parametrize( "transport_class", [transports.AssetServiceGrpcTransport, transports.AssetServiceGrpcAsyncIOTransport], ) def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() # Check ssl_channel_credentials is used if provided. with mock.patch.object(transport_class, "create_channel") as mock_create_channel: @@ -888,7 +1081,7 @@ def test_asset_service_grpc_transport_client_cert_source_for_mtls(transport_clas def test_asset_service_host_no_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com" ), @@ -898,7 +1091,7 @@ def test_asset_service_host_no_port(): def test_asset_service_host_with_port(): client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudasset.googleapis.com:8000" ), @@ -949,9 +1142,9 @@ def test_asset_service_transport_channel_mtls_with_client_cert_source(transport_ mock_grpc_channel = mock.Mock() grpc_create_channel.return_value = mock_grpc_channel - cred = credentials.AnonymousCredentials() + cred = ga_credentials.AnonymousCredentials() with pytest.warns(DeprecationWarning): - with mock.patch.object(auth, "default") as adc: + with mock.patch.object(google.auth, "default") as adc: adc.return_value = (cred, None) transport = transport_class( host="squid.clam.whelk", @@ -1023,7 +1216,6 @@ def test_asset_service_transport_channel_mtls_with_adc(transport_class): def test_asset_path(): - expected = "*".format() actual = AssetServiceClient.asset_path() assert expected == actual @@ -1031,7 +1223,6 @@ def test_asset_path(): def test_common_billing_account_path(): billing_account = "squid" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1052,7 +1243,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = AssetServiceClient.common_folder_path(folder) assert expected == actual @@ -1071,7 +1261,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = AssetServiceClient.common_organization_path(organization) assert expected == actual @@ -1090,7 +1279,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = AssetServiceClient.common_project_path(project) assert expected == actual @@ -1110,7 +1298,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "winkle" location = "nautilus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1137,7 +1324,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.AssetServiceTransport, "_prep_wrapped_messages" ) as prep: client = AssetServiceClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1146,6 +1333,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = AssetServiceClient.get_transport_class() transport = transport_class( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info)