diff --git a/docs/billing_v1/cloud_billing.rst b/docs/billing_v1/cloud_billing.rst index 2a4ff02..08631bd 100644 --- a/docs/billing_v1/cloud_billing.rst +++ b/docs/billing_v1/cloud_billing.rst @@ -5,7 +5,6 @@ CloudBilling :members: :inherited-members: - .. automodule:: google.cloud.billing_v1.services.cloud_billing.pagers :members: :inherited-members: diff --git a/docs/billing_v1/cloud_catalog.rst b/docs/billing_v1/cloud_catalog.rst index db04e68..6795e65 100644 --- a/docs/billing_v1/cloud_catalog.rst +++ b/docs/billing_v1/cloud_catalog.rst @@ -5,7 +5,6 @@ CloudCatalog :members: :inherited-members: - .. automodule:: google.cloud.billing_v1.services.cloud_catalog.pagers :members: :inherited-members: diff --git a/google/cloud/billing/__init__.py b/google/cloud/billing/__init__.py index 56b06a3..a9d1fd9 100644 --- a/google/cloud/billing/__init__.py +++ b/google/cloud/billing/__init__.py @@ -1,5 +1,4 @@ # -*- coding: utf-8 -*- - # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -15,14 +14,15 @@ # limitations under the License. # +from google.cloud.billing_v1.services.cloud_billing.client import CloudBillingClient from google.cloud.billing_v1.services.cloud_billing.async_client import ( CloudBillingAsyncClient, ) -from google.cloud.billing_v1.services.cloud_billing.client import CloudBillingClient +from google.cloud.billing_v1.services.cloud_catalog.client import CloudCatalogClient from google.cloud.billing_v1.services.cloud_catalog.async_client import ( CloudCatalogAsyncClient, ) -from google.cloud.billing_v1.services.cloud_catalog.client import CloudCatalogClient + from google.cloud.billing_v1.types.cloud_billing import BillingAccount from google.cloud.billing_v1.types.cloud_billing import CreateBillingAccountRequest from google.cloud.billing_v1.types.cloud_billing import GetBillingAccountRequest @@ -46,13 +46,11 @@ from google.cloud.billing_v1.types.cloud_catalog import Sku __all__ = ( - "AggregationInfo", - "BillingAccount", - "Category", - "CloudBillingAsyncClient", "CloudBillingClient", - "CloudCatalogAsyncClient", + "CloudBillingAsyncClient", "CloudCatalogClient", + "CloudCatalogAsyncClient", + "BillingAccount", "CreateBillingAccountRequest", "GetBillingAccountRequest", "GetProjectBillingInfoRequest", @@ -60,15 +58,17 @@ "ListBillingAccountsResponse", "ListProjectBillingInfoRequest", "ListProjectBillingInfoResponse", + "ProjectBillingInfo", + "UpdateBillingAccountRequest", + "UpdateProjectBillingInfoRequest", + "AggregationInfo", + "Category", "ListServicesRequest", "ListServicesResponse", "ListSkusRequest", "ListSkusResponse", "PricingExpression", "PricingInfo", - "ProjectBillingInfo", "Service", "Sku", - "UpdateBillingAccountRequest", - "UpdateProjectBillingInfoRequest", ) diff --git a/google/cloud/billing_v1/__init__.py b/google/cloud/billing_v1/__init__.py index 1ca4234..50a8cad 100644 --- a/google/cloud/billing_v1/__init__.py +++ b/google/cloud/billing_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,7 +15,10 @@ # from .services.cloud_billing import CloudBillingClient +from .services.cloud_billing import CloudBillingAsyncClient from .services.cloud_catalog import CloudCatalogClient +from .services.cloud_catalog import CloudCatalogAsyncClient + from .types.cloud_billing import BillingAccount from .types.cloud_billing import CreateBillingAccountRequest from .types.cloud_billing import GetBillingAccountRequest @@ -39,12 +41,14 @@ from .types.cloud_catalog import Service from .types.cloud_catalog import Sku - __all__ = ( + "CloudBillingAsyncClient", + "CloudCatalogAsyncClient", "AggregationInfo", "BillingAccount", "Category", "CloudBillingClient", + "CloudCatalogClient", "CreateBillingAccountRequest", "GetBillingAccountRequest", "GetProjectBillingInfoRequest", @@ -63,5 +67,4 @@ "Sku", "UpdateBillingAccountRequest", "UpdateProjectBillingInfoRequest", - "CloudCatalogClient", ) diff --git a/google/cloud/billing_v1/gapic_metadata.json b/google/cloud/billing_v1/gapic_metadata.json new file mode 100644 index 0000000..94940c7 --- /dev/null +++ b/google/cloud/billing_v1/gapic_metadata.json @@ -0,0 +1,157 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.cloud.billing_v1", + "protoPackage": "google.cloud.billing.v1", + "schema": "1.0", + "services": { + "CloudBilling": { + "clients": { + "grpc": { + "libraryClient": "CloudBillingClient", + "rpcs": { + "CreateBillingAccount": { + "methods": [ + "create_billing_account" + ] + }, + "GetBillingAccount": { + "methods": [ + "get_billing_account" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetProjectBillingInfo": { + "methods": [ + "get_project_billing_info" + ] + }, + "ListBillingAccounts": { + "methods": [ + "list_billing_accounts" + ] + }, + "ListProjectBillingInfo": { + "methods": [ + "list_project_billing_info" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBillingAccount": { + "methods": [ + "update_billing_account" + ] + }, + "UpdateProjectBillingInfo": { + "methods": [ + "update_project_billing_info" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudBillingAsyncClient", + "rpcs": { + "CreateBillingAccount": { + "methods": [ + "create_billing_account" + ] + }, + "GetBillingAccount": { + "methods": [ + "get_billing_account" + ] + }, + "GetIamPolicy": { + "methods": [ + "get_iam_policy" + ] + }, + "GetProjectBillingInfo": { + "methods": [ + "get_project_billing_info" + ] + }, + "ListBillingAccounts": { + "methods": [ + "list_billing_accounts" + ] + }, + "ListProjectBillingInfo": { + "methods": [ + "list_project_billing_info" + ] + }, + "SetIamPolicy": { + "methods": [ + "set_iam_policy" + ] + }, + "TestIamPermissions": { + "methods": [ + "test_iam_permissions" + ] + }, + "UpdateBillingAccount": { + "methods": [ + "update_billing_account" + ] + }, + "UpdateProjectBillingInfo": { + "methods": [ + "update_project_billing_info" + ] + } + } + } + } + }, + "CloudCatalog": { + "clients": { + "grpc": { + "libraryClient": "CloudCatalogClient", + "rpcs": { + "ListServices": { + "methods": [ + "list_services" + ] + }, + "ListSkus": { + "methods": [ + "list_skus" + ] + } + } + }, + "grpc-async": { + "libraryClient": "CloudCatalogAsyncClient", + "rpcs": { + "ListServices": { + "methods": [ + "list_services" + ] + }, + "ListSkus": { + "methods": [ + "list_skus" + ] + } + } + } + } + } + } +} diff --git a/google/cloud/billing_v1/services/__init__.py b/google/cloud/billing_v1/services/__init__.py index 42ffdf2..4de6597 100644 --- a/google/cloud/billing_v1/services/__init__.py +++ b/google/cloud/billing_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/billing_v1/services/cloud_billing/__init__.py b/google/cloud/billing_v1/services/cloud_billing/__init__.py index 82ba378..09dc5df 100644 --- a/google/cloud/billing_v1/services/cloud_billing/__init__.py +++ b/google/cloud/billing_v1/services/cloud_billing/__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 CloudBillingClient from .async_client import CloudBillingAsyncClient diff --git a/google/cloud/billing_v1/services/cloud_billing/async_client.py b/google/cloud/billing_v1/services/cloud_billing/async_client.py index f56bbdf..1568ef2 100644 --- a/google/cloud/billing_v1/services/cloud_billing/async_client.py +++ b/google/cloud/billing_v1/services/cloud_billing/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.cloud.billing_v1.services.cloud_billing import pagers from google.cloud.billing_v1.types import cloud_billing -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from .transports.base import CloudBillingTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import CloudBillingGrpcAsyncIOTransport from .client import CloudBillingClient @@ -54,20 +51,16 @@ class CloudBillingAsyncClient: parse_common_billing_account_path = staticmethod( CloudBillingClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(CloudBillingClient.common_folder_path) parse_common_folder_path = staticmethod(CloudBillingClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudBillingClient.common_organization_path) parse_common_organization_path = staticmethod( CloudBillingClient.parse_common_organization_path ) - common_project_path = staticmethod(CloudBillingClient.common_project_path) parse_common_project_path = staticmethod( CloudBillingClient.parse_common_project_path ) - common_location_path = staticmethod(CloudBillingClient.common_location_path) parse_common_location_path = staticmethod( CloudBillingClient.parse_common_location_path @@ -75,7 +68,8 @@ class CloudBillingAsyncClient: @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. @@ -90,7 +84,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 @@ -107,7 +101,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudBillingTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: CloudBillingTransport: The transport used by the client instance. @@ -121,12 +115,12 @@ def transport(self) -> CloudBillingTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, CloudBillingTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud billing client. + """Instantiates the cloud billing client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -158,7 +152,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = CloudBillingClient( credentials=credentials, transport=transport, @@ -191,7 +184,6 @@ async def get_billing_account( 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. @@ -219,7 +211,6 @@ async def get_billing_account( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -232,7 +223,8 @@ async def get_billing_account( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -268,7 +260,6 @@ async def list_billing_accounts( request (:class:`google.cloud.billing_v1.types.ListBillingAccountsRequest`): The request object. Request message for `ListBillingAccounts`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -284,7 +275,6 @@ async def list_billing_accounts( """ # Create or coerce a protobuf request object. - request = cloud_billing.ListBillingAccountsRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -296,7 +286,8 @@ async def list_billing_accounts( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -352,7 +343,6 @@ async def update_billing_account( This corresponds to the ``account`` 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. @@ -380,7 +370,6 @@ async def update_billing_account( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if account is not None: @@ -395,7 +384,8 @@ async def update_billing_account( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -450,7 +440,6 @@ async def create_billing_account( This corresponds to the ``billing_account`` 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 +467,6 @@ async def create_billing_account( # If we have keyword arguments corresponding to fields on the # request, apply these. - if billing_account is not None: request.billing_account = billing_account @@ -523,7 +511,6 @@ async def list_project_billing_info( 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. @@ -552,7 +539,6 @@ async def list_project_billing_info( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -565,7 +551,8 @@ async def list_project_billing_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, ), @@ -616,7 +603,6 @@ async def get_project_billing_info( 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. @@ -646,7 +632,6 @@ async def get_project_billing_info( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -659,7 +644,8 @@ async def get_project_billing_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, ), @@ -746,7 +732,6 @@ async def update_project_billing_info( This corresponds to the ``project_billing_info`` 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. @@ -776,7 +761,6 @@ async def update_project_billing_info( # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if project_billing_info is not None: @@ -791,7 +775,8 @@ async def update_project_billing_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, ), @@ -813,13 +798,13 @@ async def update_project_billing_info( async def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a billing account. The caller must have the ``billing.accounts.getIamPolicy`` permission on the account, which is often given to billing account @@ -838,7 +823,6 @@ async def get_iam_policy( This corresponds to the ``resource`` 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. @@ -917,10 +901,9 @@ async def get_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: - request = iam_policy.GetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -931,7 +914,8 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -953,13 +937,13 @@ async def get_iam_policy( async def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a billing account. Replaces any existing policy. The caller must have the ``billing.accounts.setIamPolicy`` permission on the account, @@ -979,7 +963,6 @@ async def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1058,10 +1041,9 @@ async def set_iam_policy( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: - request = iam_policy.SetIamPolicyRequest(resource=resource,) + request = iam_policy_pb2.SetIamPolicyRequest(resource=resource,) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1072,7 +1054,8 @@ async def set_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, ), deadline=60.0, ), @@ -1094,14 +1077,14 @@ async def set_iam_policy( async def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Tests the access control policy for a billing account. This method takes the resource and a set of permissions as input and returns the subset of the input @@ -1130,7 +1113,6 @@ async def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -1154,10 +1136,9 @@ async def test_iam_permissions( # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: - request = iam_policy.TestIamPermissionsRequest( + request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions, ) @@ -1170,7 +1151,8 @@ async def test_iam_permissions( 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/billing_v1/services/cloud_billing/client.py b/google/cloud/billing_v1/services/cloud_billing/client.py index 4c5b232..3ea5c3b 100644 --- a/google/cloud/billing_v1/services/cloud_billing/client.py +++ b/google/cloud/billing_v1/services/cloud_billing/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 @@ -34,9 +32,8 @@ from google.cloud.billing_v1.services.cloud_billing import pagers from google.cloud.billing_v1.types import cloud_billing -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from .transports.base import CloudBillingTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudBillingGrpcTransport from .transports.grpc_asyncio import CloudBillingGrpcAsyncIOTransport @@ -55,7 +52,7 @@ class CloudBillingClientMeta(type): _transport_registry["grpc_asyncio"] = CloudBillingGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[CloudBillingTransport]: - """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 CloudBillingClient(metaclass=CloudBillingClientMeta): @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,16 +149,17 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudBillingTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - CloudBillingTransport: The transport used by the client instance. + CloudBillingTransport: 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, ) @@ -172,7 +172,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 @@ -183,7 +183,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 @@ -194,7 +194,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 @@ -205,7 +205,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, ) @@ -219,12 +219,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, CloudBillingTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud billing client. + """Instantiates the cloud billing client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -279,9 +279,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: @@ -293,12 +294,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. @@ -313,8 +316,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: @@ -354,7 +357,6 @@ def get_billing_account( 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. @@ -384,10 +386,8 @@ def get_billing_account( # there are no flattened fields. if not isinstance(request, cloud_billing.GetBillingAccountRequest): request = cloud_billing.GetBillingAccountRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -423,7 +423,6 @@ def list_billing_accounts( request (google.cloud.billing_v1.types.ListBillingAccountsRequest): The request object. Request message for `ListBillingAccounts`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -439,7 +438,6 @@ def list_billing_accounts( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a cloud_billing.ListBillingAccountsRequest. # There's no risk of modifying the input as we've already verified @@ -499,7 +497,6 @@ def update_billing_account( This corresponds to the ``account`` 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. @@ -529,10 +526,8 @@ def update_billing_account( # there are no flattened fields. if not isinstance(request, cloud_billing.UpdateBillingAccountRequest): request = cloud_billing.UpdateBillingAccountRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if account is not None: @@ -589,7 +584,6 @@ def create_billing_account( This corresponds to the ``billing_account`` 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. @@ -619,10 +613,8 @@ def create_billing_account( # there are no flattened fields. if not isinstance(request, cloud_billing.CreateBillingAccountRequest): request = cloud_billing.CreateBillingAccountRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if billing_account is not None: request.billing_account = billing_account @@ -663,7 +655,6 @@ def list_project_billing_info( 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. @@ -694,10 +685,8 @@ def list_project_billing_info( # there are no flattened fields. if not isinstance(request, cloud_billing.ListProjectBillingInfoRequest): request = cloud_billing.ListProjectBillingInfoRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -750,7 +739,6 @@ def get_project_billing_info( 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. @@ -782,10 +770,8 @@ def get_project_billing_info( # there are no flattened fields. if not isinstance(request, cloud_billing.GetProjectBillingInfoRequest): request = cloud_billing.GetProjectBillingInfoRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name @@ -872,7 +858,6 @@ def update_project_billing_info( This corresponds to the ``project_billing_info`` 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. @@ -904,10 +889,8 @@ def update_project_billing_info( # there are no flattened fields. if not isinstance(request, cloud_billing.UpdateProjectBillingInfoRequest): request = cloud_billing.UpdateProjectBillingInfoRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if name is not None: request.name = name if project_billing_info is not None: @@ -933,13 +916,13 @@ def update_project_billing_info( def get_iam_policy( self, - request: iam_policy.GetIamPolicyRequest = None, + request: iam_policy_pb2.GetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Gets the access control policy for a billing account. The caller must have the ``billing.accounts.getIamPolicy`` permission on the account, which is often given to billing account @@ -958,7 +941,6 @@ def get_iam_policy( This corresponds to the ``resource`` 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. @@ -1037,11 +1019,10 @@ def get_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.GetIamPolicyRequest(**request) + request = iam_policy_pb2.GetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.GetIamPolicyRequest() - + request = iam_policy_pb2.GetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1063,13 +1044,13 @@ def get_iam_policy( def set_iam_policy( self, - request: iam_policy.SetIamPolicyRequest = None, + request: iam_policy_pb2.SetIamPolicyRequest = None, *, resource: str = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: + ) -> policy_pb2.Policy: r"""Sets the access control policy for a billing account. Replaces any existing policy. The caller must have the ``billing.accounts.setIamPolicy`` permission on the account, @@ -1089,7 +1070,6 @@ def set_iam_policy( This corresponds to the ``resource`` 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. @@ -1168,11 +1148,10 @@ def set_iam_policy( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.SetIamPolicyRequest(**request) + request = iam_policy_pb2.SetIamPolicyRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.SetIamPolicyRequest() - + request = iam_policy_pb2.SetIamPolicyRequest() if resource is not None: request.resource = resource @@ -1194,14 +1173,14 @@ def set_iam_policy( def test_iam_permissions( self, - request: iam_policy.TestIamPermissionsRequest = None, + request: iam_policy_pb2.TestIamPermissionsRequest = None, *, resource: str = None, permissions: Sequence[str] = None, retry: retries.Retry = gapic_v1.method.DEFAULT, timeout: float = None, metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: + ) -> iam_policy_pb2.TestIamPermissionsResponse: r"""Tests the access control policy for a billing account. This method takes the resource and a set of permissions as input and returns the subset of the input @@ -1230,7 +1209,6 @@ def test_iam_permissions( This corresponds to the ``permissions`` 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. @@ -1254,14 +1232,12 @@ def test_iam_permissions( if isinstance(request, dict): # The request isn't a proto-plus wrapped type, # so it must be constructed via keyword expansion. - request = iam_policy.TestIamPermissionsRequest(**request) + request = iam_policy_pb2.TestIamPermissionsRequest(**request) elif not request: # Null request, just make one. - request = iam_policy.TestIamPermissionsRequest() - + request = iam_policy_pb2.TestIamPermissionsRequest() if resource is not None: request.resource = resource - if permissions: request.permissions.extend(permissions) diff --git a/google/cloud/billing_v1/services/cloud_billing/pagers.py b/google/cloud/billing_v1/services/cloud_billing/pagers.py index a0fbaba..a54ea29 100644 --- a/google/cloud/billing_v1/services/cloud_billing/pagers.py +++ b/google/cloud/billing_v1/services/cloud_billing/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, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,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/billing_v1/services/cloud_billing/transports/__init__.py b/google/cloud/billing_v1/services/cloud_billing/transports/__init__.py index e80f5b8..9815329 100644 --- a/google/cloud/billing_v1/services/cloud_billing/transports/__init__.py +++ b/google/cloud/billing_v1/services/cloud_billing/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/billing_v1/services/cloud_billing/transports/base.py b/google/cloud/billing_v1/services/cloud_billing/transports/base.py index a59b9b4..45c58e4 100644 --- a/google/cloud/billing_v1/services/cloud_billing/transports/base.py +++ b/google/cloud/billing_v1/services/cloud_billing/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.auth import credentials # type: ignore +from google.auth import credentials as ga_credentials # type: ignore from google.cloud.billing_v1.types import cloud_billing -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_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 CloudBillingTransport(abc.ABC): """Abstract transport class for CloudBilling.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudbilling.googleapis.com" + def __init__( self, *, - host: str = "cloudbilling.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 = { @@ -113,7 +173,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, ), @@ -127,7 +188,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, ), @@ -141,7 +203,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, ), @@ -160,7 +223,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, ), @@ -174,7 +238,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, ), @@ -188,7 +253,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, ), @@ -202,7 +268,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, ), @@ -216,7 +283,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, ), @@ -230,7 +298,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, ), @@ -242,22 +311,20 @@ def _prep_wrapped_messages(self, client_info): @property def get_billing_account( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.GetBillingAccountRequest], - typing.Union[ - cloud_billing.BillingAccount, typing.Awaitable[cloud_billing.BillingAccount] - ], + Union[cloud_billing.BillingAccount, Awaitable[cloud_billing.BillingAccount]], ]: raise NotImplementedError() @property def list_billing_accounts( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.ListBillingAccountsRequest], - typing.Union[ + Union[ cloud_billing.ListBillingAccountsResponse, - typing.Awaitable[cloud_billing.ListBillingAccountsResponse], + Awaitable[cloud_billing.ListBillingAccountsResponse], ], ]: raise NotImplementedError() @@ -265,33 +332,29 @@ def list_billing_accounts( @property def update_billing_account( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.UpdateBillingAccountRequest], - typing.Union[ - cloud_billing.BillingAccount, typing.Awaitable[cloud_billing.BillingAccount] - ], + Union[cloud_billing.BillingAccount, Awaitable[cloud_billing.BillingAccount]], ]: raise NotImplementedError() @property def create_billing_account( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.CreateBillingAccountRequest], - typing.Union[ - cloud_billing.BillingAccount, typing.Awaitable[cloud_billing.BillingAccount] - ], + Union[cloud_billing.BillingAccount, Awaitable[cloud_billing.BillingAccount]], ]: raise NotImplementedError() @property def list_project_billing_info( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.ListProjectBillingInfoRequest], - typing.Union[ + Union[ cloud_billing.ListProjectBillingInfoResponse, - typing.Awaitable[cloud_billing.ListProjectBillingInfoResponse], + Awaitable[cloud_billing.ListProjectBillingInfoResponse], ], ]: raise NotImplementedError() @@ -299,11 +362,11 @@ def list_project_billing_info( @property def get_project_billing_info( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.GetProjectBillingInfoRequest], - typing.Union[ + Union[ cloud_billing.ProjectBillingInfo, - typing.Awaitable[cloud_billing.ProjectBillingInfo], + Awaitable[cloud_billing.ProjectBillingInfo], ], ]: raise NotImplementedError() @@ -311,11 +374,11 @@ def get_project_billing_info( @property def update_project_billing_info( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_billing.UpdateProjectBillingInfoRequest], - typing.Union[ + Union[ cloud_billing.ProjectBillingInfo, - typing.Awaitable[cloud_billing.ProjectBillingInfo], + Awaitable[cloud_billing.ProjectBillingInfo], ], ]: raise NotImplementedError() @@ -323,29 +386,29 @@ def update_project_billing_info( @property def get_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.GetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def set_iam_policy( self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ) -> Callable[ + [iam_policy_pb2.SetIamPolicyRequest], + Union[policy_pb2.Policy, Awaitable[policy_pb2.Policy]], ]: raise NotImplementedError() @property def test_iam_permissions( self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + Union[ + iam_policy_pb2.TestIamPermissionsResponse, + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ], ]: raise NotImplementedError() diff --git a/google/cloud/billing_v1/services/cloud_billing/transports/grpc.py b/google/cloud/billing_v1/services/cloud_billing/transports/grpc.py index 94fb1ae..a54d600 100644 --- a/google/cloud/billing_v1/services/cloud_billing/transports/grpc.py +++ b/google/cloud/billing_v1/services/cloud_billing/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 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.billing_v1.types import cloud_billing -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from .base import CloudBillingTransport, DEFAULT_CLIENT_INFO @@ -53,7 +50,7 @@ def __init__( self, *, host: str = "cloudbilling.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 @@ -177,7 +175,7 @@ def __init__( def create_channel( cls, host: str = "cloudbilling.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, ) @@ -485,7 +485,7 @@ def update_project_billing_info( @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy for a billing account. The caller @@ -506,15 +506,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.billing.v1.CloudBilling/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy for a billing account. Replaces @@ -536,8 +536,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.billing.v1.CloudBilling/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -545,7 +545,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -568,8 +569,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.billing.v1.CloudBilling/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/billing_v1/services/cloud_billing/transports/grpc_asyncio.py b/google/cloud/billing_v1/services/cloud_billing/transports/grpc_asyncio.py index a6b3ebc..7b07f82 100644 --- a/google/cloud/billing_v1/services/cloud_billing/transports/grpc_asyncio.py +++ b/google/cloud/billing_v1/services/cloud_billing/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 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.billing_v1.types import cloud_billing -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore - +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from .base import CloudBillingTransport, DEFAULT_CLIENT_INFO from .grpc import CloudBillingGrpcTransport @@ -56,7 +53,7 @@ class CloudBillingGrpcAsyncIOTransport(CloudBillingTransport): def create_channel( cls, host: str = "cloudbilling.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 = "cloudbilling.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 @@ -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 @@ -493,7 +492,7 @@ def update_project_billing_info( @property def get_iam_policy( self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the get iam policy method over gRPC. Gets the access control policy for a billing account. The caller @@ -514,15 +513,15 @@ def get_iam_policy( if "get_iam_policy" not in self._stubs: self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.billing.v1.CloudBilling/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["get_iam_policy"] @property def set_iam_policy( self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: r"""Return a callable for the set iam policy method over gRPC. Sets the access control policy for a billing account. Replaces @@ -544,8 +543,8 @@ def set_iam_policy( if "set_iam_policy" not in self._stubs: self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( "/google.cloud.billing.v1.CloudBilling/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, + request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy_pb2.Policy.FromString, ) return self._stubs["set_iam_policy"] @@ -553,8 +552,8 @@ def set_iam_policy( def test_iam_permissions( self, ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], + [iam_policy_pb2.TestIamPermissionsRequest], + Awaitable[iam_policy_pb2.TestIamPermissionsResponse], ]: r"""Return a callable for the test iam permissions method over gRPC. @@ -577,8 +576,8 @@ def test_iam_permissions( if "test_iam_permissions" not in self._stubs: self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( "/google.cloud.billing.v1.CloudBilling/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, ) return self._stubs["test_iam_permissions"] diff --git a/google/cloud/billing_v1/services/cloud_catalog/__init__.py b/google/cloud/billing_v1/services/cloud_catalog/__init__.py index cc54a8d..6785e0d 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/__init__.py +++ b/google/cloud/billing_v1/services/cloud_catalog/__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 CloudCatalogClient from .async_client import CloudCatalogAsyncClient diff --git a/google/cloud/billing_v1/services/cloud_catalog/async_client.py b/google/cloud/billing_v1/services/cloud_catalog/async_client.py index 31e91d7..4be1c6a 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/async_client.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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,15 +20,14 @@ 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.billing_v1.services.cloud_catalog import pagers from google.cloud.billing_v1.types import cloud_catalog - from .transports.base import CloudCatalogTransport, DEFAULT_CLIENT_INFO from .transports.grpc_asyncio import CloudCatalogGrpcAsyncIOTransport from .client import CloudCatalogClient @@ -51,27 +48,22 @@ class CloudCatalogAsyncClient: parse_service_path = staticmethod(CloudCatalogClient.parse_service_path) sku_path = staticmethod(CloudCatalogClient.sku_path) parse_sku_path = staticmethod(CloudCatalogClient.parse_sku_path) - common_billing_account_path = staticmethod( CloudCatalogClient.common_billing_account_path ) parse_common_billing_account_path = staticmethod( CloudCatalogClient.parse_common_billing_account_path ) - common_folder_path = staticmethod(CloudCatalogClient.common_folder_path) parse_common_folder_path = staticmethod(CloudCatalogClient.parse_common_folder_path) - common_organization_path = staticmethod(CloudCatalogClient.common_organization_path) parse_common_organization_path = staticmethod( CloudCatalogClient.parse_common_organization_path ) - common_project_path = staticmethod(CloudCatalogClient.common_project_path) parse_common_project_path = staticmethod( CloudCatalogClient.parse_common_project_path ) - common_location_path = staticmethod(CloudCatalogClient.common_location_path) parse_common_location_path = staticmethod( CloudCatalogClient.parse_common_location_path @@ -79,7 +71,8 @@ class CloudCatalogAsyncClient: @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. @@ -94,7 +87,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 @@ -111,7 +104,7 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudCatalogTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: CloudCatalogTransport: The transport used by the client instance. @@ -125,12 +118,12 @@ def transport(self) -> CloudCatalogTransport: def __init__( self, *, - credentials: credentials.Credentials = None, + credentials: ga_credentials.Credentials = None, transport: Union[str, CloudCatalogTransport] = "grpc_asyncio", client_options: ClientOptions = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud catalog client. + """Instantiates the cloud catalog client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -162,7 +155,6 @@ def __init__( google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport creation failed for any reason. """ - self._client = CloudCatalogClient( credentials=credentials, transport=transport, @@ -183,7 +175,6 @@ async def list_services( Args: request (:class:`google.cloud.billing_v1.types.ListServicesRequest`): The request object. Request message for `ListServices`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -199,7 +190,6 @@ async def list_services( """ # Create or coerce a protobuf request object. - request = cloud_catalog.ListServicesRequest(request) # Wrap the RPC method; this adds retry and timeout information, @@ -244,7 +234,6 @@ async def list_skus( 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. @@ -273,7 +262,6 @@ async def list_skus( # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/billing_v1/services/cloud_catalog/client.py b/google/cloud/billing_v1/services/cloud_catalog/client.py index eefb8eb..ea21d9b 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/client.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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 @@ -34,7 +32,6 @@ from google.cloud.billing_v1.services.cloud_catalog import pagers from google.cloud.billing_v1.types import cloud_catalog - from .transports.base import CloudCatalogTransport, DEFAULT_CLIENT_INFO from .transports.grpc import CloudCatalogGrpcTransport from .transports.grpc_asyncio import CloudCatalogGrpcAsyncIOTransport @@ -53,7 +50,7 @@ class CloudCatalogClientMeta(type): _transport_registry["grpc_asyncio"] = CloudCatalogGrpcAsyncIOTransport def get_transport_class(cls, label: str = None,) -> Type[CloudCatalogTransport]: - """Return an appropriate transport class. + """Returns an appropriate transport class. Args: label: The name of the desired transport. If none is @@ -79,7 +76,8 @@ class CloudCatalogClient(metaclass=CloudCatalogClientMeta): @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: @@ -113,7 +111,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. @@ -130,7 +129,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 @@ -149,38 +148,39 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): @property def transport(self) -> CloudCatalogTransport: - """Return the transport used by the client instance. + """Returns the transport used by the client instance. Returns: - CloudCatalogTransport: The transport used by the client instance. + CloudCatalogTransport: The transport used by the client + instance. """ return self._transport @staticmethod def service_path(service: str,) -> str: - """Return a fully-qualified service string.""" + """Returns a fully-qualified service string.""" return "services/{service}".format(service=service,) @staticmethod def parse_service_path(path: str) -> Dict[str, str]: - """Parse a service path into its component segments.""" + """Parses a service path into its component segments.""" m = re.match(r"^services/(?P.+?)$", path) return m.groupdict() if m else {} @staticmethod def sku_path(service: str, sku: str,) -> str: - """Return a fully-qualified sku string.""" + """Returns a fully-qualified sku string.""" return "services/{service}/skus/{sku}".format(service=service, sku=sku,) @staticmethod def parse_sku_path(path: str) -> Dict[str, str]: - """Parse a sku path into its component segments.""" + """Parses a sku path into its component segments.""" m = re.match(r"^services/(?P.+?)/skus/(?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, ) @@ -193,7 +193,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 @@ -204,7 +204,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 @@ -215,7 +215,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 @@ -226,7 +226,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, ) @@ -240,12 +240,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, CloudCatalogTransport, None] = None, client_options: Optional[client_options_lib.ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: - """Instantiate the cloud catalog client. + """Instantiates the cloud catalog client. Args: credentials (Optional[google.auth.credentials.Credentials]): The @@ -300,9 +300,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: @@ -314,12 +315,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. @@ -334,8 +337,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: @@ -363,7 +366,6 @@ def list_services( Args: request (google.cloud.billing_v1.types.ListServicesRequest): The request object. Request message for `ListServices`. - retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -379,7 +381,6 @@ def list_services( """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes # in a cloud_catalog.ListServicesRequest. # There's no risk of modifying the input as we've already verified @@ -425,7 +426,6 @@ def list_skus( 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. @@ -456,10 +456,8 @@ def list_skus( # there are no flattened fields. if not isinstance(request, cloud_catalog.ListSkusRequest): request = cloud_catalog.ListSkusRequest(request) - # If we have keyword arguments corresponding to fields on the # request, apply these. - if parent is not None: request.parent = parent diff --git a/google/cloud/billing_v1/services/cloud_catalog/pagers.py b/google/cloud/billing_v1/services/cloud_catalog/pagers.py index 99752d9..4dcd17c 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/pagers.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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, @@ -117,7 +115,7 @@ def __init__( *, metadata: Sequence[Tuple[str, str]] = () ): - """Instantiate the pager. + """Instantiates the pager. Args: method (Callable): The method that was originally called, and @@ -245,7 +243,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/billing_v1/services/cloud_catalog/transports/__init__.py b/google/cloud/billing_v1/services/cloud_catalog/transports/__init__.py index a81f59e..1048acd 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/transports/__init__.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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/billing_v1/services/cloud_catalog/transports/base.py b/google/cloud/billing_v1/services/cloud_catalog/transports/base.py index 9bd9b21..070b183 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/transports/base.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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.billing_v1.types import cloud_catalog - try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution("google-cloud-billing",).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 CloudCatalogTransport(abc.ABC): """Abstract transport class for CloudCatalog.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + DEFAULT_HOST: str = "cloudbilling.googleapis.com" + def __init__( self, *, - host: str = "cloudbilling.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 = { @@ -115,11 +175,11 @@ def _prep_wrapped_messages(self, client_info): @property def list_services( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_catalog.ListServicesRequest], - typing.Union[ + Union[ cloud_catalog.ListServicesResponse, - typing.Awaitable[cloud_catalog.ListServicesResponse], + Awaitable[cloud_catalog.ListServicesResponse], ], ]: raise NotImplementedError() @@ -127,11 +187,10 @@ def list_services( @property def list_skus( self, - ) -> typing.Callable[ + ) -> Callable[ [cloud_catalog.ListSkusRequest], - typing.Union[ - cloud_catalog.ListSkusResponse, - typing.Awaitable[cloud_catalog.ListSkusResponse], + Union[ + cloud_catalog.ListSkusResponse, Awaitable[cloud_catalog.ListSkusResponse] ], ]: raise NotImplementedError() diff --git a/google/cloud/billing_v1/services/cloud_catalog/transports/grpc.py b/google/cloud/billing_v1/services/cloud_catalog/transports/grpc.py index ab6a557..b12f1dc 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/transports/grpc.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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.billing_v1.types import cloud_catalog - from .base import CloudCatalogTransport, DEFAULT_CLIENT_INFO @@ -52,7 +49,7 @@ def __init__( self, *, host: str = "cloudbilling.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 @@ -176,7 +174,7 @@ def __init__( def create_channel( cls, host: str = "cloudbilling.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, @@ -207,13 +205,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/billing_v1/services/cloud_catalog/transports/grpc_asyncio.py b/google/cloud/billing_v1/services/cloud_catalog/transports/grpc_asyncio.py index af6f4b7..dfb1fcf 100644 --- a/google/cloud/billing_v1/services/cloud_catalog/transports/grpc_asyncio.py +++ b/google/cloud/billing_v1/services/cloud_catalog/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.billing_v1.types import cloud_catalog - from .base import CloudCatalogTransport, DEFAULT_CLIENT_INFO from .grpc import CloudCatalogGrpcTransport @@ -55,7 +52,7 @@ class CloudCatalogGrpcAsyncIOTransport(CloudCatalogTransport): def create_channel( cls, host: str = "cloudbilling.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 = "cloudbilling.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 @@ -168,7 +168,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/billing_v1/types/__init__.py b/google/cloud/billing_v1/types/__init__.py index 43a8f93..67859c3 100644 --- a/google/cloud/billing_v1/types/__init__.py +++ b/google/cloud/billing_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 .cloud_billing import ( BillingAccount, CreateBillingAccountRequest, diff --git a/google/cloud/billing_v1/types/cloud_billing.py b/google/cloud/billing_v1/types/cloud_billing.py index 23e03b1..08966cf 100644 --- a/google/cloud/billing_v1/types/cloud_billing.py +++ b/google/cloud/billing_v1/types/cloud_billing.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( @@ -70,13 +67,10 @@ class BillingAccount(proto.Message): be empty. """ - name = proto.Field(proto.STRING, number=1) - - open_ = proto.Field(proto.BOOL, number=2) - - display_name = proto.Field(proto.STRING, number=3) - - master_billing_account = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=1,) + open_ = proto.Field(proto.BOOL, number=2,) + display_name = proto.Field(proto.STRING, number=3,) + master_billing_account = proto.Field(proto.STRING, number=4,) class ProjectBillingInfo(proto.Message): @@ -112,18 +106,14 @@ class ProjectBillingInfo(proto.Message): paid services. This field is read-only. """ - name = proto.Field(proto.STRING, number=1) - - project_id = proto.Field(proto.STRING, number=2) - - billing_account_name = proto.Field(proto.STRING, number=3) - - billing_enabled = proto.Field(proto.BOOL, number=4) + name = proto.Field(proto.STRING, number=1,) + project_id = proto.Field(proto.STRING, number=2,) + billing_account_name = proto.Field(proto.STRING, number=3,) + billing_enabled = proto.Field(proto.BOOL, number=4,) class GetBillingAccountRequest(proto.Message): r"""Request message for ``GetBillingAccount``. - Attributes: name (str): Required. The resource name of the billing account to @@ -131,12 +121,11 @@ class GetBillingAccountRequest(proto.Message): ``billingAccounts/012345-567890-ABCDEF``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class ListBillingAccountsRequest(proto.Message): r"""Request message for ``ListBillingAccounts``. - Attributes: page_size (int): Requested page size. The maximum page size is @@ -156,16 +145,13 @@ class ListBillingAccountsRequest(proto.Message): supported. """ - page_size = proto.Field(proto.INT32, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - filter = proto.Field(proto.STRING, number=3) + page_size = proto.Field(proto.INT32, number=1,) + page_token = proto.Field(proto.STRING, number=2,) + filter = proto.Field(proto.STRING, number=3,) class ListBillingAccountsResponse(proto.Message): r"""Response message for ``ListBillingAccounts``. - Attributes: billing_accounts (Sequence[google.cloud.billing_v1.types.BillingAccount]): A list of billing accounts. @@ -183,13 +169,11 @@ def raw_page(self): billing_accounts = proto.RepeatedField( proto.MESSAGE, number=1, message="BillingAccount", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class CreateBillingAccountRequest(proto.Message): r"""Request message for ``CreateBillingAccount``. - Attributes: billing_account (google.cloud.billing_v1.types.BillingAccount): Required. The billing account resource to @@ -204,7 +188,6 @@ class CreateBillingAccountRequest(proto.Message): class UpdateBillingAccountRequest(proto.Message): r"""Request message for ``UpdateBillingAccount``. - Attributes: name (str): Required. The name of the billing account @@ -217,16 +200,15 @@ class UpdateBillingAccountRequest(proto.Message): is currently supported. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) account = proto.Field(proto.MESSAGE, number=2, message="BillingAccount",) - - update_mask = proto.Field(proto.MESSAGE, number=3, message=field_mask.FieldMask,) + update_mask = proto.Field( + proto.MESSAGE, number=3, message=field_mask_pb2.FieldMask, + ) class ListProjectBillingInfoRequest(proto.Message): r"""Request message for ``ListProjectBillingInfo``. - Attributes: name (str): Required. The resource name of the billing account @@ -242,16 +224,13 @@ class ListProjectBillingInfoRequest(proto.Message): the first page of results is returned. """ - name = proto.Field(proto.STRING, number=1) - - page_size = proto.Field(proto.INT32, number=2) - - page_token = proto.Field(proto.STRING, number=3) + name = proto.Field(proto.STRING, number=1,) + page_size = proto.Field(proto.INT32, number=2,) + page_token = proto.Field(proto.STRING, number=3,) class ListProjectBillingInfoResponse(proto.Message): r"""Request message for ``ListProjectBillingInfoResponse``. - Attributes: project_billing_info (Sequence[google.cloud.billing_v1.types.ProjectBillingInfo]): A list of ``ProjectBillingInfo`` resources representing the @@ -270,13 +249,11 @@ def raw_page(self): project_billing_info = proto.RepeatedField( proto.MESSAGE, number=1, message="ProjectBillingInfo", ) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class GetProjectBillingInfoRequest(proto.Message): r"""Request message for ``GetProjectBillingInfo``. - Attributes: name (str): Required. The resource name of the project for which billing @@ -284,12 +261,11 @@ class GetProjectBillingInfoRequest(proto.Message): ``projects/tokyo-rain-123``. """ - name = proto.Field(proto.STRING, number=1) + name = proto.Field(proto.STRING, number=1,) class UpdateProjectBillingInfoRequest(proto.Message): r"""Request message for ``UpdateProjectBillingInfo``. - Attributes: name (str): Required. The resource name of the project associated with @@ -301,8 +277,7 @@ class UpdateProjectBillingInfoRequest(proto.Message): except ``billing_account_name``. """ - name = proto.Field(proto.STRING, number=1) - + name = proto.Field(proto.STRING, number=1,) project_billing_info = proto.Field( proto.MESSAGE, number=2, message="ProjectBillingInfo", ) diff --git a/google/cloud/billing_v1/types/cloud_catalog.py b/google/cloud/billing_v1/types/cloud_catalog.py index 09f9a39..14fa6b5 100644 --- a/google/cloud/billing_v1/types/cloud_catalog.py +++ b/google/cloud/billing_v1/types/cloud_catalog.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.protobuf import timestamp_pb2 as timestamp # type: ignore -from google.type import money_pb2 as money # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import money_pb2 # type: ignore __protobuf__ = proto.module( @@ -41,7 +38,6 @@ class Service(proto.Message): r"""Encapsulates a single service in Google Cloud Platform. - Attributes: name (str): The resource name for the service. @@ -58,18 +54,14 @@ class Service(proto.Message): "businessEntities/Maps". """ - name = proto.Field(proto.STRING, number=1) - - service_id = proto.Field(proto.STRING, number=2) - - display_name = proto.Field(proto.STRING, number=3) - - business_entity_name = proto.Field(proto.STRING, number=4) + name = proto.Field(proto.STRING, number=1,) + service_id = proto.Field(proto.STRING, number=2,) + display_name = proto.Field(proto.STRING, number=3,) + business_entity_name = proto.Field(proto.STRING, number=4,) class Sku(proto.Message): r"""Encapsulates a single SKU in Google Cloud Platform - Attributes: name (str): The resource name for the SKU. @@ -98,24 +90,17 @@ class Sku(proto.Message): Google Cloud Platform. """ - name = proto.Field(proto.STRING, number=1) - - sku_id = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - + name = proto.Field(proto.STRING, number=1,) + sku_id = proto.Field(proto.STRING, number=2,) + description = proto.Field(proto.STRING, number=3,) category = proto.Field(proto.MESSAGE, number=4, message="Category",) - - service_regions = proto.RepeatedField(proto.STRING, number=5) - + service_regions = proto.RepeatedField(proto.STRING, number=5,) pricing_info = proto.RepeatedField(proto.MESSAGE, number=6, message="PricingInfo",) - - service_provider_name = proto.Field(proto.STRING, number=7) + service_provider_name = proto.Field(proto.STRING, number=7,) class Category(proto.Message): r"""Represents the category hierarchy of a SKU. - Attributes: service_display_name (str): The display name of the service this SKU @@ -134,13 +119,10 @@ class Category(proto.Message): "Commit1Yr" etc. """ - service_display_name = proto.Field(proto.STRING, number=1) - - resource_family = proto.Field(proto.STRING, number=2) - - resource_group = proto.Field(proto.STRING, number=3) - - usage_type = proto.Field(proto.STRING, number=4) + service_display_name = proto.Field(proto.STRING, number=1,) + resource_family = proto.Field(proto.STRING, number=2,) + resource_group = proto.Field(proto.STRING, number=3,) + usage_type = proto.Field(proto.STRING, number=4,) class PricingInfo(proto.Message): @@ -175,17 +157,15 @@ class PricingInfo(proto.Message): 1.0. Example: USD \* currency_conversion_rate = JPY """ - effective_time = proto.Field(proto.MESSAGE, number=1, message=timestamp.Timestamp,) - - summary = proto.Field(proto.STRING, number=2) - + effective_time = proto.Field( + proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, + ) + summary = proto.Field(proto.STRING, number=2,) pricing_expression = proto.Field( proto.MESSAGE, number=3, message="PricingExpression", ) - aggregation_info = proto.Field(proto.MESSAGE, number=4, message="AggregationInfo",) - - currency_conversion_rate = proto.Field(proto.DOUBLE, number=5) + currency_conversion_rate = proto.Field(proto.DOUBLE, number=5,) class PricingExpression(proto.Message): @@ -251,22 +231,15 @@ class TierRate(proto.Message): $10 indicates that each unit will cost $10. """ - start_usage_amount = proto.Field(proto.DOUBLE, number=1) - - unit_price = proto.Field(proto.MESSAGE, number=2, message=money.Money,) - - usage_unit = proto.Field(proto.STRING, number=1) - - usage_unit_description = proto.Field(proto.STRING, number=4) - - base_unit = proto.Field(proto.STRING, number=5) - - base_unit_description = proto.Field(proto.STRING, number=6) - - base_unit_conversion_factor = proto.Field(proto.DOUBLE, number=7) - - display_quantity = proto.Field(proto.DOUBLE, number=2) + start_usage_amount = proto.Field(proto.DOUBLE, number=1,) + unit_price = proto.Field(proto.MESSAGE, number=2, message=money_pb2.Money,) + usage_unit = proto.Field(proto.STRING, number=1,) + usage_unit_description = proto.Field(proto.STRING, number=4,) + base_unit = proto.Field(proto.STRING, number=5,) + base_unit_description = proto.Field(proto.STRING, number=6,) + base_unit_conversion_factor = proto.Field(proto.DOUBLE, number=7,) + display_quantity = proto.Field(proto.DOUBLE, number=2,) tiered_rates = proto.RepeatedField(proto.MESSAGE, number=3, message=TierRate,) @@ -305,15 +278,12 @@ class AggregationInterval(proto.Enum): MONTHLY = 2 aggregation_level = proto.Field(proto.ENUM, number=1, enum=AggregationLevel,) - aggregation_interval = proto.Field(proto.ENUM, number=2, enum=AggregationInterval,) - - aggregation_count = proto.Field(proto.INT32, number=3) + aggregation_count = proto.Field(proto.INT32, number=3,) class ListServicesRequest(proto.Message): r"""Request message for ``ListServices``. - Attributes: page_size (int): Requested page size. Defaults to 5000. @@ -324,14 +294,12 @@ class ListServicesRequest(proto.Message): results is returned. """ - page_size = proto.Field(proto.INT32, number=1) - - page_token = proto.Field(proto.STRING, number=2) + page_size = proto.Field(proto.INT32, number=1,) + page_token = proto.Field(proto.STRING, number=2,) class ListServicesResponse(proto.Message): r"""Response message for ``ListServices``. - Attributes: services (Sequence[google.cloud.billing_v1.types.Service]): A list of services. @@ -347,13 +315,11 @@ def raw_page(self): return self services = proto.RepeatedField(proto.MESSAGE, number=1, message="Service",) - - next_page_token = proto.Field(proto.STRING, number=2) + next_page_token = proto.Field(proto.STRING, number=2,) class ListSkusRequest(proto.Message): r"""Request message for ``ListSkus``. - Attributes: parent (str): Required. The name of the service. @@ -385,22 +351,16 @@ class ListSkusRequest(proto.Message): is returned. """ - parent = proto.Field(proto.STRING, number=1) - - start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - currency_code = proto.Field(proto.STRING, number=4) - - page_size = proto.Field(proto.INT32, number=5) - - page_token = proto.Field(proto.STRING, number=6) + parent = proto.Field(proto.STRING, number=1,) + start_time = proto.Field(proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp,) + end_time = proto.Field(proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp,) + currency_code = proto.Field(proto.STRING, number=4,) + page_size = proto.Field(proto.INT32, number=5,) + page_token = proto.Field(proto.STRING, number=6,) class ListSkusResponse(proto.Message): r"""Response message for ``ListSkus``. - Attributes: skus (Sequence[google.cloud.billing_v1.types.Sku]): The list of public SKUs of the given service. @@ -416,8 +376,7 @@ def raw_page(self): return self skus = proto.RepeatedField(proto.MESSAGE, number=1, message="Sku",) - - 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/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..4de6597 --- /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 0000000..4de6597 --- /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 0000000..4de6597 --- /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/billing_v1/__init__.py b/tests/unit/gapic/billing_v1/__init__.py index 42ffdf2..4de6597 100644 --- a/tests/unit/gapic/billing_v1/__init__.py +++ b/tests/unit/gapic/billing_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/billing_v1/test_cloud_billing.py b/tests/unit/gapic/billing_v1/test_cloud_billing.py index 0a94fec..fd251c7 100644 --- a/tests/unit/gapic/billing_v1/test_cloud_billing.py +++ b/tests/unit/gapic/billing_v1/test_cloud_billing.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 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.billing_v1.services.cloud_billing import CloudBillingAsyncClient from google.cloud.billing_v1.services.cloud_billing import CloudBillingClient from google.cloud.billing_v1.services.cloud_billing import pagers from google.cloud.billing_v1.services.cloud_billing import transports +from google.cloud.billing_v1.services.cloud_billing.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.billing_v1.services.cloud_billing.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.billing_v1.types import cloud_billing -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.type import expr_pb2 as expr # type: ignore +from google.protobuf import field_mask_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(): @@ -88,7 +117,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [CloudBillingClient, CloudBillingAsyncClient,]) def test_cloud_billing_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_cloud_billing_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [CloudBillingClient, CloudBillingAsyncClient,]) def test_cloud_billing_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_cloud_billing_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(CloudBillingClient, "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_get_billing_account( transport: str = "grpc", request_type=cloud_billing.GetBillingAccountRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -456,25 +485,18 @@ def test_get_billing_account( display_name="display_name_value", master_billing_account="master_billing_account_value", ) - response = client.get_billing_account(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.GetBillingAccountRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_billing.BillingAccount) - assert response.name == "name_value" - assert response.open_ is True - assert response.display_name == "display_name_value" - assert response.master_billing_account == "master_billing_account_value" @@ -486,7 +508,7 @@ def test_get_billing_account_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -496,7 +518,6 @@ def test_get_billing_account_empty_call(): client.get_billing_account() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.GetBillingAccountRequest() @@ -505,7 +526,7 @@ async def test_get_billing_account_async( transport: str = "grpc_asyncio", request_type=cloud_billing.GetBillingAccountRequest ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -525,24 +546,18 @@ async def test_get_billing_account_async( master_billing_account="master_billing_account_value", ) ) - response = await client.get_billing_account(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.GetBillingAccountRequest() # Establish that the response is the type that we expect. assert isinstance(response, cloud_billing.BillingAccount) - assert response.name == "name_value" - assert response.open_ is True - assert response.display_name == "display_name_value" - assert response.master_billing_account == "master_billing_account_value" @@ -552,11 +567,12 @@ async def test_get_billing_account_async_from_dict(): def test_get_billing_account_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = cloud_billing.GetBillingAccountRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -564,7 +580,6 @@ def test_get_billing_account_field_headers(): type(client.transport.get_billing_account), "__call__" ) as call: call.return_value = cloud_billing.BillingAccount() - client.get_billing_account(request) # Establish that the underlying gRPC stub method was called. @@ -579,11 +594,12 @@ def test_get_billing_account_field_headers(): @pytest.mark.asyncio async def test_get_billing_account_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = cloud_billing.GetBillingAccountRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -593,7 +609,6 @@ async def test_get_billing_account_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_billing.BillingAccount() ) - await client.get_billing_account(request) # Establish that the underlying gRPC stub method was called. @@ -607,7 +622,7 @@ async def test_get_billing_account_field_headers_async(): def test_get_billing_account_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -615,7 +630,6 @@ def test_get_billing_account_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_billing.BillingAccount() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_billing_account(name="name_value",) @@ -624,12 +638,11 @@ def test_get_billing_account_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_billing_account_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -641,7 +654,7 @@ def test_get_billing_account_flattened_error(): @pytest.mark.asyncio async def test_get_billing_account_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -661,13 +674,12 @@ async def test_get_billing_account_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_billing_account_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -681,7 +693,7 @@ def test_list_billing_accounts( transport: str = "grpc", request_type=cloud_billing.ListBillingAccountsRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -696,19 +708,15 @@ def test_list_billing_accounts( call.return_value = cloud_billing.ListBillingAccountsResponse( next_page_token="next_page_token_value", ) - response = client.list_billing_accounts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.ListBillingAccountsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBillingAccountsPager) - assert response.next_page_token == "next_page_token_value" @@ -720,7 +728,7 @@ def test_list_billing_accounts_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -730,7 +738,6 @@ def test_list_billing_accounts_empty_call(): client.list_billing_accounts() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.ListBillingAccountsRequest() @@ -740,7 +747,7 @@ async def test_list_billing_accounts_async( request_type=cloud_billing.ListBillingAccountsRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -757,18 +764,15 @@ async def test_list_billing_accounts_async( next_page_token="next_page_token_value", ) ) - response = await client.list_billing_accounts(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.ListBillingAccountsRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListBillingAccountsAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -778,7 +782,7 @@ async def test_list_billing_accounts_async_from_dict(): def test_list_billing_accounts_pager(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -821,7 +825,7 @@ def test_list_billing_accounts_pager(): def test_list_billing_accounts_pages(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -859,7 +863,7 @@ def test_list_billing_accounts_pages(): @pytest.mark.asyncio async def test_list_billing_accounts_async_pager(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -904,7 +908,7 @@ async def test_list_billing_accounts_async_pager(): @pytest.mark.asyncio async def test_list_billing_accounts_async_pages(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -948,7 +952,7 @@ def test_update_billing_account( transport: str = "grpc", request_type=cloud_billing.UpdateBillingAccountRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -966,25 +970,18 @@ def test_update_billing_account( display_name="display_name_value", master_billing_account="master_billing_account_value", ) - response = client.update_billing_account(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.UpdateBillingAccountRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_billing.BillingAccount) - assert response.name == "name_value" - assert response.open_ is True - assert response.display_name == "display_name_value" - assert response.master_billing_account == "master_billing_account_value" @@ -996,7 +993,7 @@ def test_update_billing_account_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1006,7 +1003,6 @@ def test_update_billing_account_empty_call(): client.update_billing_account() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.UpdateBillingAccountRequest() @@ -1016,7 +1012,7 @@ async def test_update_billing_account_async( request_type=cloud_billing.UpdateBillingAccountRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1036,24 +1032,18 @@ async def test_update_billing_account_async( master_billing_account="master_billing_account_value", ) ) - response = await client.update_billing_account(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.UpdateBillingAccountRequest() # Establish that the response is the type that we expect. assert isinstance(response, cloud_billing.BillingAccount) - assert response.name == "name_value" - assert response.open_ is True - assert response.display_name == "display_name_value" - assert response.master_billing_account == "master_billing_account_value" @@ -1063,11 +1053,12 @@ async def test_update_billing_account_async_from_dict(): def test_update_billing_account_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = cloud_billing.UpdateBillingAccountRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1075,7 +1066,6 @@ def test_update_billing_account_field_headers(): type(client.transport.update_billing_account), "__call__" ) as call: call.return_value = cloud_billing.BillingAccount() - client.update_billing_account(request) # Establish that the underlying gRPC stub method was called. @@ -1090,11 +1080,12 @@ def test_update_billing_account_field_headers(): @pytest.mark.asyncio async def test_update_billing_account_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = cloud_billing.UpdateBillingAccountRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1104,7 +1095,6 @@ async def test_update_billing_account_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_billing.BillingAccount() ) - await client.update_billing_account(request) # Establish that the underlying gRPC stub method was called. @@ -1118,7 +1108,7 @@ async def test_update_billing_account_field_headers_async(): def test_update_billing_account_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1126,7 +1116,6 @@ def test_update_billing_account_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_billing.BillingAccount() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_billing_account( @@ -1137,14 +1126,12 @@ def test_update_billing_account_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].account == cloud_billing.BillingAccount(name="name_value") def test_update_billing_account_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1158,7 +1145,7 @@ def test_update_billing_account_flattened_error(): @pytest.mark.asyncio async def test_update_billing_account_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1180,15 +1167,13 @@ async def test_update_billing_account_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].account == cloud_billing.BillingAccount(name="name_value") @pytest.mark.asyncio async def test_update_billing_account_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1204,7 +1189,7 @@ def test_create_billing_account( transport: str = "grpc", request_type=cloud_billing.CreateBillingAccountRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1222,25 +1207,18 @@ def test_create_billing_account( display_name="display_name_value", master_billing_account="master_billing_account_value", ) - response = client.create_billing_account(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.CreateBillingAccountRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_billing.BillingAccount) - assert response.name == "name_value" - assert response.open_ is True - assert response.display_name == "display_name_value" - assert response.master_billing_account == "master_billing_account_value" @@ -1252,7 +1230,7 @@ def test_create_billing_account_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1262,7 +1240,6 @@ def test_create_billing_account_empty_call(): client.create_billing_account() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.CreateBillingAccountRequest() @@ -1272,7 +1249,7 @@ async def test_create_billing_account_async( request_type=cloud_billing.CreateBillingAccountRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1292,24 +1269,18 @@ async def test_create_billing_account_async( master_billing_account="master_billing_account_value", ) ) - response = await client.create_billing_account(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.CreateBillingAccountRequest() # Establish that the response is the type that we expect. assert isinstance(response, cloud_billing.BillingAccount) - assert response.name == "name_value" - assert response.open_ is True - assert response.display_name == "display_name_value" - assert response.master_billing_account == "master_billing_account_value" @@ -1319,7 +1290,7 @@ async def test_create_billing_account_async_from_dict(): def test_create_billing_account_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1327,7 +1298,6 @@ def test_create_billing_account_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_billing.BillingAccount() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.create_billing_account( @@ -1338,14 +1308,13 @@ def test_create_billing_account_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].billing_account == cloud_billing.BillingAccount( name="name_value" ) def test_create_billing_account_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1358,7 +1327,7 @@ def test_create_billing_account_flattened_error(): @pytest.mark.asyncio async def test_create_billing_account_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1380,7 +1349,6 @@ async def test_create_billing_account_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].billing_account == cloud_billing.BillingAccount( name="name_value" ) @@ -1388,7 +1356,7 @@ async def test_create_billing_account_flattened_async(): @pytest.mark.asyncio async def test_create_billing_account_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1403,7 +1371,7 @@ def test_list_project_billing_info( transport: str = "grpc", request_type=cloud_billing.ListProjectBillingInfoRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1418,19 +1386,15 @@ def test_list_project_billing_info( call.return_value = cloud_billing.ListProjectBillingInfoResponse( next_page_token="next_page_token_value", ) - response = client.list_project_billing_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.ListProjectBillingInfoRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListProjectBillingInfoPager) - assert response.next_page_token == "next_page_token_value" @@ -1442,7 +1406,7 @@ def test_list_project_billing_info_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1452,7 +1416,6 @@ def test_list_project_billing_info_empty_call(): client.list_project_billing_info() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.ListProjectBillingInfoRequest() @@ -1462,7 +1425,7 @@ async def test_list_project_billing_info_async( request_type=cloud_billing.ListProjectBillingInfoRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1479,18 +1442,15 @@ async def test_list_project_billing_info_async( next_page_token="next_page_token_value", ) ) - response = await client.list_project_billing_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.ListProjectBillingInfoRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListProjectBillingInfoAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -1500,11 +1460,12 @@ async def test_list_project_billing_info_async_from_dict(): def test_list_project_billing_info_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = cloud_billing.ListProjectBillingInfoRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1512,7 +1473,6 @@ def test_list_project_billing_info_field_headers(): type(client.transport.list_project_billing_info), "__call__" ) as call: call.return_value = cloud_billing.ListProjectBillingInfoResponse() - client.list_project_billing_info(request) # Establish that the underlying gRPC stub method was called. @@ -1527,11 +1487,12 @@ def test_list_project_billing_info_field_headers(): @pytest.mark.asyncio async def test_list_project_billing_info_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = cloud_billing.ListProjectBillingInfoRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1541,7 +1502,6 @@ async def test_list_project_billing_info_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_billing.ListProjectBillingInfoResponse() ) - await client.list_project_billing_info(request) # Establish that the underlying gRPC stub method was called. @@ -1555,7 +1515,7 @@ async def test_list_project_billing_info_field_headers_async(): def test_list_project_billing_info_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1563,7 +1523,6 @@ def test_list_project_billing_info_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_billing.ListProjectBillingInfoResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_project_billing_info(name="name_value",) @@ -1572,12 +1531,11 @@ def test_list_project_billing_info_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_list_project_billing_info_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1589,7 +1547,7 @@ def test_list_project_billing_info_flattened_error(): @pytest.mark.asyncio async def test_list_project_billing_info_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1609,13 +1567,12 @@ async def test_list_project_billing_info_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_list_project_billing_info_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -1626,7 +1583,7 @@ async def test_list_project_billing_info_flattened_error_async(): def test_list_project_billing_info_pager(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1672,7 +1629,7 @@ def test_list_project_billing_info_pager(): def test_list_project_billing_info_pages(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1710,7 +1667,7 @@ def test_list_project_billing_info_pages(): @pytest.mark.asyncio async def test_list_project_billing_info_async_pager(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1755,7 +1712,7 @@ async def test_list_project_billing_info_async_pager(): @pytest.mark.asyncio async def test_list_project_billing_info_async_pages(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1799,7 +1756,7 @@ def test_get_project_billing_info( transport: str = "grpc", request_type=cloud_billing.GetProjectBillingInfoRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1817,25 +1774,18 @@ def test_get_project_billing_info( billing_account_name="billing_account_name_value", billing_enabled=True, ) - response = client.get_project_billing_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.GetProjectBillingInfoRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_billing.ProjectBillingInfo) - assert response.name == "name_value" - assert response.project_id == "project_id_value" - assert response.billing_account_name == "billing_account_name_value" - assert response.billing_enabled is True @@ -1847,7 +1797,7 @@ def test_get_project_billing_info_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -1857,7 +1807,6 @@ def test_get_project_billing_info_empty_call(): client.get_project_billing_info() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.GetProjectBillingInfoRequest() @@ -1867,7 +1816,7 @@ async def test_get_project_billing_info_async( request_type=cloud_billing.GetProjectBillingInfoRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -1887,24 +1836,18 @@ async def test_get_project_billing_info_async( billing_enabled=True, ) ) - response = await client.get_project_billing_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.GetProjectBillingInfoRequest() # Establish that the response is the type that we expect. assert isinstance(response, cloud_billing.ProjectBillingInfo) - assert response.name == "name_value" - assert response.project_id == "project_id_value" - assert response.billing_account_name == "billing_account_name_value" - assert response.billing_enabled is True @@ -1914,11 +1857,12 @@ async def test_get_project_billing_info_async_from_dict(): def test_get_project_billing_info_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = cloud_billing.GetProjectBillingInfoRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1926,7 +1870,6 @@ def test_get_project_billing_info_field_headers(): type(client.transport.get_project_billing_info), "__call__" ) as call: call.return_value = cloud_billing.ProjectBillingInfo() - client.get_project_billing_info(request) # Establish that the underlying gRPC stub method was called. @@ -1941,11 +1884,12 @@ def test_get_project_billing_info_field_headers(): @pytest.mark.asyncio async def test_get_project_billing_info_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = cloud_billing.GetProjectBillingInfoRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -1955,7 +1899,6 @@ async def test_get_project_billing_info_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_billing.ProjectBillingInfo() ) - await client.get_project_billing_info(request) # Establish that the underlying gRPC stub method was called. @@ -1969,7 +1912,7 @@ async def test_get_project_billing_info_field_headers_async(): def test_get_project_billing_info_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -1977,7 +1920,6 @@ def test_get_project_billing_info_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_billing.ProjectBillingInfo() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_project_billing_info(name="name_value",) @@ -1986,12 +1928,11 @@ def test_get_project_billing_info_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" def test_get_project_billing_info_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2003,7 +1944,7 @@ def test_get_project_billing_info_flattened_error(): @pytest.mark.asyncio async def test_get_project_billing_info_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2023,13 +1964,12 @@ async def test_get_project_billing_info_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_project_billing_info_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2043,7 +1983,7 @@ def test_update_project_billing_info( transport: str = "grpc", request_type=cloud_billing.UpdateProjectBillingInfoRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2061,25 +2001,18 @@ def test_update_project_billing_info( billing_account_name="billing_account_name_value", billing_enabled=True, ) - response = client.update_project_billing_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.UpdateProjectBillingInfoRequest() # Establish that the response is the type that we expect. - assert isinstance(response, cloud_billing.ProjectBillingInfo) - assert response.name == "name_value" - assert response.project_id == "project_id_value" - assert response.billing_account_name == "billing_account_name_value" - assert response.billing_enabled is True @@ -2091,7 +2024,7 @@ def test_update_project_billing_info_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2101,7 +2034,6 @@ def test_update_project_billing_info_empty_call(): client.update_project_billing_info() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.UpdateProjectBillingInfoRequest() @@ -2111,7 +2043,7 @@ async def test_update_project_billing_info_async( request_type=cloud_billing.UpdateProjectBillingInfoRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2131,24 +2063,18 @@ async def test_update_project_billing_info_async( billing_enabled=True, ) ) - response = await client.update_project_billing_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_billing.UpdateProjectBillingInfoRequest() # Establish that the response is the type that we expect. assert isinstance(response, cloud_billing.ProjectBillingInfo) - assert response.name == "name_value" - assert response.project_id == "project_id_value" - assert response.billing_account_name == "billing_account_name_value" - assert response.billing_enabled is True @@ -2158,11 +2084,12 @@ async def test_update_project_billing_info_async_from_dict(): def test_update_project_billing_info_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = cloud_billing.UpdateProjectBillingInfoRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2170,7 +2097,6 @@ def test_update_project_billing_info_field_headers(): type(client.transport.update_project_billing_info), "__call__" ) as call: call.return_value = cloud_billing.ProjectBillingInfo() - client.update_project_billing_info(request) # Establish that the underlying gRPC stub method was called. @@ -2185,11 +2111,12 @@ def test_update_project_billing_info_field_headers(): @pytest.mark.asyncio async def test_update_project_billing_info_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = cloud_billing.UpdateProjectBillingInfoRequest() + request.name = "name/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2199,7 +2126,6 @@ async def test_update_project_billing_info_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_billing.ProjectBillingInfo() ) - await client.update_project_billing_info(request) # Establish that the underlying gRPC stub method was called. @@ -2213,7 +2139,7 @@ async def test_update_project_billing_info_field_headers_async(): def test_update_project_billing_info_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2221,7 +2147,6 @@ def test_update_project_billing_info_flattened(): ) as call: # Designate an appropriate return value for the call. call.return_value = cloud_billing.ProjectBillingInfo() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_project_billing_info( @@ -2233,16 +2158,14 @@ def test_update_project_billing_info_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].project_billing_info == cloud_billing.ProjectBillingInfo( name="name_value" ) def test_update_project_billing_info_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2256,7 +2179,7 @@ def test_update_project_billing_info_flattened_error(): @pytest.mark.asyncio async def test_update_project_billing_info_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -2279,9 +2202,7 @@ async def test_update_project_billing_info_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - assert args[0].project_billing_info == cloud_billing.ProjectBillingInfo( name="name_value" ) @@ -2289,7 +2210,7 @@ async def test_update_project_billing_info_flattened_async(): @pytest.mark.asyncio async def test_update_project_billing_info_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -2302,10 +2223,10 @@ async def test_update_project_billing_info_flattened_error_async(): def test_get_iam_policy( - transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2315,22 +2236,17 @@ def test_get_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.get_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] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2342,7 +2258,7 @@ def test_get_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2350,16 +2266,15 @@ def test_get_iam_policy_empty_call(): client.get_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() @pytest.mark.asyncio async def test_get_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.GetIamPolicyRequest ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2370,22 +2285,18 @@ async def test_get_iam_policy_async( with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.get_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] == iam_policy.GetIamPolicyRequest() + assert args[0] == iam_policy_pb2.GetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2395,17 +2306,17 @@ async def test_get_iam_policy_async_from_dict(): def test_get_iam_policy_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2420,17 +2331,17 @@ def test_get_iam_policy_field_headers(): @pytest.mark.asyncio async def test_get_iam_policy_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = iam_policy.GetIamPolicyRequest() + request = iam_policy_pb2.GetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.get_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2444,29 +2355,27 @@ async def test_get_iam_policy_field_headers_async(): def test_get_iam_policy_from_dict_foreign(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.get_iam_policy( request={ "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), + "options": options_pb2.GetPolicyOptions(requested_policy_version=2598), } ) call.assert_called() def test_get_iam_policy_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_iam_policy(resource="resource_value",) @@ -2475,31 +2384,30 @@ def test_get_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_get_iam_policy_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_get_iam_policy_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.get_iam_policy(resource="resource_value",) @@ -2508,27 +2416,26 @@ async def test_get_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_get_iam_policy_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.get_iam_policy( - iam_policy.GetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.GetIamPolicyRequest(), resource="resource_value", ) def test_set_iam_policy( - transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2538,22 +2445,17 @@ def test_set_iam_policy( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy(version=774, etag=b"etag_blob",) - + call.return_value = policy_pb2.Policy(version=774, etag=b"etag_blob",) response = client.set_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] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2565,7 +2467,7 @@ def test_set_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2573,16 +2475,15 @@ def test_set_iam_policy_empty_call(): client.set_iam_policy() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() @pytest.mark.asyncio async def test_set_iam_policy_async( - transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest + transport: str = "grpc_asyncio", request_type=iam_policy_pb2.SetIamPolicyRequest ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2593,22 +2494,18 @@ async def test_set_iam_policy_async( with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - policy.Policy(version=774, etag=b"etag_blob",) + policy_pb2.Policy(version=774, etag=b"etag_blob",) ) - response = await client.set_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] == iam_policy.SetIamPolicyRequest() + assert args[0] == iam_policy_pb2.SetIamPolicyRequest() # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - + assert isinstance(response, policy_pb2.Policy) assert response.version == 774 - assert response.etag == b"etag_blob" @@ -2618,17 +2515,17 @@ async def test_set_iam_policy_async_from_dict(): def test_set_iam_policy_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2643,17 +2540,17 @@ def test_set_iam_policy_field_headers(): @pytest.mark.asyncio async def test_set_iam_policy_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = iam_policy.SetIamPolicyRequest() + request = iam_policy_pb2.SetIamPolicyRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) - + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) await client.set_iam_policy(request) # Establish that the underlying gRPC stub method was called. @@ -2667,29 +2564,27 @@ async def test_set_iam_policy_field_headers_async(): def test_set_iam_policy_from_dict_foreign(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() response = client.set_iam_policy( request={ "resource": "resource_value", - "policy": policy.Policy(version=774), + "policy": policy_pb2.Policy(version=774), } ) call.assert_called() def test_set_iam_policy_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() - + call.return_value = policy_pb2.Policy() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.set_iam_policy(resource="resource_value",) @@ -2698,31 +2593,30 @@ def test_set_iam_policy_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" def test_set_iam_policy_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) @pytest.mark.asyncio async def test_set_iam_policy_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.set_iam_policy), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = policy.Policy() + call.return_value = policy_pb2.Policy() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(policy_pb2.Policy()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.set_iam_policy(resource="resource_value",) @@ -2731,27 +2625,26 @@ async def test_set_iam_policy_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" @pytest.mark.asyncio async def test_set_iam_policy_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.set_iam_policy( - iam_policy.SetIamPolicyRequest(), resource="resource_value", + iam_policy_pb2.SetIamPolicyRequest(), resource="resource_value", ) def test_test_iam_permissions( - transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc", request_type=iam_policy_pb2.TestIamPermissionsRequest ): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2763,22 +2656,18 @@ def test_test_iam_permissions( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse( + call.return_value = iam_policy_pb2.TestIamPermissionsResponse( permissions=["permissions_value"], ) - response = client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2790,7 +2679,7 @@ def test_test_iam_permissions_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 = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -2800,16 +2689,16 @@ def test_test_iam_permissions_empty_call(): client.test_iam_permissions() call.assert_called() _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() @pytest.mark.asyncio async def test_test_iam_permissions_async( - transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest + transport: str = "grpc_asyncio", + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = CloudBillingAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -2822,20 +2711,19 @@ async def test_test_iam_permissions_async( ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse(permissions=["permissions_value"],) + iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) ) - response = await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - - assert args[0] == iam_policy.TestIamPermissionsRequest() + assert args[0] == iam_policy_pb2.TestIamPermissionsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) assert response.permissions == ["permissions_value"] @@ -2845,19 +2733,19 @@ async def test_test_iam_permissions_async_from_dict(): def test_test_iam_permissions_field_headers(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -2872,11 +2760,12 @@ def test_test_iam_permissions_field_headers(): @pytest.mark.asyncio async def test_test_iam_permissions_field_headers_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(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 = iam_policy.TestIamPermissionsRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() + request.resource = "resource/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -2884,9 +2773,8 @@ async def test_test_iam_permissions_field_headers_async(): type(client.transport.test_iam_permissions), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) - await client.test_iam_permissions(request) # Establish that the underlying gRPC stub method was called. @@ -2900,14 +2788,13 @@ async def test_test_iam_permissions_field_headers_async(): def test_test_iam_permissions_from_dict_foreign(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() response = client.test_iam_permissions( request={ "resource": "resource_value", @@ -2918,15 +2805,14 @@ def test_test_iam_permissions_from_dict_foreign(): def test_test_iam_permissions_flattened(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() - + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.test_iam_permissions( @@ -2937,20 +2823,18 @@ def test_test_iam_permissions_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] def test_test_iam_permissions_flattened_error(): - client = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -2958,17 +2842,17 @@ def test_test_iam_permissions_flattened_error(): @pytest.mark.asyncio async def test_test_iam_permissions_flattened_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( type(client.transport.test_iam_permissions), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = iam_policy.TestIamPermissionsResponse() + call.return_value = iam_policy_pb2.TestIamPermissionsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - iam_policy.TestIamPermissionsResponse() + iam_policy_pb2.TestIamPermissionsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. @@ -2980,21 +2864,19 @@ async def test_test_iam_permissions_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0].resource == "resource_value" - assert args[0].permissions == ["permissions_value"] @pytest.mark.asyncio async def test_test_iam_permissions_flattened_error_async(): - client = CloudBillingAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): await client.test_iam_permissions( - iam_policy.TestIamPermissionsRequest(), + iam_policy_pb2.TestIamPermissionsRequest(), resource="resource_value", permissions=["permissions_value"], ) @@ -3003,16 +2885,16 @@ async def test_test_iam_permissions_flattened_error_async(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudBillingGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudBillingClient( - 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.CloudBillingGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudBillingClient( @@ -3022,7 +2904,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.CloudBillingGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudBillingClient( @@ -3033,7 +2915,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.CloudBillingGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = CloudBillingClient(transport=transport) assert client.transport is transport @@ -3042,13 +2924,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CloudBillingGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.CloudBillingGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -3063,23 +2945,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 = CloudBillingClient(credentials=credentials.AnonymousCredentials(),) + client = CloudBillingClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.CloudBillingGrpcTransport,) def test_cloud_billing_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.CloudBillingTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -3091,7 +2973,7 @@ def test_cloud_billing_base_transport(): ) as Transport: Transport.return_value = None transport = transports.CloudBillingTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -3113,15 +2995,37 @@ def test_cloud_billing_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_cloud_billing_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.billing_v1.services.cloud_billing.transports.CloudBillingTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudBillingTransport( + 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_cloud_billing_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.billing_v1.services.cloud_billing.transports.CloudBillingTransport._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.CloudBillingTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -3134,19 +3038,33 @@ def test_cloud_billing_base_transport_with_credentials_file(): def test_cloud_billing_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.billing_v1.services.cloud_billing.transports.CloudBillingTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudBillingTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_cloud_billing_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) + CloudBillingClient() + 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_cloud_billing_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) CloudBillingClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -3154,26 +3072,162 @@ def test_cloud_billing_auth_adc(): ) -def test_cloud_billing_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudBillingGrpcTransport, + transports.CloudBillingGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_cloud_billing_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.CloudBillingGrpcTransport( - 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.CloudBillingGrpcTransport, + transports.CloudBillingGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_cloud_billing_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.CloudBillingGrpcTransport, grpc_helpers), + (transports.CloudBillingGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_cloud_billing_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( + "cloudbilling.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="cloudbilling.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.CloudBillingGrpcTransport, grpc_helpers), + (transports.CloudBillingGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_billing_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( + "cloudbilling.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.CloudBillingGrpcTransport, grpc_helpers), + (transports.CloudBillingGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_billing_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( + "cloudbilling.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.CloudBillingGrpcTransport, transports.CloudBillingGrpcAsyncIOTransport], ) def test_cloud_billing_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: @@ -3212,7 +3266,7 @@ def test_cloud_billing_grpc_transport_client_cert_source_for_mtls(transport_clas def test_cloud_billing_host_no_port(): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudbilling.googleapis.com" ), @@ -3222,7 +3276,7 @@ def test_cloud_billing_host_no_port(): def test_cloud_billing_host_with_port(): client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudbilling.googleapis.com:8000" ), @@ -3273,9 +3327,9 @@ def test_cloud_billing_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", @@ -3348,7 +3402,6 @@ def test_cloud_billing_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, ) @@ -3369,7 +3422,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "whelk" - expected = "folders/{folder}".format(folder=folder,) actual = CloudBillingClient.common_folder_path(folder) assert expected == actual @@ -3388,7 +3440,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "oyster" - expected = "organizations/{organization}".format(organization=organization,) actual = CloudBillingClient.common_organization_path(organization) assert expected == actual @@ -3407,7 +3458,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "cuttlefish" - expected = "projects/{project}".format(project=project,) actual = CloudBillingClient.common_project_path(project) assert expected == actual @@ -3427,7 +3477,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, ) @@ -3454,7 +3503,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.CloudBillingTransport, "_prep_wrapped_messages" ) as prep: client = CloudBillingClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -3463,6 +3512,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = CloudBillingClient.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/billing_v1/test_cloud_catalog.py b/tests/unit/gapic/billing_v1/test_cloud_catalog.py index 26d0354..c9f448b 100644 --- a/tests/unit/gapic/billing_v1/test_cloud_catalog.py +++ b/tests/unit/gapic/billing_v1/test_cloud_catalog.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.billing_v1.services.cloud_catalog import CloudCatalogAsyncClient from google.cloud.billing_v1.services.cloud_catalog import CloudCatalogClient from google.cloud.billing_v1.services.cloud_catalog import pagers from google.cloud.billing_v1.services.cloud_catalog import transports +from google.cloud.billing_v1.services.cloud_catalog.transports.base import ( + _API_CORE_VERSION, +) +from google.cloud.billing_v1.services.cloud_catalog.transports.base import ( + _GOOGLE_AUTH_VERSION, +) from google.cloud.billing_v1.types import cloud_catalog 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(): @@ -84,7 +113,7 @@ def test__get_default_mtls_endpoint(): @pytest.mark.parametrize("client_class", [CloudCatalogClient, CloudCatalogAsyncClient,]) def test_cloud_catalog_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_cloud_catalog_client_from_service_account_info(client_class): @pytest.mark.parametrize("client_class", [CloudCatalogClient, CloudCatalogAsyncClient,]) def test_cloud_catalog_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_cloud_catalog_client_client_options( ): # Check that if channel is provided we won't create a new one. with mock.patch.object(CloudCatalogClient, "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_list_services( transport: str = "grpc", request_type=cloud_catalog.ListServicesRequest ): client = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -447,19 +476,15 @@ def test_list_services( call.return_value = cloud_catalog.ListServicesResponse( next_page_token="next_page_token_value", ) - response = client.list_services(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_catalog.ListServicesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListServicesPager) - assert response.next_page_token == "next_page_token_value" @@ -471,7 +496,7 @@ def test_list_services_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 = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -479,7 +504,6 @@ def test_list_services_empty_call(): client.list_services() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_catalog.ListServicesRequest() @@ -488,7 +512,7 @@ async def test_list_services_async( transport: str = "grpc_asyncio", request_type=cloud_catalog.ListServicesRequest ): client = CloudCatalogAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -501,18 +525,15 @@ async def test_list_services_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_catalog.ListServicesResponse(next_page_token="next_page_token_value",) ) - response = await client.list_services(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_catalog.ListServicesRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListServicesAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -522,7 +543,7 @@ async def test_list_services_async_from_dict(): def test_list_services_pager(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_services), "__call__") as call: @@ -557,7 +578,7 @@ def test_list_services_pager(): def test_list_services_pages(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_services), "__call__") as call: @@ -587,7 +608,7 @@ def test_list_services_pages(): @pytest.mark.asyncio async def test_list_services_async_pager(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -624,7 +645,7 @@ async def test_list_services_async_pager(): @pytest.mark.asyncio async def test_list_services_async_pages(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -658,7 +679,7 @@ async def test_list_services_async_pages(): def test_list_skus(transport: str = "grpc", request_type=cloud_catalog.ListSkusRequest): client = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -671,19 +692,15 @@ def test_list_skus(transport: str = "grpc", request_type=cloud_catalog.ListSkusR call.return_value = cloud_catalog.ListSkusResponse( next_page_token="next_page_token_value", ) - response = client.list_skus(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == cloud_catalog.ListSkusRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSkusPager) - assert response.next_page_token == "next_page_token_value" @@ -695,7 +712,7 @@ def test_list_skus_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 = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), transport="grpc", + credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. @@ -703,7 +720,6 @@ def test_list_skus_empty_call(): client.list_skus() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == cloud_catalog.ListSkusRequest() @@ -712,7 +728,7 @@ async def test_list_skus_async( transport: str = "grpc_asyncio", request_type=cloud_catalog.ListSkusRequest ): client = CloudCatalogAsyncClient( - credentials=credentials.AnonymousCredentials(), transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Everything is optional in proto3 as far as the runtime is concerned, @@ -725,18 +741,15 @@ async def test_list_skus_async( call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_catalog.ListSkusResponse(next_page_token="next_page_token_value",) ) - response = await client.list_skus(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == cloud_catalog.ListSkusRequest() # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListSkusAsyncPager) - assert response.next_page_token == "next_page_token_value" @@ -746,17 +759,17 @@ async def test_list_skus_async_from_dict(): def test_list_skus_field_headers(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogClient(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 = cloud_catalog.ListSkusRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_skus), "__call__") as call: call.return_value = cloud_catalog.ListSkusResponse() - client.list_skus(request) # Establish that the underlying gRPC stub method was called. @@ -771,11 +784,12 @@ def test_list_skus_field_headers(): @pytest.mark.asyncio async def test_list_skus_field_headers_async(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogAsyncClient(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 = cloud_catalog.ListSkusRequest() + request.parent = "parent/value" # Mock the actual call within the gRPC stub, and fake the request. @@ -783,7 +797,6 @@ async def test_list_skus_field_headers_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( cloud_catalog.ListSkusResponse() ) - await client.list_skus(request) # Establish that the underlying gRPC stub method was called. @@ -797,13 +810,12 @@ async def test_list_skus_field_headers_async(): def test_list_skus_flattened(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_skus), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = cloud_catalog.ListSkusResponse() - # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.list_skus(parent="parent_value",) @@ -812,12 +824,11 @@ def test_list_skus_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" def test_list_skus_flattened_error(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -829,7 +840,7 @@ def test_list_skus_flattened_error(): @pytest.mark.asyncio async def test_list_skus_flattened_async(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_skus), "__call__") as call: @@ -847,13 +858,12 @@ async def test_list_skus_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_skus_flattened_error_async(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogAsyncClient(credentials=ga_credentials.AnonymousCredentials(),) # Attempting to call a method with both a request object and flattened # fields is an error. @@ -864,7 +874,7 @@ async def test_list_skus_flattened_error_async(): def test_list_skus_pager(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_skus), "__call__") as call: @@ -898,7 +908,7 @@ def test_list_skus_pager(): def test_list_skus_pages(): - client = CloudCatalogClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_skus), "__call__") as call: @@ -924,7 +934,7 @@ def test_list_skus_pages(): @pytest.mark.asyncio async def test_list_skus_async_pager(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -957,7 +967,7 @@ async def test_list_skus_async_pager(): @pytest.mark.asyncio async def test_list_skus_async_pages(): - client = CloudCatalogAsyncClient(credentials=credentials.AnonymousCredentials,) + client = CloudCatalogAsyncClient(credentials=ga_credentials.AnonymousCredentials,) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( @@ -988,16 +998,16 @@ async def test_list_skus_async_pages(): def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudCatalogGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudCatalogClient( - 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.CloudCatalogGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudCatalogClient( @@ -1007,7 +1017,7 @@ def test_credentials_transport_error(): # It is an error to provide scopes and a transport instance. transport = transports.CloudCatalogGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = CloudCatalogClient( @@ -1018,7 +1028,7 @@ def test_credentials_transport_error(): def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.CloudCatalogGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) client = CloudCatalogClient(transport=transport) assert client.transport is transport @@ -1027,13 +1037,13 @@ def test_transport_instance(): def test_transport_get_channel(): # A client may be instantiated with a custom transport instance. transport = transports.CloudCatalogGrpcTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel transport = transports.CloudCatalogGrpcAsyncIOTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) channel = transport.grpc_channel assert channel @@ -1048,23 +1058,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 = CloudCatalogClient(credentials=credentials.AnonymousCredentials(),) + client = CloudCatalogClient(credentials=ga_credentials.AnonymousCredentials(),) assert isinstance(client.transport, transports.CloudCatalogGrpcTransport,) def test_cloud_catalog_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.CloudCatalogTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) @@ -1076,7 +1086,7 @@ def test_cloud_catalog_base_transport(): ) as Transport: Transport.return_value = None transport = transports.CloudCatalogTransport( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly @@ -1090,15 +1100,37 @@ def test_cloud_catalog_base_transport(): getattr(transport, method)(request=object()) +@requires_google_auth_gte_1_25_0 def test_cloud_catalog_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.billing_v1.services.cloud_catalog.transports.CloudCatalogTransport._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.CloudCatalogTransport( + 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_cloud_catalog_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.billing_v1.services.cloud_catalog.transports.CloudCatalogTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudCatalogTransport( credentials_file="credentials.json", quota_project_id="octopus", ) @@ -1111,19 +1143,33 @@ def test_cloud_catalog_base_transport_with_credentials_file(): def test_cloud_catalog_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.billing_v1.services.cloud_catalog.transports.CloudCatalogTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None - adc.return_value = (credentials.AnonymousCredentials(), None) + adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.CloudCatalogTransport() adc.assert_called_once() +@requires_google_auth_gte_1_25_0 def test_cloud_catalog_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) + CloudCatalogClient() + 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_cloud_catalog_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) CloudCatalogClient() adc.assert_called_once_with( scopes=("https://www.googleapis.com/auth/cloud-platform",), @@ -1131,26 +1177,162 @@ def test_cloud_catalog_auth_adc(): ) -def test_cloud_catalog_transport_auth_adc(): +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudCatalogGrpcTransport, + transports.CloudCatalogGrpcAsyncIOTransport, + ], +) +@requires_google_auth_gte_1_25_0 +def test_cloud_catalog_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.CloudCatalogGrpcTransport( - 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.CloudCatalogGrpcTransport, + transports.CloudCatalogGrpcAsyncIOTransport, + ], +) +@requires_google_auth_lt_1_25_0 +def test_cloud_catalog_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.CloudCatalogGrpcTransport, grpc_helpers), + (transports.CloudCatalogGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_gte_1_26_0 +def test_cloud_catalog_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( + "cloudbilling.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="cloudbilling.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.CloudCatalogGrpcTransport, grpc_helpers), + (transports.CloudCatalogGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_catalog_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( + "cloudbilling.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.CloudCatalogGrpcTransport, grpc_helpers), + (transports.CloudCatalogGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +@requires_api_core_lt_1_26_0 +def test_cloud_catalog_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( + "cloudbilling.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.CloudCatalogGrpcTransport, transports.CloudCatalogGrpcAsyncIOTransport], ) def test_cloud_catalog_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: @@ -1189,7 +1371,7 @@ def test_cloud_catalog_grpc_transport_client_cert_source_for_mtls(transport_clas def test_cloud_catalog_host_no_port(): client = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudbilling.googleapis.com" ), @@ -1199,7 +1381,7 @@ def test_cloud_catalog_host_no_port(): def test_cloud_catalog_host_with_port(): client = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), + credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="cloudbilling.googleapis.com:8000" ), @@ -1250,9 +1432,9 @@ def test_cloud_catalog_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", @@ -1325,7 +1507,6 @@ def test_cloud_catalog_transport_channel_mtls_with_adc(transport_class): def test_service_path(): service = "squid" - expected = "services/{service}".format(service=service,) actual = CloudCatalogClient.service_path(service) assert expected == actual @@ -1345,7 +1526,6 @@ def test_parse_service_path(): def test_sku_path(): service = "whelk" sku = "octopus" - expected = "services/{service}/skus/{sku}".format(service=service, sku=sku,) actual = CloudCatalogClient.sku_path(service, sku) assert expected == actual @@ -1365,7 +1545,6 @@ def test_parse_sku_path(): def test_common_billing_account_path(): billing_account = "cuttlefish" - expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -1386,7 +1565,6 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): folder = "winkle" - expected = "folders/{folder}".format(folder=folder,) actual = CloudCatalogClient.common_folder_path(folder) assert expected == actual @@ -1405,7 +1583,6 @@ def test_parse_common_folder_path(): def test_common_organization_path(): organization = "scallop" - expected = "organizations/{organization}".format(organization=organization,) actual = CloudCatalogClient.common_organization_path(organization) assert expected == actual @@ -1424,7 +1601,6 @@ def test_parse_common_organization_path(): def test_common_project_path(): project = "squid" - expected = "projects/{project}".format(project=project,) actual = CloudCatalogClient.common_project_path(project) assert expected == actual @@ -1444,7 +1620,6 @@ def test_parse_common_project_path(): def test_common_location_path(): project = "whelk" location = "octopus" - expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) @@ -1471,7 +1646,7 @@ def test_client_withDEFAULT_CLIENT_INFO(): transports.CloudCatalogTransport, "_prep_wrapped_messages" ) as prep: client = CloudCatalogClient( - credentials=credentials.AnonymousCredentials(), client_info=client_info, + credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) @@ -1480,6 +1655,6 @@ def test_client_withDEFAULT_CLIENT_INFO(): ) as prep: transport_class = CloudCatalogClient.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)