From 96314b4f42494fb657b288c597477ce0caf0124c Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Thu, 9 Feb 2023 11:54:48 -0500 Subject: [PATCH] feat: enable "rest" transport in Python for services supporting numeric enums (#237) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: enable "rest" transport in Python for services supporting numeric enums PiperOrigin-RevId: 508143576 Source-Link: https://github.com/googleapis/googleapis/commit/7a702a989db3b413f39ff8994ca53fb38b6928c2 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6ad1279c0e7aa787ac6b66c9fd4a210692edffcd Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmFkMTI3OWMwZTdhYTc4N2FjNmI2NmM5ZmQ0YTIxMDY5MmVkZmZjZCJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md --------- Co-authored-by: Owl Bot --- .../cloud/billing_v1/gapic_metadata.json | 70 + .../services/cloud_billing/client.py | 2 + .../cloud_billing/transports/__init__.py | 4 + .../services/cloud_billing/transports/rest.py | 1669 +++++++++ .../services/cloud_catalog/client.py | 2 + .../cloud_catalog/transports/__init__.py | 4 + .../services/cloud_catalog/transports/rest.py | 420 +++ .../gapic/billing_v1/test_cloud_billing.py | 3170 ++++++++++++++++- .../gapic/billing_v1/test_cloud_catalog.py | 602 +++- 9 files changed, 5780 insertions(+), 163 deletions(-) create mode 100644 packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/rest.py create mode 100644 packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/rest.py diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/gapic_metadata.json b/packages/google-cloud-billing/google/cloud/billing_v1/gapic_metadata.json index 94940c7b70f2..d7464c62897f 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/gapic_metadata.json +++ b/packages/google-cloud-billing/google/cloud/billing_v1/gapic_metadata.json @@ -116,6 +116,61 @@ ] } } + }, + "rest": { + "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" + ] + } + } } } }, @@ -150,6 +205,21 @@ ] } } + }, + "rest": { + "libraryClient": "CloudCatalogClient", + "rpcs": { + "ListServices": { + "methods": [ + "list_services" + ] + }, + "ListSkus": { + "methods": [ + "list_skus" + ] + } + } } } } diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py index 639ab4213790..22a0ad017a8d 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/client.py @@ -55,6 +55,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, CloudBillingTransport from .transports.grpc import CloudBillingGrpcTransport from .transports.grpc_asyncio import CloudBillingGrpcAsyncIOTransport +from .transports.rest import CloudBillingRestTransport class CloudBillingClientMeta(type): @@ -68,6 +69,7 @@ class CloudBillingClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[CloudBillingTransport]] _transport_registry["grpc"] = CloudBillingGrpcTransport _transport_registry["grpc_asyncio"] = CloudBillingGrpcAsyncIOTransport + _transport_registry["rest"] = CloudBillingRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/__init__.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/__init__.py index f016cac719fa..a42606dc7a76 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/__init__.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/__init__.py @@ -19,14 +19,18 @@ from .base import CloudBillingTransport from .grpc import CloudBillingGrpcTransport from .grpc_asyncio import CloudBillingGrpcAsyncIOTransport +from .rest import CloudBillingRestInterceptor, CloudBillingRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[CloudBillingTransport]] _transport_registry["grpc"] = CloudBillingGrpcTransport _transport_registry["grpc_asyncio"] = CloudBillingGrpcAsyncIOTransport +_transport_registry["rest"] = CloudBillingRestTransport __all__ = ( "CloudBillingTransport", "CloudBillingGrpcTransport", "CloudBillingGrpcAsyncIOTransport", + "CloudBillingRestTransport", + "CloudBillingRestInterceptor", ) diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/rest.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/rest.py new file mode 100644 index 000000000000..8f191c8e854e --- /dev/null +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_billing/transports/rest.py @@ -0,0 +1,1669 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore + +from google.cloud.billing_v1.types import cloud_billing + +from .base import CloudBillingTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CloudBillingRestInterceptor: + """Interceptor for CloudBilling. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CloudBillingRestTransport. + + .. code-block:: python + class MyCustomCloudBillingInterceptor(CloudBillingRestInterceptor): + def pre_create_billing_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_billing_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_billing_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_billing_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_project_billing_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_project_billing_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_billing_accounts(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_billing_accounts(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_project_billing_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_project_billing_info(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_set_iam_policy(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_set_iam_policy(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_test_iam_permissions(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_test_iam_permissions(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_billing_account(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_billing_account(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_project_billing_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_project_billing_info(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CloudBillingRestTransport(interceptor=MyCustomCloudBillingInterceptor()) + client = CloudBillingClient(transport=transport) + + + """ + + def pre_create_billing_account( + self, + request: cloud_billing.CreateBillingAccountRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_billing.CreateBillingAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_billing_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_create_billing_account( + self, response: cloud_billing.BillingAccount + ) -> cloud_billing.BillingAccount: + """Post-rpc interceptor for create_billing_account + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_get_billing_account( + self, + request: cloud_billing.GetBillingAccountRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_billing.GetBillingAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_billing_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_get_billing_account( + self, response: cloud_billing.BillingAccount + ) -> cloud_billing.BillingAccount: + """Post-rpc interceptor for get_billing_account + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_get_iam_policy( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.GetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_get_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for get_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_get_project_billing_info( + self, + request: cloud_billing.GetProjectBillingInfoRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_billing.GetProjectBillingInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_project_billing_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_get_project_billing_info( + self, response: cloud_billing.ProjectBillingInfo + ) -> cloud_billing.ProjectBillingInfo: + """Post-rpc interceptor for get_project_billing_info + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_list_billing_accounts( + self, + request: cloud_billing.ListBillingAccountsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_billing.ListBillingAccountsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_billing_accounts + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_list_billing_accounts( + self, response: cloud_billing.ListBillingAccountsResponse + ) -> cloud_billing.ListBillingAccountsResponse: + """Post-rpc interceptor for list_billing_accounts + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_list_project_billing_info( + self, + request: cloud_billing.ListProjectBillingInfoRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_billing.ListProjectBillingInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_project_billing_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_list_project_billing_info( + self, response: cloud_billing.ListProjectBillingInfoResponse + ) -> cloud_billing.ListProjectBillingInfoResponse: + """Post-rpc interceptor for list_project_billing_info + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_set_iam_policy( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.SetIamPolicyRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_set_iam_policy(self, response: policy_pb2.Policy) -> policy_pb2.Policy: + """Post-rpc interceptor for set_iam_policy + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_test_iam_permissions( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[iam_policy_pb2.TestIamPermissionsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_test_iam_permissions( + self, response: iam_policy_pb2.TestIamPermissionsResponse + ) -> iam_policy_pb2.TestIamPermissionsResponse: + """Post-rpc interceptor for test_iam_permissions + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_update_billing_account( + self, + request: cloud_billing.UpdateBillingAccountRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_billing.UpdateBillingAccountRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_billing_account + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_update_billing_account( + self, response: cloud_billing.BillingAccount + ) -> cloud_billing.BillingAccount: + """Post-rpc interceptor for update_billing_account + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + def pre_update_project_billing_info( + self, + request: cloud_billing.UpdateProjectBillingInfoRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + cloud_billing.UpdateProjectBillingInfoRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for update_project_billing_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudBilling server. + """ + return request, metadata + + def post_update_project_billing_info( + self, response: cloud_billing.ProjectBillingInfo + ) -> cloud_billing.ProjectBillingInfo: + """Post-rpc interceptor for update_project_billing_info + + Override in a subclass to manipulate the response + after it is returned by the CloudBilling server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CloudBillingRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CloudBillingRestInterceptor + + +class CloudBillingRestTransport(CloudBillingTransport): + """REST backend transport for CloudBilling. + + Retrieves the Google Cloud Console billing accounts and + associates them with projects. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "cloudbilling.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CloudBillingRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CloudBillingRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateBillingAccount(CloudBillingRestStub): + def __hash__(self): + return hash("CreateBillingAccount") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_billing.CreateBillingAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.BillingAccount: + r"""Call the create billing account method over HTTP. + + Args: + request (~.cloud_billing.CreateBillingAccountRequest): + The request object. Request message for ``CreateBillingAccount``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.BillingAccount: + A billing account in the `Google Cloud + Console `__. You can + assign a billing account to one or more projects. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/billingAccounts", + "body": "billing_account", + }, + ] + request, metadata = self._interceptor.pre_create_billing_account( + request, metadata + ) + pb_request = cloud_billing.CreateBillingAccountRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.BillingAccount() + pb_resp = cloud_billing.BillingAccount.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_billing_account(resp) + return resp + + class _GetBillingAccount(CloudBillingRestStub): + def __hash__(self): + return hash("GetBillingAccount") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_billing.GetBillingAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.BillingAccount: + r"""Call the get billing account method over HTTP. + + Args: + request (~.cloud_billing.GetBillingAccountRequest): + The request object. Request message for ``GetBillingAccount``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.BillingAccount: + A billing account in the `Google Cloud + Console `__. You can + assign a billing account to one or more projects. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=billingAccounts/*}", + }, + ] + request, metadata = self._interceptor.pre_get_billing_account( + request, metadata + ) + pb_request = cloud_billing.GetBillingAccountRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.BillingAccount() + pb_resp = cloud_billing.BillingAccount.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_billing_account(resp) + return resp + + class _GetIamPolicy(CloudBillingRestStub): + def __hash__(self): + return hash("GetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: iam_policy_pb2.GetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Call the get iam policy method over HTTP. + + Args: + request (~.iam_policy_pb2.GetIamPolicyRequest): + The request object. Request message for ``GetIamPolicy`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{resource=billingAccounts/*}:getIamPolicy", + }, + ] + request, metadata = self._interceptor.pre_get_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_iam_policy(resp) + return resp + + class _GetProjectBillingInfo(CloudBillingRestStub): + def __hash__(self): + return hash("GetProjectBillingInfo") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_billing.GetProjectBillingInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.ProjectBillingInfo: + r"""Call the get project billing info method over HTTP. + + Args: + request (~.cloud_billing.GetProjectBillingInfoRequest): + The request object. Request message for ``GetProjectBillingInfo``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.ProjectBillingInfo: + Encapsulation of billing information + for a Google Cloud Console project. A + project has at most one associated + billing account at a time (but a billing + account can be assigned to multiple + projects). + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*}/billingInfo", + }, + ] + request, metadata = self._interceptor.pre_get_project_billing_info( + request, metadata + ) + pb_request = cloud_billing.GetProjectBillingInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.ProjectBillingInfo() + pb_resp = cloud_billing.ProjectBillingInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_project_billing_info(resp) + return resp + + class _ListBillingAccounts(CloudBillingRestStub): + def __hash__(self): + return hash("ListBillingAccounts") + + def __call__( + self, + request: cloud_billing.ListBillingAccountsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.ListBillingAccountsResponse: + r"""Call the list billing accounts method over HTTP. + + Args: + request (~.cloud_billing.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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.ListBillingAccountsResponse: + Response message for ``ListBillingAccounts``. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/billingAccounts", + }, + ] + request, metadata = self._interceptor.pre_list_billing_accounts( + request, metadata + ) + pb_request = cloud_billing.ListBillingAccountsRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.ListBillingAccountsResponse() + pb_resp = cloud_billing.ListBillingAccountsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_billing_accounts(resp) + return resp + + class _ListProjectBillingInfo(CloudBillingRestStub): + def __hash__(self): + return hash("ListProjectBillingInfo") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_billing.ListProjectBillingInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.ListProjectBillingInfoResponse: + r"""Call the list project billing info method over HTTP. + + Args: + request (~.cloud_billing.ListProjectBillingInfoRequest): + The request object. Request message for ``ListProjectBillingInfo``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.ListProjectBillingInfoResponse: + Request message for ``ListProjectBillingInfoResponse``. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=billingAccounts/*}/projects", + }, + ] + request, metadata = self._interceptor.pre_list_project_billing_info( + request, metadata + ) + pb_request = cloud_billing.ListProjectBillingInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.ListProjectBillingInfoResponse() + pb_resp = cloud_billing.ListProjectBillingInfoResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_project_billing_info(resp) + return resp + + class _SetIamPolicy(CloudBillingRestStub): + def __hash__(self): + return hash("SetIamPolicy") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: iam_policy_pb2.SetIamPolicyRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_pb2.Policy: + r"""Call the set iam policy method over HTTP. + + Args: + request (~.iam_policy_pb2.SetIamPolicyRequest): + The request object. Request message for ``SetIamPolicy`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy_pb2.Policy: + An Identity and Access Management (IAM) policy, which + specifies access controls for Google Cloud resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members``, or + principals, to a single ``role``. Principals can be user + accounts, service accounts, Google groups, and domains + (such as G Suite). A ``role`` is a named list of + permissions; each ``role`` can be an IAM predefined role + or a user-created custom role. + + For some types of Google Cloud resources, a ``binding`` + can also specify a ``condition``, which is a logical + expression that allows access to a resource only if the + expression evaluates to ``true``. A condition can add + constraints based on attributes of the request, the + resource, or both. To learn which resources support + conditions in their IAM policies, see the `IAM + documentation `__. + + **JSON example:** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": [ + "user:eve@example.com" + ], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", + } + } + ], + "etag": "BwWWja0YfJA=", + "version": 3 + } + + **YAML example:** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + etag: BwWWja0YfJA= + version: 3 + + For a description of IAM and its features, see the `IAM + documentation `__. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=billingAccounts/*}:setIamPolicy", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_set_iam_policy(request, metadata) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = policy_pb2.Policy() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_set_iam_policy(resp) + return resp + + class _TestIamPermissions(CloudBillingRestStub): + def __hash__(self): + return hash("TestIamPermissions") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: iam_policy_pb2.TestIamPermissionsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy_pb2.TestIamPermissionsResponse: + r"""Call the test iam permissions method over HTTP. + + Args: + request (~.iam_policy_pb2.TestIamPermissionsRequest): + The request object. Request message for ``TestIamPermissions`` method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy_pb2.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{resource=billingAccounts/*}:testIamPermissions", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_test_iam_permissions( + request, metadata + ) + pb_request = request + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = iam_policy_pb2.TestIamPermissionsResponse() + pb_resp = resp + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_test_iam_permissions(resp) + return resp + + class _UpdateBillingAccount(CloudBillingRestStub): + def __hash__(self): + return hash("UpdateBillingAccount") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_billing.UpdateBillingAccountRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.BillingAccount: + r"""Call the update billing account method over HTTP. + + Args: + request (~.cloud_billing.UpdateBillingAccountRequest): + The request object. Request message for ``UpdateBillingAccount``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.BillingAccount: + A billing account in the `Google Cloud + Console `__. You can + assign a billing account to one or more projects. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{name=billingAccounts/*}", + "body": "account", + }, + ] + request, metadata = self._interceptor.pre_update_billing_account( + request, metadata + ) + pb_request = cloud_billing.UpdateBillingAccountRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.BillingAccount() + pb_resp = cloud_billing.BillingAccount.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_billing_account(resp) + return resp + + class _UpdateProjectBillingInfo(CloudBillingRestStub): + def __hash__(self): + return hash("UpdateProjectBillingInfo") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_billing.UpdateProjectBillingInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_billing.ProjectBillingInfo: + r"""Call the update project billing + info method over HTTP. + + Args: + request (~.cloud_billing.UpdateProjectBillingInfoRequest): + The request object. Request message for ``UpdateProjectBillingInfo``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_billing.ProjectBillingInfo: + Encapsulation of billing information + for a Google Cloud Console project. A + project has at most one associated + billing account at a time (but a billing + account can be assigned to multiple + projects). + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "put", + "uri": "/v1/{name=projects/*}/billingInfo", + "body": "project_billing_info", + }, + ] + request, metadata = self._interceptor.pre_update_project_billing_info( + request, metadata + ) + pb_request = cloud_billing.UpdateProjectBillingInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_billing.ProjectBillingInfo() + pb_resp = cloud_billing.ProjectBillingInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_project_billing_info(resp) + return resp + + @property + def create_billing_account( + self, + ) -> Callable[ + [cloud_billing.CreateBillingAccountRequest], cloud_billing.BillingAccount + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._CreateBillingAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_billing_account( + self, + ) -> Callable[ + [cloud_billing.GetBillingAccountRequest], cloud_billing.BillingAccount + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetBillingAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_project_billing_info( + self, + ) -> Callable[ + [cloud_billing.GetProjectBillingInfoRequest], cloud_billing.ProjectBillingInfo + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetProjectBillingInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_billing_accounts( + self, + ) -> Callable[ + [cloud_billing.ListBillingAccountsRequest], + cloud_billing.ListBillingAccountsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListBillingAccounts(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_project_billing_info( + self, + ) -> Callable[ + [cloud_billing.ListProjectBillingInfoRequest], + cloud_billing.ListProjectBillingInfoResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListProjectBillingInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._SetIamPolicy(self._session, self._host, self._interceptor) # type: ignore + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy_pb2.TestIamPermissionsRequest], + iam_policy_pb2.TestIamPermissionsResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._TestIamPermissions(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_billing_account( + self, + ) -> Callable[ + [cloud_billing.UpdateBillingAccountRequest], cloud_billing.BillingAccount + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateBillingAccount(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_project_billing_info( + self, + ) -> Callable[ + [cloud_billing.UpdateProjectBillingInfoRequest], + cloud_billing.ProjectBillingInfo, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateProjectBillingInfo(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CloudBillingRestTransport",) diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py index 27a226590ac6..d4f707ccc845 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/client.py @@ -52,6 +52,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, CloudCatalogTransport from .transports.grpc import CloudCatalogGrpcTransport from .transports.grpc_asyncio import CloudCatalogGrpcAsyncIOTransport +from .transports.rest import CloudCatalogRestTransport class CloudCatalogClientMeta(type): @@ -65,6 +66,7 @@ class CloudCatalogClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[CloudCatalogTransport]] _transport_registry["grpc"] = CloudCatalogGrpcTransport _transport_registry["grpc_asyncio"] = CloudCatalogGrpcAsyncIOTransport + _transport_registry["rest"] = CloudCatalogRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/__init__.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/__init__.py index 24d254d602f2..5a848ee5cb5e 100644 --- a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/__init__.py +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/__init__.py @@ -19,14 +19,18 @@ from .base import CloudCatalogTransport from .grpc import CloudCatalogGrpcTransport from .grpc_asyncio import CloudCatalogGrpcAsyncIOTransport +from .rest import CloudCatalogRestInterceptor, CloudCatalogRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[CloudCatalogTransport]] _transport_registry["grpc"] = CloudCatalogGrpcTransport _transport_registry["grpc_asyncio"] = CloudCatalogGrpcAsyncIOTransport +_transport_registry["rest"] = CloudCatalogRestTransport __all__ = ( "CloudCatalogTransport", "CloudCatalogGrpcTransport", "CloudCatalogGrpcAsyncIOTransport", + "CloudCatalogRestTransport", + "CloudCatalogRestInterceptor", ) diff --git a/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/rest.py b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/rest.py new file mode 100644 index 000000000000..94a3eec29fb6 --- /dev/null +++ b/packages/google-cloud-billing/google/cloud/billing_v1/services/cloud_catalog/transports/rest.py @@ -0,0 +1,420 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import dataclasses +import json # type: ignore +import re +from typing import Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, path_template, rest_helpers, rest_streaming +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +from google.protobuf import json_format +import grpc # type: ignore +from requests import __version__ as requests_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + + +from google.cloud.billing_v1.types import cloud_catalog + +from .base import CloudCatalogTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class CloudCatalogRestInterceptor: + """Interceptor for CloudCatalog. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the CloudCatalogRestTransport. + + .. code-block:: python + class MyCustomCloudCatalogInterceptor(CloudCatalogRestInterceptor): + def pre_list_services(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_services(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_skus(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_skus(self, response): + logging.log(f"Received response: {response}") + return response + + transport = CloudCatalogRestTransport(interceptor=MyCustomCloudCatalogInterceptor()) + client = CloudCatalogClient(transport=transport) + + + """ + + def pre_list_services( + self, + request: cloud_catalog.ListServicesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_catalog.ListServicesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_services + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudCatalog server. + """ + return request, metadata + + def post_list_services( + self, response: cloud_catalog.ListServicesResponse + ) -> cloud_catalog.ListServicesResponse: + """Post-rpc interceptor for list_services + + Override in a subclass to manipulate the response + after it is returned by the CloudCatalog server but before + it is returned to user code. + """ + return response + + def pre_list_skus( + self, + request: cloud_catalog.ListSkusRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[cloud_catalog.ListSkusRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_skus + + Override in a subclass to manipulate the request or metadata + before they are sent to the CloudCatalog server. + """ + return request, metadata + + def post_list_skus( + self, response: cloud_catalog.ListSkusResponse + ) -> cloud_catalog.ListSkusResponse: + """Post-rpc interceptor for list_skus + + Override in a subclass to manipulate the response + after it is returned by the CloudCatalog server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class CloudCatalogRestStub: + _session: AuthorizedSession + _host: str + _interceptor: CloudCatalogRestInterceptor + + +class CloudCatalogRestTransport(CloudCatalogTransport): + """REST backend transport for CloudCatalog. + + A catalog of Google Cloud Platform services and SKUs. + Provides pricing information and metadata on Google Cloud + Platform services and SKUs. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + + """ + + def __init__( + self, + *, + host: str = "cloudbilling.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[CloudCatalogRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or CloudCatalogRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _ListServices(CloudCatalogRestStub): + def __hash__(self): + return hash("ListServices") + + def __call__( + self, + request: cloud_catalog.ListServicesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_catalog.ListServicesResponse: + r"""Call the list services method over HTTP. + + Args: + request (~.cloud_catalog.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. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_catalog.ListServicesResponse: + Response message for ``ListServices``. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/services", + }, + ] + request, metadata = self._interceptor.pre_list_services(request, metadata) + pb_request = cloud_catalog.ListServicesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_catalog.ListServicesResponse() + pb_resp = cloud_catalog.ListServicesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_services(resp) + return resp + + class _ListSkus(CloudCatalogRestStub): + def __hash__(self): + return hash("ListSkus") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, str] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: cloud_catalog.ListSkusRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> cloud_catalog.ListSkusResponse: + r"""Call the list skus method over HTTP. + + Args: + request (~.cloud_catalog.ListSkusRequest): + The request object. Request message for ``ListSkus``. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.cloud_catalog.ListSkusResponse: + Response message for ``ListSkus``. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=services/*}/skus", + }, + ] + request, metadata = self._interceptor.pre_list_skus(request, metadata) + pb_request = cloud_catalog.ListSkusRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = cloud_catalog.ListSkusResponse() + pb_resp = cloud_catalog.ListSkusResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_skus(resp) + return resp + + @property + def list_services( + self, + ) -> Callable[ + [cloud_catalog.ListServicesRequest], cloud_catalog.ListServicesResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListServices(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_skus( + self, + ) -> Callable[[cloud_catalog.ListSkusRequest], cloud_catalog.ListSkusResponse]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ListSkus(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("CloudCatalogRestTransport",) diff --git a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py index 929eee372259..773658f2b8b8 100644 --- a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py +++ b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_billing.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -35,12 +37,15 @@ from google.iam.v1 import policy_pb2 # type: ignore from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.type import expr_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.billing_v1.services.cloud_billing import ( CloudBillingAsyncClient, @@ -97,6 +102,7 @@ def test__get_default_mtls_endpoint(): [ (CloudBillingClient, "grpc"), (CloudBillingAsyncClient, "grpc_asyncio"), + (CloudBillingClient, "rest"), ], ) def test_cloud_billing_client_from_service_account_info(client_class, transport_name): @@ -110,7 +116,11 @@ def test_cloud_billing_client_from_service_account_info(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudbilling.googleapis.com:443") + assert client.transport._host == ( + "cloudbilling.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com" + ) @pytest.mark.parametrize( @@ -118,6 +128,7 @@ def test_cloud_billing_client_from_service_account_info(client_class, transport_ [ (transports.CloudBillingGrpcTransport, "grpc"), (transports.CloudBillingGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CloudBillingRestTransport, "rest"), ], ) def test_cloud_billing_client_service_account_always_use_jwt( @@ -143,6 +154,7 @@ def test_cloud_billing_client_service_account_always_use_jwt( [ (CloudBillingClient, "grpc"), (CloudBillingAsyncClient, "grpc_asyncio"), + (CloudBillingClient, "rest"), ], ) def test_cloud_billing_client_from_service_account_file(client_class, transport_name): @@ -163,13 +175,18 @@ def test_cloud_billing_client_from_service_account_file(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudbilling.googleapis.com:443") + assert client.transport._host == ( + "cloudbilling.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com" + ) def test_cloud_billing_client_get_transport_class(): transport = CloudBillingClient.get_transport_class() available_transports = [ transports.CloudBillingGrpcTransport, + transports.CloudBillingRestTransport, ] assert transport in available_transports @@ -186,6 +203,7 @@ def test_cloud_billing_client_get_transport_class(): transports.CloudBillingGrpcAsyncIOTransport, "grpc_asyncio", ), + (CloudBillingClient, transports.CloudBillingRestTransport, "rest"), ], ) @mock.patch.object( @@ -329,6 +347,8 @@ def test_cloud_billing_client_client_options( "grpc_asyncio", "false", ), + (CloudBillingClient, transports.CloudBillingRestTransport, "rest", "true"), + (CloudBillingClient, transports.CloudBillingRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -522,6 +542,7 @@ def test_cloud_billing_client_get_mtls_endpoint_and_cert_source(client_class): transports.CloudBillingGrpcAsyncIOTransport, "grpc_asyncio", ), + (CloudBillingClient, transports.CloudBillingRestTransport, "rest"), ], ) def test_cloud_billing_client_client_options_scopes( @@ -562,6 +583,7 @@ def test_cloud_billing_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (CloudBillingClient, transports.CloudBillingRestTransport, "rest", None), ], ) def test_cloud_billing_client_client_options_credentials_file( @@ -3432,211 +3454,2968 @@ 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( +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.GetBillingAccountRequest, + dict, + ], +) +def test_get_billing_account_rest(request_type): + client = CloudBillingClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = CloudBillingClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"name": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount( + name="name_value", + open_=True, + display_name="display_name_value", + master_billing_account="master_billing_account_value", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.CloudBillingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = CloudBillingClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_billing_account(request) + + # 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" + + +def test_get_billing_account_rest_required_fields( + request_type=cloud_billing.GetBillingAccountRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.CloudBillingGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_billing_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_billing_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CloudBillingClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudBillingClient( - client_options=options, - transport=transport, - ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = CloudBillingClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + response_value = Response() + response_value.status_code = 200 - # It is an error to provide scopes and a transport instance. - transport = transports.CloudBillingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_billing_account(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_billing_account_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - with pytest.raises(ValueError): - client = CloudBillingClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + unset_fields = transport.get_billing_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudBillingGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_billing_account_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), ) client = CloudBillingClient(transport=transport) - assert client.transport is transport + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_get_billing_account" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_get_billing_account" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.GetBillingAccountRequest.pb( + cloud_billing.GetBillingAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_billing.BillingAccount.to_json( + cloud_billing.BillingAccount() + ) + request = cloud_billing.GetBillingAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.BillingAccount() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.CloudBillingGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + client.get_billing_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - transport = transports.CloudBillingGrpcAsyncIOTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_get_billing_account_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.GetBillingAccountRequest +): + client = CloudBillingClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # send a request that will satisfy transcoding + request_init = {"name": "billingAccounts/sample1"} + request = request_type(**request_init) -@pytest.mark.parametrize( - "transport_class", - [ - transports.CloudBillingGrpcTransport, - transports.CloudBillingGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_billing_account(request) -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = CloudBillingClient.get_transport_class(transport_name)( +def test_get_billing_account_rest_flattened(): + client = CloudBillingClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount() -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. + # get arguments that satisfy an http rule for this method + sample_request = {"name": "billingAccounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_billing_account(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=billingAccounts/*}" % client.transport._host, args[1] + ) + + +def test_get_billing_account_rest_flattened_error(transport: str = "rest"): client = CloudBillingClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert isinstance( - client.transport, - transports.CloudBillingGrpcTransport, + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_billing_account( + cloud_billing.GetBillingAccountRequest(), + name="name_value", + ) + + +def test_get_billing_account_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) -def test_cloud_billing_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.CloudBillingTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.ListBillingAccountsRequest, + dict, + ], +) +def test_list_billing_accounts_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) -def test_cloud_billing_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.billing_v1.services.cloud_billing.transports.CloudBillingTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.CloudBillingTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ListBillingAccountsResponse( + next_page_token="next_page_token_value", ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "get_billing_account", - "list_billing_accounts", - "update_billing_account", - "create_billing_account", - "list_project_billing_info", - "get_project_billing_info", - "update_project_billing_info", - "get_iam_policy", - "set_iam_policy", - "test_iam_permissions", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ListBillingAccountsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) - with pytest.raises(NotImplementedError): - transport.close() + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_billing_accounts(request) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBillingAccountsPager) + assert response.next_page_token == "next_page_token_value" -def test_cloud_billing_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_billing_accounts_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) 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 = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudBillingTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_list_billing_accounts" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_list_billing_accounts" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.ListBillingAccountsRequest.pb( + cloud_billing.ListBillingAccountsRequest() ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=( - "https://www.googleapis.com/auth/cloud-billing", - "https://www.googleapis.com/auth/cloud-billing.readonly", - "https://www.googleapis.com/auth/cloud-platform", - ), - quota_project_id="octopus", + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_billing.ListBillingAccountsResponse.to_json( + cloud_billing.ListBillingAccountsResponse() ) + request = cloud_billing.ListBillingAccountsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.ListBillingAccountsResponse() + + client.list_billing_accounts( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -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(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 = (ga_credentials.AnonymousCredentials(), None) - transport = transports.CloudBillingTransport() - adc.assert_called_once() + pre.assert_called_once() + post.assert_called_once() -def test_cloud_billing_auth_adc(): - # 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() +def test_list_billing_accounts_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.ListBillingAccountsRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_billing_accounts(request) + + +def test_list_billing_accounts_rest_pager(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_billing.ListBillingAccountsResponse( + billing_accounts=[ + cloud_billing.BillingAccount(), + cloud_billing.BillingAccount(), + cloud_billing.BillingAccount(), + ], + next_page_token="abc", + ), + cloud_billing.ListBillingAccountsResponse( + billing_accounts=[], + next_page_token="def", + ), + cloud_billing.ListBillingAccountsResponse( + billing_accounts=[ + cloud_billing.BillingAccount(), + ], + next_page_token="ghi", + ), + cloud_billing.ListBillingAccountsResponse( + billing_accounts=[ + cloud_billing.BillingAccount(), + cloud_billing.BillingAccount(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_billing.ListBillingAccountsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_billing_accounts(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_billing.BillingAccount) for i in results) + + pages = list(client.list_billing_accounts(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.UpdateBillingAccountRequest, + dict, + ], +) +def test_update_billing_account_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "billingAccounts/sample1"} + request_init["account"] = { + "name": "name_value", + "open_": True, + "display_name": "display_name_value", + "master_billing_account": "master_billing_account_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount( + name="name_value", + open_=True, + display_name="display_name_value", + master_billing_account="master_billing_account_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_billing_account(request) + + # 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" + + +def test_update_billing_account_rest_required_fields( + request_type=cloud_billing.UpdateBillingAccountRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_billing_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_billing_account._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_billing_account(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_billing_account_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_billing_account._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("updateMask",)) + & set( + ( + "name", + "account", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_billing_account_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_update_billing_account" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_update_billing_account" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.UpdateBillingAccountRequest.pb( + cloud_billing.UpdateBillingAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_billing.BillingAccount.to_json( + cloud_billing.BillingAccount() + ) + + request = cloud_billing.UpdateBillingAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.BillingAccount() + + client.update_billing_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_billing_account_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.UpdateBillingAccountRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "billingAccounts/sample1"} + request_init["account"] = { + "name": "name_value", + "open_": True, + "display_name": "display_name_value", + "master_billing_account": "master_billing_account_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_billing_account(request) + + +def test_update_billing_account_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "billingAccounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + account=cloud_billing.BillingAccount(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_billing_account(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=billingAccounts/*}" % client.transport._host, args[1] + ) + + +def test_update_billing_account_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_billing_account( + cloud_billing.UpdateBillingAccountRequest(), + name="name_value", + account=cloud_billing.BillingAccount(name="name_value"), + ) + + +def test_update_billing_account_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.CreateBillingAccountRequest, + dict, + ], +) +def test_create_billing_account_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["billing_account"] = { + "name": "name_value", + "open_": True, + "display_name": "display_name_value", + "master_billing_account": "master_billing_account_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount( + name="name_value", + open_=True, + display_name="display_name_value", + master_billing_account="master_billing_account_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_billing_account(request) + + # 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" + + +def test_create_billing_account_rest_required_fields( + request_type=cloud_billing.CreateBillingAccountRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_billing_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_billing_account._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.create_billing_account(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_billing_account_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_billing_account._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("billingAccount",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_billing_account_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_create_billing_account" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_create_billing_account" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.CreateBillingAccountRequest.pb( + cloud_billing.CreateBillingAccountRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_billing.BillingAccount.to_json( + cloud_billing.BillingAccount() + ) + + request = cloud_billing.CreateBillingAccountRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.BillingAccount() + + client.create_billing_account( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_billing_account_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.CreateBillingAccountRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request_init["billing_account"] = { + "name": "name_value", + "open_": True, + "display_name": "display_name_value", + "master_billing_account": "master_billing_account_value", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.create_billing_account(request) + + +def test_create_billing_account_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.BillingAccount() + + # get arguments that satisfy an http rule for this method + sample_request = {} + + # get truthy value for each flattened field + mock_args = dict( + billing_account=cloud_billing.BillingAccount(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.BillingAccount.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.create_billing_account(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/billingAccounts" % client.transport._host, args[1] + ) + + +def test_create_billing_account_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_billing_account( + cloud_billing.CreateBillingAccountRequest(), + billing_account=cloud_billing.BillingAccount(name="name_value"), + ) + + +def test_create_billing_account_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.ListProjectBillingInfoRequest, + dict, + ], +) +def test_list_project_billing_info_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ListProjectBillingInfoResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ListProjectBillingInfoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_project_billing_info(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListProjectBillingInfoPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_project_billing_info_rest_required_fields( + request_type=cloud_billing.ListProjectBillingInfoRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_project_billing_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_project_billing_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ListProjectBillingInfoResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_billing.ListProjectBillingInfoResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_project_billing_info(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_project_billing_info_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_project_billing_info._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("name",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_project_billing_info_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_list_project_billing_info" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_list_project_billing_info" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.ListProjectBillingInfoRequest.pb( + cloud_billing.ListProjectBillingInfoRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = ( + cloud_billing.ListProjectBillingInfoResponse.to_json( + cloud_billing.ListProjectBillingInfoResponse() + ) + ) + + request = cloud_billing.ListProjectBillingInfoRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.ListProjectBillingInfoResponse() + + client.list_project_billing_info( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_project_billing_info_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.ListProjectBillingInfoRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_project_billing_info(request) + + +def test_list_project_billing_info_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ListProjectBillingInfoResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "billingAccounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ListProjectBillingInfoResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_project_billing_info(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=billingAccounts/*}/projects" % client.transport._host, args[1] + ) + + +def test_list_project_billing_info_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_project_billing_info( + cloud_billing.ListProjectBillingInfoRequest(), + name="name_value", + ) + + +def test_list_project_billing_info_rest_pager(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_billing.ListProjectBillingInfoResponse( + project_billing_info=[ + cloud_billing.ProjectBillingInfo(), + cloud_billing.ProjectBillingInfo(), + cloud_billing.ProjectBillingInfo(), + ], + next_page_token="abc", + ), + cloud_billing.ListProjectBillingInfoResponse( + project_billing_info=[], + next_page_token="def", + ), + cloud_billing.ListProjectBillingInfoResponse( + project_billing_info=[ + cloud_billing.ProjectBillingInfo(), + ], + next_page_token="ghi", + ), + cloud_billing.ListProjectBillingInfoResponse( + project_billing_info=[ + cloud_billing.ProjectBillingInfo(), + cloud_billing.ProjectBillingInfo(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_billing.ListProjectBillingInfoResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"name": "billingAccounts/sample1"} + + pager = client.list_project_billing_info(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_billing.ProjectBillingInfo) for i in results) + + pages = list(client.list_project_billing_info(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.GetProjectBillingInfoRequest, + dict, + ], +) +def test_get_project_billing_info_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ProjectBillingInfo( + name="name_value", + project_id="project_id_value", + billing_account_name="billing_account_name_value", + billing_enabled=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ProjectBillingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_project_billing_info(request) + + # 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 + + +def test_get_project_billing_info_rest_required_fields( + request_type=cloud_billing.GetProjectBillingInfoRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_project_billing_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_project_billing_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ProjectBillingInfo() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_billing.ProjectBillingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_project_billing_info(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_project_billing_info_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_project_billing_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_project_billing_info_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_get_project_billing_info" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_get_project_billing_info" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.GetProjectBillingInfoRequest.pb( + cloud_billing.GetProjectBillingInfoRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_billing.ProjectBillingInfo.to_json( + cloud_billing.ProjectBillingInfo() + ) + + request = cloud_billing.GetProjectBillingInfoRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.ProjectBillingInfo() + + client.get_project_billing_info( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_project_billing_info_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.GetProjectBillingInfoRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_project_billing_info(request) + + +def test_get_project_billing_info_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ProjectBillingInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ProjectBillingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_project_billing_info(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*}/billingInfo" % client.transport._host, args[1] + ) + + +def test_get_project_billing_info_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_project_billing_info( + cloud_billing.GetProjectBillingInfoRequest(), + name="name_value", + ) + + +def test_get_project_billing_info_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_billing.UpdateProjectBillingInfoRequest, + dict, + ], +) +def test_update_project_billing_info_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + request_init["project_billing_info"] = { + "name": "name_value", + "project_id": "project_id_value", + "billing_account_name": "billing_account_name_value", + "billing_enabled": True, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ProjectBillingInfo( + name="name_value", + project_id="project_id_value", + billing_account_name="billing_account_name_value", + billing_enabled=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ProjectBillingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_project_billing_info(request) + + # 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 + + +def test_update_project_billing_info_rest_required_fields( + request_type=cloud_billing.UpdateProjectBillingInfoRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_project_billing_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_project_billing_info._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ProjectBillingInfo() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_billing.ProjectBillingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_project_billing_info(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_project_billing_info_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_project_billing_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_project_billing_info_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_update_project_billing_info" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_update_project_billing_info" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_billing.UpdateProjectBillingInfoRequest.pb( + cloud_billing.UpdateProjectBillingInfoRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_billing.ProjectBillingInfo.to_json( + cloud_billing.ProjectBillingInfo() + ) + + request = cloud_billing.UpdateProjectBillingInfoRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_billing.ProjectBillingInfo() + + client.update_project_billing_info( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_project_billing_info_rest_bad_request( + transport: str = "rest", request_type=cloud_billing.UpdateProjectBillingInfoRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1"} + request_init["project_billing_info"] = { + "name": "name_value", + "project_id": "project_id_value", + "billing_account_name": "billing_account_name_value", + "billing_enabled": True, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_project_billing_info(request) + + +def test_update_project_billing_info_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_billing.ProjectBillingInfo() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + project_billing_info=cloud_billing.ProjectBillingInfo(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_billing.ProjectBillingInfo.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_project_billing_info(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*}/billingInfo" % client.transport._host, args[1] + ) + + +def test_update_project_billing_info_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_project_billing_info( + cloud_billing.UpdateProjectBillingInfoRequest(), + name="name_value", + project_billing_info=cloud_billing.ProjectBillingInfo(name="name_value"), + ) + + +def test_update_project_billing_info_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.GetIamPolicyRequest, + dict, + ], +) +def test_get_iam_policy_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.GetIamPolicyRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("options",)) & set(("resource",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_iam_policy_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_get_iam_policy" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_get_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.GetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.GetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.get_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.GetIamPolicyRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_iam_policy(request) + + +def test_get_iam_policy_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "billingAccounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{resource=billingAccounts/*}:getIamPolicy" % client.transport._host, + args[1], + ) + + +def test_get_iam_policy_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_iam_policy( + iam_policy_pb2.GetIamPolicyRequest(), + resource="resource_value", + ) + + +def test_get_iam_policy_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.SetIamPolicyRequest, + dict, + ], +) +def test_set_iam_policy_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.set_iam_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_rest_required_fields( + request_type=iam_policy_pb2.SetIamPolicyRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["resource"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).set_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.set_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_set_iam_policy_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.set_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "policy", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_set_iam_policy_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_set_iam_policy" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_set_iam_policy" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.SetIamPolicyRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson(policy_pb2.Policy()) + + request = iam_policy_pb2.SetIamPolicyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = policy_pb2.Policy() + + client.set_iam_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_set_iam_policy_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.SetIamPolicyRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.set_iam_policy(request) + + +def test_set_iam_policy_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "billingAccounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.set_iam_policy(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{resource=billingAccounts/*}:setIamPolicy" % client.transport._host, + args[1], + ) + + +def test_set_iam_policy_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.set_iam_policy( + iam_policy_pb2.SetIamPolicyRequest(), + resource="resource_value", + ) + + +def test_set_iam_policy_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + iam_policy_pb2.TestIamPermissionsRequest, + dict, + ], +) +def test_test_iam_permissions_rest(request_type): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.test_iam_permissions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_rest_required_fields( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + transport_class = transports.CloudBillingRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = request + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + jsonified_request["permissions"] = "permissions_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == "permissions_value" + + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.test_iam_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "permissions", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_test_iam_permissions_rest_interceptors(null_interceptor): + transport = transports.CloudBillingRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudBillingRestInterceptor(), + ) + client = CloudBillingClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudBillingRestInterceptor, "post_test_iam_permissions" + ) as post, mock.patch.object( + transports.CloudBillingRestInterceptor, "pre_test_iam_permissions" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) + + request = iam_policy_pb2.TestIamPermissionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + + client.test_iam_permissions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_test_iam_permissions_rest_bad_request( + transport: str = "rest", request_type=iam_policy_pb2.TestIamPermissionsRequest +): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"resource": "billingAccounts/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.test_iam_permissions(request) + + +def test_test_iam_permissions_rest_flattened(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"resource": "billingAccounts/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + resource="resource_value", + permissions=["permissions_value"], + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = return_value + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.test_iam_permissions(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{resource=billingAccounts/*}:testIamPermissions" + % client.transport._host, + args[1], + ) + + +def test_test_iam_permissions_rest_flattened_error(transport: str = "rest"): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.test_iam_permissions( + iam_policy_pb2.TestIamPermissionsRequest(), + resource="resource_value", + permissions=["permissions_value"], + ) + + +def test_test_iam_permissions_rest_error(): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.CloudBillingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudBillingClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.CloudBillingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudBillingClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.CloudBillingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudBillingClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = CloudBillingClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.CloudBillingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = CloudBillingClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudBillingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = CloudBillingClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.CloudBillingGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.CloudBillingGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.CloudBillingGrpcTransport, + transports.CloudBillingGrpcAsyncIOTransport, + transports.CloudBillingRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "rest", + ], +) +def test_transport_kind(transport_name): + transport = CloudBillingClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = 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(core_exceptions.DuplicateCredentialArgs): + transport = transports.CloudBillingTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_cloud_billing_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.billing_v1.services.cloud_billing.transports.CloudBillingTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.CloudBillingTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get_billing_account", + "list_billing_accounts", + "update_billing_account", + "create_billing_account", + "list_project_billing_info", + "get_project_billing_info", + "update_project_billing_info", + "get_iam_policy", + "set_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_cloud_billing_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.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-billing", + "https://www.googleapis.com/auth/cloud-billing.readonly", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +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(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 = (ga_credentials.AnonymousCredentials(), None) + transport = transports.CloudBillingTransport() + adc.assert_called_once() + + +def test_cloud_billing_auth_adc(): + # 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=None, default_scopes=( @@ -3677,6 +6456,7 @@ def test_cloud_billing_transport_auth_adc(transport_class): [ transports.CloudBillingGrpcTransport, transports.CloudBillingGrpcAsyncIOTransport, + transports.CloudBillingRestTransport, ], ) def test_cloud_billing_transport_auth_gdch_credentials(transport_class): @@ -3775,11 +6555,23 @@ def test_cloud_billing_grpc_transport_client_cert_source_for_mtls(transport_clas ) +def test_cloud_billing_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CloudBillingRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_cloud_billing_host_no_port(transport_name): @@ -3790,7 +6582,11 @@ def test_cloud_billing_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudbilling.googleapis.com:443") + assert client.transport._host == ( + "cloudbilling.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com" + ) @pytest.mark.parametrize( @@ -3798,6 +6594,7 @@ def test_cloud_billing_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_cloud_billing_host_with_port(transport_name): @@ -3808,7 +6605,60 @@ def test_cloud_billing_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudbilling.googleapis.com:8000") + assert client.transport._host == ( + "cloudbilling.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_billing_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudBillingClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudBillingClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get_billing_account._session + session2 = client2.transport.get_billing_account._session + assert session1 != session2 + session1 = client1.transport.list_billing_accounts._session + session2 = client2.transport.list_billing_accounts._session + assert session1 != session2 + session1 = client1.transport.update_billing_account._session + session2 = client2.transport.update_billing_account._session + assert session1 != session2 + session1 = client1.transport.create_billing_account._session + session2 = client2.transport.create_billing_account._session + assert session1 != session2 + session1 = client1.transport.list_project_billing_info._session + session2 = client2.transport.list_project_billing_info._session + assert session1 != session2 + session1 = client1.transport.get_project_billing_info._session + session2 = client2.transport.get_project_billing_info._session + assert session1 != session2 + session1 = client1.transport.update_project_billing_info._session + session2 = client2.transport.update_project_billing_info._session + assert session1 != session2 + session1 = client1.transport.get_iam_policy._session + session2 = client2.transport.get_iam_policy._session + assert session1 != session2 + session1 = client1.transport.set_iam_policy._session + session2 = client2.transport.set_iam_policy._session + assert session1 != session2 + session1 = client1.transport.test_iam_permissions._session + session2 = client2.transport.test_iam_permissions._session + assert session1 != session2 def test_cloud_billing_grpc_transport_channel(): @@ -4071,6 +6921,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -4088,6 +6939,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: diff --git a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py index 830e11c3133d..f9a911c769ff 100644 --- a/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py +++ b/packages/google-cloud-billing/tests/unit/gapic/billing_v1/test_cloud_catalog.py @@ -22,6 +22,8 @@ except ImportError: # pragma: NO COVER import mock +from collections.abc import Iterable +import json import math from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template @@ -31,12 +33,15 @@ from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.oauth2 import service_account +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.billing_v1.services.cloud_catalog import ( CloudCatalogAsyncClient, @@ -93,6 +98,7 @@ def test__get_default_mtls_endpoint(): [ (CloudCatalogClient, "grpc"), (CloudCatalogAsyncClient, "grpc_asyncio"), + (CloudCatalogClient, "rest"), ], ) def test_cloud_catalog_client_from_service_account_info(client_class, transport_name): @@ -106,7 +112,11 @@ def test_cloud_catalog_client_from_service_account_info(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudbilling.googleapis.com:443") + assert client.transport._host == ( + "cloudbilling.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com" + ) @pytest.mark.parametrize( @@ -114,6 +124,7 @@ def test_cloud_catalog_client_from_service_account_info(client_class, transport_ [ (transports.CloudCatalogGrpcTransport, "grpc"), (transports.CloudCatalogGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.CloudCatalogRestTransport, "rest"), ], ) def test_cloud_catalog_client_service_account_always_use_jwt( @@ -139,6 +150,7 @@ def test_cloud_catalog_client_service_account_always_use_jwt( [ (CloudCatalogClient, "grpc"), (CloudCatalogAsyncClient, "grpc_asyncio"), + (CloudCatalogClient, "rest"), ], ) def test_cloud_catalog_client_from_service_account_file(client_class, transport_name): @@ -159,13 +171,18 @@ def test_cloud_catalog_client_from_service_account_file(client_class, transport_ assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("cloudbilling.googleapis.com:443") + assert client.transport._host == ( + "cloudbilling.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com" + ) def test_cloud_catalog_client_get_transport_class(): transport = CloudCatalogClient.get_transport_class() available_transports = [ transports.CloudCatalogGrpcTransport, + transports.CloudCatalogRestTransport, ] assert transport in available_transports @@ -182,6 +199,7 @@ def test_cloud_catalog_client_get_transport_class(): transports.CloudCatalogGrpcAsyncIOTransport, "grpc_asyncio", ), + (CloudCatalogClient, transports.CloudCatalogRestTransport, "rest"), ], ) @mock.patch.object( @@ -325,6 +343,8 @@ def test_cloud_catalog_client_client_options( "grpc_asyncio", "false", ), + (CloudCatalogClient, transports.CloudCatalogRestTransport, "rest", "true"), + (CloudCatalogClient, transports.CloudCatalogRestTransport, "rest", "false"), ], ) @mock.patch.object( @@ -518,6 +538,7 @@ def test_cloud_catalog_client_get_mtls_endpoint_and_cert_source(client_class): transports.CloudCatalogGrpcAsyncIOTransport, "grpc_asyncio", ), + (CloudCatalogClient, transports.CloudCatalogRestTransport, "rest"), ], ) def test_cloud_catalog_client_client_options_scopes( @@ -558,6 +579,7 @@ def test_cloud_catalog_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + (CloudCatalogClient, transports.CloudCatalogRestTransport, "rest", None), ], ) def test_cloud_catalog_client_client_options_credentials_file( @@ -1366,6 +1388,527 @@ async def test_list_skus_async_pages(): assert page_.raw_page.next_page_token == token +@pytest.mark.parametrize( + "request_type", + [ + cloud_catalog.ListServicesRequest, + dict, + ], +) +def test_list_services_rest(request_type): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_catalog.ListServicesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_catalog.ListServicesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_services(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_services_rest_interceptors(null_interceptor): + transport = transports.CloudCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudCatalogRestInterceptor(), + ) + client = CloudCatalogClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudCatalogRestInterceptor, "post_list_services" + ) as post, mock.patch.object( + transports.CloudCatalogRestInterceptor, "pre_list_services" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_catalog.ListServicesRequest.pb( + cloud_catalog.ListServicesRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_catalog.ListServicesResponse.to_json( + cloud_catalog.ListServicesResponse() + ) + + request = cloud_catalog.ListServicesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_catalog.ListServicesResponse() + + client.list_services( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_services_rest_bad_request( + transport: str = "rest", request_type=cloud_catalog.ListServicesRequest +): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_services(request) + + +def test_list_services_rest_pager(transport: str = "rest"): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_catalog.ListServicesResponse( + services=[ + cloud_catalog.Service(), + cloud_catalog.Service(), + cloud_catalog.Service(), + ], + next_page_token="abc", + ), + cloud_catalog.ListServicesResponse( + services=[], + next_page_token="def", + ), + cloud_catalog.ListServicesResponse( + services=[ + cloud_catalog.Service(), + ], + next_page_token="ghi", + ), + cloud_catalog.ListServicesResponse( + services=[ + cloud_catalog.Service(), + cloud_catalog.Service(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + cloud_catalog.ListServicesResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {} + + pager = client.list_services(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_catalog.Service) for i in results) + + pages = list(client.list_services(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + cloud_catalog.ListSkusRequest, + dict, + ], +) +def test_list_skus_rest(request_type): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "services/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_catalog.ListSkusResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_catalog.ListSkusResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_skus(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSkusPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_skus_rest_required_fields(request_type=cloud_catalog.ListSkusRequest): + transport_class = transports.CloudCatalogRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_skus._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_skus._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "currency_code", + "end_time", + "page_size", + "page_token", + "start_time", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = cloud_catalog.ListSkusResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = cloud_catalog.ListSkusResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_skus(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_skus_rest_unset_required_fields(): + transport = transports.CloudCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_skus._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "currencyCode", + "endTime", + "pageSize", + "pageToken", + "startTime", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_skus_rest_interceptors(null_interceptor): + transport = transports.CloudCatalogRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.CloudCatalogRestInterceptor(), + ) + client = CloudCatalogClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.CloudCatalogRestInterceptor, "post_list_skus" + ) as post, mock.patch.object( + transports.CloudCatalogRestInterceptor, "pre_list_skus" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = cloud_catalog.ListSkusRequest.pb(cloud_catalog.ListSkusRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = cloud_catalog.ListSkusResponse.to_json( + cloud_catalog.ListSkusResponse() + ) + + request = cloud_catalog.ListSkusRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = cloud_catalog.ListSkusResponse() + + client.list_skus( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_skus_rest_bad_request( + transport: str = "rest", request_type=cloud_catalog.ListSkusRequest +): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "services/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_skus(request) + + +def test_list_skus_rest_flattened(): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = cloud_catalog.ListSkusResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "services/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = cloud_catalog.ListSkusResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_skus(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=services/*}/skus" % client.transport._host, args[1] + ) + + +def test_list_skus_rest_flattened_error(transport: str = "rest"): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_skus( + cloud_catalog.ListSkusRequest(), + parent="parent_value", + ) + + +def test_list_skus_rest_pager(transport: str = "rest"): + client = CloudCatalogClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + cloud_catalog.ListSkusResponse( + skus=[ + cloud_catalog.Sku(), + cloud_catalog.Sku(), + cloud_catalog.Sku(), + ], + next_page_token="abc", + ), + cloud_catalog.ListSkusResponse( + skus=[], + next_page_token="def", + ), + cloud_catalog.ListSkusResponse( + skus=[ + cloud_catalog.Sku(), + ], + next_page_token="ghi", + ), + cloud_catalog.ListSkusResponse( + skus=[ + cloud_catalog.Sku(), + cloud_catalog.Sku(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(cloud_catalog.ListSkusResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "services/sample1"} + + pager = client.list_skus(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, cloud_catalog.Sku) for i in results) + + pages = list(client.list_skus(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.CloudCatalogGrpcTransport( @@ -1447,6 +1990,7 @@ def test_transport_get_channel(): [ transports.CloudCatalogGrpcTransport, transports.CloudCatalogGrpcAsyncIOTransport, + transports.CloudCatalogRestTransport, ], ) def test_transport_adc(transport_class): @@ -1461,6 +2005,7 @@ def test_transport_adc(transport_class): "transport_name", [ "grpc", + "rest", ], ) def test_transport_kind(transport_name): @@ -1603,6 +2148,7 @@ def test_cloud_catalog_transport_auth_adc(transport_class): [ transports.CloudCatalogGrpcTransport, transports.CloudCatalogGrpcAsyncIOTransport, + transports.CloudCatalogRestTransport, ], ) def test_cloud_catalog_transport_auth_gdch_credentials(transport_class): @@ -1701,11 +2247,23 @@ def test_cloud_catalog_grpc_transport_client_cert_source_for_mtls(transport_clas ) +def test_cloud_catalog_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.CloudCatalogRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_cloud_catalog_host_no_port(transport_name): @@ -1716,7 +2274,11 @@ def test_cloud_catalog_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudbilling.googleapis.com:443") + assert client.transport._host == ( + "cloudbilling.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com" + ) @pytest.mark.parametrize( @@ -1724,6 +2286,7 @@ def test_cloud_catalog_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_cloud_catalog_host_with_port(transport_name): @@ -1734,7 +2297,36 @@ def test_cloud_catalog_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("cloudbilling.googleapis.com:8000") + assert client.transport._host == ( + "cloudbilling.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://cloudbilling.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_cloud_catalog_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = CloudCatalogClient( + credentials=creds1, + transport=transport_name, + ) + client2 = CloudCatalogClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_services._session + session2 = client2.transport.list_services._session + assert session1 != session2 + session1 = client1.transport.list_skus._session + session2 = client2.transport.list_skus._session + assert session1 != session2 def test_cloud_catalog_grpc_transport_channel(): @@ -2040,6 +2632,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -2057,6 +2650,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: