diff --git a/google/cloud/bigquery_reservation_v1/gapic_metadata.json b/google/cloud/bigquery_reservation_v1/gapic_metadata.json index 1ccca0ff..582310e2 100644 --- a/google/cloud/bigquery_reservation_v1/gapic_metadata.json +++ b/google/cloud/bigquery_reservation_v1/gapic_metadata.json @@ -226,6 +226,116 @@ ] } } + }, + "rest": { + "libraryClient": "ReservationServiceClient", + "rpcs": { + "CreateAssignment": { + "methods": [ + "create_assignment" + ] + }, + "CreateCapacityCommitment": { + "methods": [ + "create_capacity_commitment" + ] + }, + "CreateReservation": { + "methods": [ + "create_reservation" + ] + }, + "DeleteAssignment": { + "methods": [ + "delete_assignment" + ] + }, + "DeleteCapacityCommitment": { + "methods": [ + "delete_capacity_commitment" + ] + }, + "DeleteReservation": { + "methods": [ + "delete_reservation" + ] + }, + "GetBiReservation": { + "methods": [ + "get_bi_reservation" + ] + }, + "GetCapacityCommitment": { + "methods": [ + "get_capacity_commitment" + ] + }, + "GetReservation": { + "methods": [ + "get_reservation" + ] + }, + "ListAssignments": { + "methods": [ + "list_assignments" + ] + }, + "ListCapacityCommitments": { + "methods": [ + "list_capacity_commitments" + ] + }, + "ListReservations": { + "methods": [ + "list_reservations" + ] + }, + "MergeCapacityCommitments": { + "methods": [ + "merge_capacity_commitments" + ] + }, + "MoveAssignment": { + "methods": [ + "move_assignment" + ] + }, + "SearchAllAssignments": { + "methods": [ + "search_all_assignments" + ] + }, + "SearchAssignments": { + "methods": [ + "search_assignments" + ] + }, + "SplitCapacityCommitment": { + "methods": [ + "split_capacity_commitment" + ] + }, + "UpdateAssignment": { + "methods": [ + "update_assignment" + ] + }, + "UpdateBiReservation": { + "methods": [ + "update_bi_reservation" + ] + }, + "UpdateCapacityCommitment": { + "methods": [ + "update_capacity_commitment" + ] + }, + "UpdateReservation": { + "methods": [ + "update_reservation" + ] + } + } } } } diff --git a/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py b/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py index 02ef5b74..b96170a7 100644 --- a/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py +++ b/google/cloud/bigquery_reservation_v1/services/reservation_service/client.py @@ -58,6 +58,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, ReservationServiceTransport from .transports.grpc import ReservationServiceGrpcTransport from .transports.grpc_asyncio import ReservationServiceGrpcAsyncIOTransport +from .transports.rest import ReservationServiceRestTransport class ReservationServiceClientMeta(type): @@ -73,6 +74,7 @@ class ReservationServiceClientMeta(type): ) # type: Dict[str, Type[ReservationServiceTransport]] _transport_registry["grpc"] = ReservationServiceGrpcTransport _transport_registry["grpc_asyncio"] = ReservationServiceGrpcAsyncIOTransport + _transport_registry["rest"] = ReservationServiceRestTransport def get_transport_class( cls, diff --git a/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/__init__.py b/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/__init__.py index 41ef8651..f317136b 100644 --- a/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/__init__.py +++ b/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/__init__.py @@ -19,6 +19,7 @@ from .base import ReservationServiceTransport from .grpc import ReservationServiceGrpcTransport from .grpc_asyncio import ReservationServiceGrpcAsyncIOTransport +from .rest import ReservationServiceRestInterceptor, ReservationServiceRestTransport # Compile a registry of transports. _transport_registry = ( @@ -26,9 +27,12 @@ ) # type: Dict[str, Type[ReservationServiceTransport]] _transport_registry["grpc"] = ReservationServiceGrpcTransport _transport_registry["grpc_asyncio"] = ReservationServiceGrpcAsyncIOTransport +_transport_registry["rest"] = ReservationServiceRestTransport __all__ = ( "ReservationServiceTransport", "ReservationServiceGrpcTransport", "ReservationServiceGrpcAsyncIOTransport", + "ReservationServiceRestTransport", + "ReservationServiceRestInterceptor", ) diff --git a/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py b/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py new file mode 100644 index 00000000..c49df9e5 --- /dev/null +++ b/google/cloud/bigquery_reservation_v1/services/reservation_service/transports/rest.py @@ -0,0 +1,2982 @@ +# -*- 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.protobuf import empty_pb2 # type: ignore + +from google.cloud.bigquery_reservation_v1.types import reservation as gcbr_reservation +from google.cloud.bigquery_reservation_v1.types import reservation + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import ReservationServiceTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class ReservationServiceRestInterceptor: + """Interceptor for ReservationService. + + 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 ReservationServiceRestTransport. + + .. code-block:: python + class MyCustomReservationServiceInterceptor(ReservationServiceRestInterceptor): + def pre_create_assignment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_assignment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_capacity_commitment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_capacity_commitment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_create_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_create_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_assignment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_capacity_commitment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_delete_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def pre_get_bi_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_bi_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_capacity_commitment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_capacity_commitment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_assignments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_assignments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_capacity_commitments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_capacity_commitments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_reservations(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_reservations(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_merge_capacity_commitments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_merge_capacity_commitments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_move_assignment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_move_assignment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_all_assignments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_all_assignments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_search_assignments(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_search_assignments(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_split_capacity_commitment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_split_capacity_commitment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_assignment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_assignment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_bi_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_bi_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_capacity_commitment(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_capacity_commitment(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_reservation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_reservation(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReservationServiceRestTransport(interceptor=MyCustomReservationServiceInterceptor()) + client = ReservationServiceClient(transport=transport) + + + """ + + def pre_create_assignment( + self, + request: reservation.CreateAssignmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.CreateAssignmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_assignment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_create_assignment( + self, response: reservation.Assignment + ) -> reservation.Assignment: + """Post-rpc interceptor for create_assignment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_create_capacity_commitment( + self, + request: reservation.CreateCapacityCommitmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.CreateCapacityCommitmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_capacity_commitment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_create_capacity_commitment( + self, response: reservation.CapacityCommitment + ) -> reservation.CapacityCommitment: + """Post-rpc interceptor for create_capacity_commitment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_create_reservation( + self, + request: gcbr_reservation.CreateReservationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcbr_reservation.CreateReservationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for create_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_create_reservation( + self, response: gcbr_reservation.Reservation + ) -> gcbr_reservation.Reservation: + """Post-rpc interceptor for create_reservation + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_delete_assignment( + self, + request: reservation.DeleteAssignmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.DeleteAssignmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_assignment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def pre_delete_capacity_commitment( + self, + request: reservation.DeleteCapacityCommitmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.DeleteCapacityCommitmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_capacity_commitment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def pre_delete_reservation( + self, + request: reservation.DeleteReservationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.DeleteReservationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for delete_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def pre_get_bi_reservation( + self, + request: reservation.GetBiReservationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.GetBiReservationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_bi_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_get_bi_reservation( + self, response: reservation.BiReservation + ) -> reservation.BiReservation: + """Post-rpc interceptor for get_bi_reservation + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_get_capacity_commitment( + self, + request: reservation.GetCapacityCommitmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.GetCapacityCommitmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_capacity_commitment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_get_capacity_commitment( + self, response: reservation.CapacityCommitment + ) -> reservation.CapacityCommitment: + """Post-rpc interceptor for get_capacity_commitment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_get_reservation( + self, + request: reservation.GetReservationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.GetReservationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_get_reservation( + self, response: reservation.Reservation + ) -> reservation.Reservation: + """Post-rpc interceptor for get_reservation + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_list_assignments( + self, + request: reservation.ListAssignmentsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.ListAssignmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_assignments + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_list_assignments( + self, response: reservation.ListAssignmentsResponse + ) -> reservation.ListAssignmentsResponse: + """Post-rpc interceptor for list_assignments + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_list_capacity_commitments( + self, + request: reservation.ListCapacityCommitmentsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.ListCapacityCommitmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_capacity_commitments + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_list_capacity_commitments( + self, response: reservation.ListCapacityCommitmentsResponse + ) -> reservation.ListCapacityCommitmentsResponse: + """Post-rpc interceptor for list_capacity_commitments + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_list_reservations( + self, + request: reservation.ListReservationsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.ListReservationsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_reservations + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_list_reservations( + self, response: reservation.ListReservationsResponse + ) -> reservation.ListReservationsResponse: + """Post-rpc interceptor for list_reservations + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_merge_capacity_commitments( + self, + request: reservation.MergeCapacityCommitmentsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.MergeCapacityCommitmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for merge_capacity_commitments + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_merge_capacity_commitments( + self, response: reservation.CapacityCommitment + ) -> reservation.CapacityCommitment: + """Post-rpc interceptor for merge_capacity_commitments + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_move_assignment( + self, + request: reservation.MoveAssignmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.MoveAssignmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for move_assignment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_move_assignment( + self, response: reservation.Assignment + ) -> reservation.Assignment: + """Post-rpc interceptor for move_assignment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_search_all_assignments( + self, + request: reservation.SearchAllAssignmentsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.SearchAllAssignmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_all_assignments + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_search_all_assignments( + self, response: reservation.SearchAllAssignmentsResponse + ) -> reservation.SearchAllAssignmentsResponse: + """Post-rpc interceptor for search_all_assignments + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_search_assignments( + self, + request: reservation.SearchAssignmentsRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.SearchAssignmentsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for search_assignments + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_search_assignments( + self, response: reservation.SearchAssignmentsResponse + ) -> reservation.SearchAssignmentsResponse: + """Post-rpc interceptor for search_assignments + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_split_capacity_commitment( + self, + request: reservation.SplitCapacityCommitmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.SplitCapacityCommitmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for split_capacity_commitment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_split_capacity_commitment( + self, response: reservation.SplitCapacityCommitmentResponse + ) -> reservation.SplitCapacityCommitmentResponse: + """Post-rpc interceptor for split_capacity_commitment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_update_assignment( + self, + request: reservation.UpdateAssignmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.UpdateAssignmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_assignment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_update_assignment( + self, response: reservation.Assignment + ) -> reservation.Assignment: + """Post-rpc interceptor for update_assignment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_update_bi_reservation( + self, + request: reservation.UpdateBiReservationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.UpdateBiReservationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_bi_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_update_bi_reservation( + self, response: reservation.BiReservation + ) -> reservation.BiReservation: + """Post-rpc interceptor for update_bi_reservation + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_update_capacity_commitment( + self, + request: reservation.UpdateCapacityCommitmentRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[reservation.UpdateCapacityCommitmentRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_capacity_commitment + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_update_capacity_commitment( + self, response: reservation.CapacityCommitment + ) -> reservation.CapacityCommitment: + """Post-rpc interceptor for update_capacity_commitment + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + def pre_update_reservation( + self, + request: gcbr_reservation.UpdateReservationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcbr_reservation.UpdateReservationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_reservation + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationService server. + """ + return request, metadata + + def post_update_reservation( + self, response: gcbr_reservation.Reservation + ) -> gcbr_reservation.Reservation: + """Post-rpc interceptor for update_reservation + + Override in a subclass to manipulate the response + after it is returned by the ReservationService server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class ReservationServiceRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReservationServiceRestInterceptor + + +class ReservationServiceRestTransport(ReservationServiceTransport): + """REST backend transport for ReservationService. + + This API allows users to manage their flat-rate BigQuery + reservations. + + A reservation provides computational resource guarantees, in the + form of `slots `__, to + users. A slot is a unit of computational power in BigQuery, and + serves as the basic unit of parallelism. In a scan of a + multi-partitioned table, a single slot operates on a single + partition of the table. A reservation resource exists as a child + resource of the admin project and location, e.g.: + ``projects/myproject/locations/US/reservations/reservationName``. + + A capacity commitment is a way to purchase compute capacity for + BigQuery jobs (in the form of slots) with some committed period of + usage. A capacity commitment resource exists as a child resource of + the admin project and location, e.g.: + ``projects/myproject/locations/US/capacityCommitments/id``. + + 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 = "bigqueryreservation.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[ReservationServiceRestInterceptor] = 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 ReservationServiceRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _CreateAssignment(ReservationServiceRestStub): + def __hash__(self): + return hash("CreateAssignment") + + __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: reservation.CreateAssignmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.Assignment: + r"""Call the create assignment method over HTTP. + + Args: + request (~.reservation.CreateAssignmentRequest): + The request object. The request for + [ReservationService.CreateAssignment][google.cloud.bigquery.reservation.v1.ReservationService.CreateAssignment]. + Note: "bigquery.reservationAssignments.create" + permission is required on the related assignee. + + 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: + ~.reservation.Assignment: + An assignment allows a project to + submit jobs of a certain type using + slots from the specified reservation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/reservations/*}/assignments", + "body": "assignment", + }, + ] + request, metadata = self._interceptor.pre_create_assignment( + request, metadata + ) + pb_request = reservation.CreateAssignmentRequest.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 = reservation.Assignment() + pb_resp = reservation.Assignment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_assignment(resp) + return resp + + class _CreateCapacityCommitment(ReservationServiceRestStub): + def __hash__(self): + return hash("CreateCapacityCommitment") + + __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: reservation.CreateCapacityCommitmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.CapacityCommitment: + r"""Call the create capacity + commitment method over HTTP. + + Args: + request (~.reservation.CreateCapacityCommitmentRequest): + The request object. The request for + [ReservationService.CreateCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.CreateCapacityCommitment]. + + 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: + ~.reservation.CapacityCommitment: + Capacity commitment is a way to + purchase compute capacity for BigQuery + jobs (in the form of slots) with some + committed period of usage. Annual + commitments renew by default. + Commitments can be removed after their + commitment end time passes. + + In order to remove annual commitment, + its plan needs to be changed to monthly + or flex first. + + A capacity commitment resource exists as + a child resource of the admin project. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/capacityCommitments", + "body": "capacity_commitment", + }, + ] + request, metadata = self._interceptor.pre_create_capacity_commitment( + request, metadata + ) + pb_request = reservation.CreateCapacityCommitmentRequest.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 = reservation.CapacityCommitment() + pb_resp = reservation.CapacityCommitment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_capacity_commitment(resp) + return resp + + class _CreateReservation(ReservationServiceRestStub): + def __hash__(self): + return hash("CreateReservation") + + __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: gcbr_reservation.CreateReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcbr_reservation.Reservation: + r"""Call the create reservation method over HTTP. + + Args: + request (~.gcbr_reservation.CreateReservationRequest): + The request object. The request for + [ReservationService.CreateReservation][google.cloud.bigquery.reservation.v1.ReservationService.CreateReservation]. + + 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: + ~.gcbr_reservation.Reservation: + A reservation is a mechanism used to + guarantee slots to users. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/reservations", + "body": "reservation", + }, + ] + request, metadata = self._interceptor.pre_create_reservation( + request, metadata + ) + pb_request = gcbr_reservation.CreateReservationRequest.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 = gcbr_reservation.Reservation() + pb_resp = gcbr_reservation.Reservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_create_reservation(resp) + return resp + + class _DeleteAssignment(ReservationServiceRestStub): + def __hash__(self): + return hash("DeleteAssignment") + + __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: reservation.DeleteAssignmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete assignment method over HTTP. + + Args: + request (~.reservation.DeleteAssignmentRequest): + The request object. The request for + [ReservationService.DeleteAssignment][google.cloud.bigquery.reservation.v1.ReservationService.DeleteAssignment]. + Note: "bigquery.reservationAssignments.delete" + permission is required on the related assignee. + + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/reservations/*/assignments/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_assignment( + request, metadata + ) + pb_request = reservation.DeleteAssignmentRequest.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) + + class _DeleteCapacityCommitment(ReservationServiceRestStub): + def __hash__(self): + return hash("DeleteCapacityCommitment") + + __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: reservation.DeleteCapacityCommitmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete capacity + commitment method over HTTP. + + Args: + request (~.reservation.DeleteCapacityCommitmentRequest): + The request object. The request for + [ReservationService.DeleteCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.DeleteCapacityCommitment]. + + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/capacityCommitments/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_capacity_commitment( + request, metadata + ) + pb_request = reservation.DeleteCapacityCommitmentRequest.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) + + class _DeleteReservation(ReservationServiceRestStub): + def __hash__(self): + return hash("DeleteReservation") + + __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: reservation.DeleteReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ): + r"""Call the delete reservation method over HTTP. + + Args: + request (~.reservation.DeleteReservationRequest): + The request object. The request for + [ReservationService.DeleteReservation][google.cloud.bigquery.reservation.v1.ReservationService.DeleteReservation]. + + 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. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "delete", + "uri": "/v1/{name=projects/*/locations/*/reservations/*}", + }, + ] + request, metadata = self._interceptor.pre_delete_reservation( + request, metadata + ) + pb_request = reservation.DeleteReservationRequest.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) + + class _GetBiReservation(ReservationServiceRestStub): + def __hash__(self): + return hash("GetBiReservation") + + __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: reservation.GetBiReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.BiReservation: + r"""Call the get bi reservation method over HTTP. + + Args: + request (~.reservation.GetBiReservationRequest): + The request object. A request to get a singleton BI + reservation. + + 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: + ~.reservation.BiReservation: + Represents a BI Reservation. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/biReservation}", + }, + ] + request, metadata = self._interceptor.pre_get_bi_reservation( + request, metadata + ) + pb_request = reservation.GetBiReservationRequest.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 = reservation.BiReservation() + pb_resp = reservation.BiReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_bi_reservation(resp) + return resp + + class _GetCapacityCommitment(ReservationServiceRestStub): + def __hash__(self): + return hash("GetCapacityCommitment") + + __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: reservation.GetCapacityCommitmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.CapacityCommitment: + r"""Call the get capacity commitment method over HTTP. + + Args: + request (~.reservation.GetCapacityCommitmentRequest): + The request object. The request for + [ReservationService.GetCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.GetCapacityCommitment]. + + 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: + ~.reservation.CapacityCommitment: + Capacity commitment is a way to + purchase compute capacity for BigQuery + jobs (in the form of slots) with some + committed period of usage. Annual + commitments renew by default. + Commitments can be removed after their + commitment end time passes. + + In order to remove annual commitment, + its plan needs to be changed to monthly + or flex first. + + A capacity commitment resource exists as + a child resource of the admin project. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/capacityCommitments/*}", + }, + ] + request, metadata = self._interceptor.pre_get_capacity_commitment( + request, metadata + ) + pb_request = reservation.GetCapacityCommitmentRequest.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 = reservation.CapacityCommitment() + pb_resp = reservation.CapacityCommitment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_capacity_commitment(resp) + return resp + + class _GetReservation(ReservationServiceRestStub): + def __hash__(self): + return hash("GetReservation") + + __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: reservation.GetReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.Reservation: + r"""Call the get reservation method over HTTP. + + Args: + request (~.reservation.GetReservationRequest): + The request object. The request for + [ReservationService.GetReservation][google.cloud.bigquery.reservation.v1.ReservationService.GetReservation]. + + 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: + ~.reservation.Reservation: + A reservation is a mechanism used to + guarantee slots to users. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/reservations/*}", + }, + ] + request, metadata = self._interceptor.pre_get_reservation(request, metadata) + pb_request = reservation.GetReservationRequest.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 = reservation.Reservation() + pb_resp = reservation.Reservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_reservation(resp) + return resp + + class _ListAssignments(ReservationServiceRestStub): + def __hash__(self): + return hash("ListAssignments") + + __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: reservation.ListAssignmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.ListAssignmentsResponse: + r"""Call the list assignments method over HTTP. + + Args: + request (~.reservation.ListAssignmentsRequest): + The request object. The request for + [ReservationService.ListAssignments][google.cloud.bigquery.reservation.v1.ReservationService.ListAssignments]. + + 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: + ~.reservation.ListAssignmentsResponse: + The response for + [ReservationService.ListAssignments][google.cloud.bigquery.reservation.v1.ReservationService.ListAssignments]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/reservations/*}/assignments", + }, + ] + request, metadata = self._interceptor.pre_list_assignments( + request, metadata + ) + pb_request = reservation.ListAssignmentsRequest.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 = reservation.ListAssignmentsResponse() + pb_resp = reservation.ListAssignmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_assignments(resp) + return resp + + class _ListCapacityCommitments(ReservationServiceRestStub): + def __hash__(self): + return hash("ListCapacityCommitments") + + __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: reservation.ListCapacityCommitmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.ListCapacityCommitmentsResponse: + r"""Call the list capacity commitments method over HTTP. + + Args: + request (~.reservation.ListCapacityCommitmentsRequest): + The request object. The request for + [ReservationService.ListCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.ListCapacityCommitments]. + + 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: + ~.reservation.ListCapacityCommitmentsResponse: + The response for + [ReservationService.ListCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.ListCapacityCommitments]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/capacityCommitments", + }, + ] + request, metadata = self._interceptor.pre_list_capacity_commitments( + request, metadata + ) + pb_request = reservation.ListCapacityCommitmentsRequest.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 = reservation.ListCapacityCommitmentsResponse() + pb_resp = reservation.ListCapacityCommitmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_capacity_commitments(resp) + return resp + + class _ListReservations(ReservationServiceRestStub): + def __hash__(self): + return hash("ListReservations") + + __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: reservation.ListReservationsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.ListReservationsResponse: + r"""Call the list reservations method over HTTP. + + Args: + request (~.reservation.ListReservationsRequest): + The request object. The request for + [ReservationService.ListReservations][google.cloud.bigquery.reservation.v1.ReservationService.ListReservations]. + + 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: + ~.reservation.ListReservationsResponse: + The response for + [ReservationService.ListReservations][google.cloud.bigquery.reservation.v1.ReservationService.ListReservations]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}/reservations", + }, + ] + request, metadata = self._interceptor.pre_list_reservations( + request, metadata + ) + pb_request = reservation.ListReservationsRequest.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 = reservation.ListReservationsResponse() + pb_resp = reservation.ListReservationsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_reservations(resp) + return resp + + class _MergeCapacityCommitments(ReservationServiceRestStub): + def __hash__(self): + return hash("MergeCapacityCommitments") + + def __call__( + self, + request: reservation.MergeCapacityCommitmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.CapacityCommitment: + r"""Call the merge capacity + commitments method over HTTP. + + Args: + request (~.reservation.MergeCapacityCommitmentsRequest): + The request object. The request for + [ReservationService.MergeCapacityCommitments][google.cloud.bigquery.reservation.v1.ReservationService.MergeCapacityCommitments]. + + 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: + ~.reservation.CapacityCommitment: + Capacity commitment is a way to + purchase compute capacity for BigQuery + jobs (in the form of slots) with some + committed period of usage. Annual + commitments renew by default. + Commitments can be removed after their + commitment end time passes. + + In order to remove annual commitment, + its plan needs to be changed to monthly + or flex first. + + A capacity commitment resource exists as + a child resource of the admin project. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}/capacityCommitments:merge", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_merge_capacity_commitments( + request, metadata + ) + pb_request = reservation.MergeCapacityCommitmentsRequest.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["$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 = reservation.CapacityCommitment() + pb_resp = reservation.CapacityCommitment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_merge_capacity_commitments(resp) + return resp + + class _MoveAssignment(ReservationServiceRestStub): + def __hash__(self): + return hash("MoveAssignment") + + __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: reservation.MoveAssignmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.Assignment: + r"""Call the move assignment method over HTTP. + + Args: + request (~.reservation.MoveAssignmentRequest): + The request object. The request for + [ReservationService.MoveAssignment][google.cloud.bigquery.reservation.v1.ReservationService.MoveAssignment]. + + **Note**: "bigquery.reservationAssignments.create" + permission is required on the destination_id. + + **Note**: "bigquery.reservationAssignments.create" and + "bigquery.reservationAssignments.delete" permission are + required on the related assignee. + + 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: + ~.reservation.Assignment: + An assignment allows a project to + submit jobs of a certain type using + slots from the specified reservation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/reservations/*/assignments/*}:move", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_move_assignment(request, metadata) + pb_request = reservation.MoveAssignmentRequest.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 = reservation.Assignment() + pb_resp = reservation.Assignment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_move_assignment(resp) + return resp + + class _SearchAllAssignments(ReservationServiceRestStub): + def __hash__(self): + return hash("SearchAllAssignments") + + __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: reservation.SearchAllAssignmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.SearchAllAssignmentsResponse: + r"""Call the search all assignments method over HTTP. + + Args: + request (~.reservation.SearchAllAssignmentsRequest): + The request object. The request for + [ReservationService.SearchAllAssignments][google.cloud.bigquery.reservation.v1.ReservationService.SearchAllAssignments]. + Note: "bigquery.reservationAssignments.search" + permission is required on the related assignee. + + 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: + ~.reservation.SearchAllAssignmentsResponse: + The response for + [ReservationService.SearchAllAssignments][google.cloud.bigquery.reservation.v1.ReservationService.SearchAllAssignments]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}:searchAllAssignments", + }, + ] + request, metadata = self._interceptor.pre_search_all_assignments( + request, metadata + ) + pb_request = reservation.SearchAllAssignmentsRequest.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 = reservation.SearchAllAssignmentsResponse() + pb_resp = reservation.SearchAllAssignmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_all_assignments(resp) + return resp + + class _SearchAssignments(ReservationServiceRestStub): + def __hash__(self): + return hash("SearchAssignments") + + __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: reservation.SearchAssignmentsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.SearchAssignmentsResponse: + r"""Call the search assignments method over HTTP. + + Args: + request (~.reservation.SearchAssignmentsRequest): + The request object. The request for + [ReservationService.SearchAssignments][google.cloud.bigquery.reservation.v1.ReservationService.SearchAssignments]. + Note: "bigquery.reservationAssignments.search" + permission is required on the related assignee. + + 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: + ~.reservation.SearchAssignmentsResponse: + The response for + [ReservationService.SearchAssignments][google.cloud.bigquery.reservation.v1.ReservationService.SearchAssignments]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*}:searchAssignments", + }, + ] + request, metadata = self._interceptor.pre_search_assignments( + request, metadata + ) + pb_request = reservation.SearchAssignmentsRequest.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 = reservation.SearchAssignmentsResponse() + pb_resp = reservation.SearchAssignmentsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_search_assignments(resp) + return resp + + class _SplitCapacityCommitment(ReservationServiceRestStub): + def __hash__(self): + return hash("SplitCapacityCommitment") + + __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: reservation.SplitCapacityCommitmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.SplitCapacityCommitmentResponse: + r"""Call the split capacity commitment method over HTTP. + + Args: + request (~.reservation.SplitCapacityCommitmentRequest): + The request object. The request for + [ReservationService.SplitCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.SplitCapacityCommitment]. + + 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: + ~.reservation.SplitCapacityCommitmentResponse: + The response for + [ReservationService.SplitCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.SplitCapacityCommitment]. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/capacityCommitments/*}:split", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_split_capacity_commitment( + request, metadata + ) + pb_request = reservation.SplitCapacityCommitmentRequest.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 = reservation.SplitCapacityCommitmentResponse() + pb_resp = reservation.SplitCapacityCommitmentResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_split_capacity_commitment(resp) + return resp + + class _UpdateAssignment(ReservationServiceRestStub): + def __hash__(self): + return hash("UpdateAssignment") + + def __call__( + self, + request: reservation.UpdateAssignmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.Assignment: + r"""Call the update assignment method over HTTP. + + Args: + request (~.reservation.UpdateAssignmentRequest): + The request object. The request for + [ReservationService.UpdateAssignment][google.cloud.bigquery.reservation.v1.ReservationService.UpdateAssignment]. + + 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: + ~.reservation.Assignment: + An assignment allows a project to + submit jobs of a certain type using + slots from the specified reservation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{assignment.name=projects/*/locations/*/reservations/*/assignments/*}", + "body": "assignment", + }, + ] + request, metadata = self._interceptor.pre_update_assignment( + request, metadata + ) + pb_request = reservation.UpdateAssignmentRequest.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["$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 = reservation.Assignment() + pb_resp = reservation.Assignment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_assignment(resp) + return resp + + class _UpdateBiReservation(ReservationServiceRestStub): + def __hash__(self): + return hash("UpdateBiReservation") + + def __call__( + self, + request: reservation.UpdateBiReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.BiReservation: + r"""Call the update bi reservation method over HTTP. + + Args: + request (~.reservation.UpdateBiReservationRequest): + The request object. A request to update a BI reservation. + 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: + ~.reservation.BiReservation: + Represents a BI Reservation. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{bi_reservation.name=projects/*/locations/*/biReservation}", + "body": "bi_reservation", + }, + ] + request, metadata = self._interceptor.pre_update_bi_reservation( + request, metadata + ) + pb_request = reservation.UpdateBiReservationRequest.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["$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 = reservation.BiReservation() + pb_resp = reservation.BiReservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_bi_reservation(resp) + return resp + + class _UpdateCapacityCommitment(ReservationServiceRestStub): + def __hash__(self): + return hash("UpdateCapacityCommitment") + + def __call__( + self, + request: reservation.UpdateCapacityCommitmentRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> reservation.CapacityCommitment: + r"""Call the update capacity + commitment method over HTTP. + + Args: + request (~.reservation.UpdateCapacityCommitmentRequest): + The request object. The request for + [ReservationService.UpdateCapacityCommitment][google.cloud.bigquery.reservation.v1.ReservationService.UpdateCapacityCommitment]. + + 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: + ~.reservation.CapacityCommitment: + Capacity commitment is a way to + purchase compute capacity for BigQuery + jobs (in the form of slots) with some + committed period of usage. Annual + commitments renew by default. + Commitments can be removed after their + commitment end time passes. + + In order to remove annual commitment, + its plan needs to be changed to monthly + or flex first. + + A capacity commitment resource exists as + a child resource of the admin project. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{capacity_commitment.name=projects/*/locations/*/capacityCommitments/*}", + "body": "capacity_commitment", + }, + ] + request, metadata = self._interceptor.pre_update_capacity_commitment( + request, metadata + ) + pb_request = reservation.UpdateCapacityCommitmentRequest.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["$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 = reservation.CapacityCommitment() + pb_resp = reservation.CapacityCommitment.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_capacity_commitment(resp) + return resp + + class _UpdateReservation(ReservationServiceRestStub): + def __hash__(self): + return hash("UpdateReservation") + + def __call__( + self, + request: gcbr_reservation.UpdateReservationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcbr_reservation.Reservation: + r"""Call the update reservation method over HTTP. + + Args: + request (~.gcbr_reservation.UpdateReservationRequest): + The request object. The request for + [ReservationService.UpdateReservation][google.cloud.bigquery.reservation.v1.ReservationService.UpdateReservation]. + + 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: + ~.gcbr_reservation.Reservation: + A reservation is a mechanism used to + guarantee slots to users. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v1/{reservation.name=projects/*/locations/*/reservations/*}", + "body": "reservation", + }, + ] + request, metadata = self._interceptor.pre_update_reservation( + request, metadata + ) + pb_request = gcbr_reservation.UpdateReservationRequest.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["$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 = gcbr_reservation.Reservation() + pb_resp = gcbr_reservation.Reservation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_reservation(resp) + return resp + + @property + def create_assignment( + self, + ) -> Callable[[reservation.CreateAssignmentRequest], reservation.Assignment]: + # 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._CreateAssignment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_capacity_commitment( + self, + ) -> Callable[ + [reservation.CreateCapacityCommitmentRequest], reservation.CapacityCommitment + ]: + # 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._CreateCapacityCommitment(self._session, self._host, self._interceptor) # type: ignore + + @property + def create_reservation( + self, + ) -> Callable[ + [gcbr_reservation.CreateReservationRequest], gcbr_reservation.Reservation + ]: + # 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._CreateReservation(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_assignment( + self, + ) -> Callable[[reservation.DeleteAssignmentRequest], empty_pb2.Empty]: + # 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._DeleteAssignment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_capacity_commitment( + self, + ) -> Callable[[reservation.DeleteCapacityCommitmentRequest], empty_pb2.Empty]: + # 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._DeleteCapacityCommitment(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_reservation( + self, + ) -> Callable[[reservation.DeleteReservationRequest], empty_pb2.Empty]: + # 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._DeleteReservation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_bi_reservation( + self, + ) -> Callable[[reservation.GetBiReservationRequest], reservation.BiReservation]: + # 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._GetBiReservation(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_capacity_commitment( + self, + ) -> Callable[ + [reservation.GetCapacityCommitmentRequest], reservation.CapacityCommitment + ]: + # 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._GetCapacityCommitment(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_reservation( + self, + ) -> Callable[[reservation.GetReservationRequest], reservation.Reservation]: + # 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._GetReservation(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_assignments( + self, + ) -> Callable[ + [reservation.ListAssignmentsRequest], reservation.ListAssignmentsResponse + ]: + # 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._ListAssignments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_capacity_commitments( + self, + ) -> Callable[ + [reservation.ListCapacityCommitmentsRequest], + reservation.ListCapacityCommitmentsResponse, + ]: + # 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._ListCapacityCommitments(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_reservations( + self, + ) -> Callable[ + [reservation.ListReservationsRequest], reservation.ListReservationsResponse + ]: + # 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._ListReservations(self._session, self._host, self._interceptor) # type: ignore + + @property + def merge_capacity_commitments( + self, + ) -> Callable[ + [reservation.MergeCapacityCommitmentsRequest], reservation.CapacityCommitment + ]: + # 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._MergeCapacityCommitments(self._session, self._host, self._interceptor) # type: ignore + + @property + def move_assignment( + self, + ) -> Callable[[reservation.MoveAssignmentRequest], reservation.Assignment]: + # 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._MoveAssignment(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_all_assignments( + self, + ) -> Callable[ + [reservation.SearchAllAssignmentsRequest], + reservation.SearchAllAssignmentsResponse, + ]: + # 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._SearchAllAssignments(self._session, self._host, self._interceptor) # type: ignore + + @property + def search_assignments( + self, + ) -> Callable[ + [reservation.SearchAssignmentsRequest], reservation.SearchAssignmentsResponse + ]: + # 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._SearchAssignments(self._session, self._host, self._interceptor) # type: ignore + + @property + def split_capacity_commitment( + self, + ) -> Callable[ + [reservation.SplitCapacityCommitmentRequest], + reservation.SplitCapacityCommitmentResponse, + ]: + # 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._SplitCapacityCommitment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_assignment( + self, + ) -> Callable[[reservation.UpdateAssignmentRequest], reservation.Assignment]: + # 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._UpdateAssignment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_bi_reservation( + self, + ) -> Callable[[reservation.UpdateBiReservationRequest], reservation.BiReservation]: + # 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._UpdateBiReservation(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_capacity_commitment( + self, + ) -> Callable[ + [reservation.UpdateCapacityCommitmentRequest], reservation.CapacityCommitment + ]: + # 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._UpdateCapacityCommitment(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_reservation( + self, + ) -> Callable[ + [gcbr_reservation.UpdateReservationRequest], gcbr_reservation.Reservation + ]: + # 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._UpdateReservation(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ReservationServiceRestTransport",) diff --git a/samples/snippets/conftest.py b/samples/snippets/conftest.py index 320cc074..1801372f 100644 --- a/samples/snippets/conftest.py +++ b/samples/snippets/conftest.py @@ -42,8 +42,10 @@ def project_id() -> str: @pytest.fixture(scope="session") -def reservation_client() -> reservation_service.ReservationServiceClient: - return reservation_service.ReservationServiceClient() +def reservation_client( + transport: str = "grpc", +) -> reservation_service.ReservationServiceClient: + return reservation_service.ReservationServiceClient(transport=transport) @pytest.fixture(scope="session") diff --git a/samples/snippets/quickstart.py b/samples/snippets/quickstart.py index eb1227ca..2452da9d 100644 --- a/samples/snippets/quickstart.py +++ b/samples/snippets/quickstart.py @@ -18,9 +18,11 @@ from google.cloud import bigquery_reservation_v1 -def main(project_id: str = "your-project-id", location: str = "US") -> None: +def main( + project_id: str = "your-project-id", location: str = "US", transport: str = "grpc" +) -> None: # Constructs the client for interacting with the service. - client = bigquery_reservation_v1.ReservationServiceClient() + client = bigquery_reservation_v1.ReservationServiceClient(transport=transport) report_capacity_commitments(client, project_id, location) report_reservations(client, project_id, location) diff --git a/samples/snippets/quickstart_test.py b/samples/snippets/quickstart_test.py index 3ade3e40..85a0a872 100644 --- a/samples/snippets/quickstart_test.py +++ b/samples/snippets/quickstart_test.py @@ -17,7 +17,10 @@ from . import quickstart -def test_quickstart(capsys: pytest.CaptureFixture, project_id: str) -> None: - quickstart.main(project_id) +@pytest.mark.parametrize("transport", ["grpc", "rest"]) +def test_quickstart( + capsys: pytest.CaptureFixture, project_id: str, transport: str +) -> None: + quickstart.main(project_id=project_id, transport=transport) out, _ = capsys.readouterr() assert " reservations processed." in out diff --git a/samples/snippets/reservation_create.py b/samples/snippets/reservation_create.py index bae295e8..efaaefe3 100644 --- a/samples/snippets/reservation_create.py +++ b/samples/snippets/reservation_create.py @@ -16,12 +16,17 @@ def create_reservation( - project_id: str, location: str, reservation_id: str, slot_capacity: str + project_id: str, + location: str, + reservation_id: str, + slot_capacity: str, + transport: str, ) -> reservation_types.Reservation: original_project_id = project_id original_location = location original_reservation_id = reservation_id original_slot_capacity = slot_capacity + original_transport = transport # [START bigqueryreservation_reservation_create] # TODO(developer): Set project_id to the project ID containing the @@ -40,11 +45,15 @@ def create_reservation( # reservation. slot_capacity = 100 + # TODO(developer): Choose a transport to use. Either 'grpc' or 'rest' + transport = "grpc" + # [START_EXCLUDE] project_id = original_project_id location = original_location reservation_id = original_reservation_id slot_capacity = original_slot_capacity + transport = original_transport # [END_EXCLUDE] from google.cloud.bigquery_reservation_v1.services import reservation_service @@ -52,7 +61,9 @@ def create_reservation( reservation as reservation_types, ) - reservation_client = reservation_service.ReservationServiceClient() + reservation_client = reservation_service.ReservationServiceClient( + transport=transport + ) parent = reservation_client.common_location_path(project_id, location) diff --git a/samples/snippets/reservation_delete.py b/samples/snippets/reservation_delete.py index b0537b5e..a0f25ce1 100644 --- a/samples/snippets/reservation_delete.py +++ b/samples/snippets/reservation_delete.py @@ -13,10 +13,13 @@ # limitations under the License. -def delete_reservation(project_id: str, location: str, reservation_id: str) -> None: +def delete_reservation( + project_id: str, location: str, reservation_id: str, transport: str +) -> None: original_project_id = project_id original_location = location original_reservation_id = reservation_id + original_transport = transport # [START bigqueryreservation_reservation_delete] # TODO(developer): Set project_id to the project ID containing the @@ -31,15 +34,21 @@ def delete_reservation(project_id: str, location: str, reservation_id: str) -> N # TODO(developer): Set reservation_id to a unique ID of the reservation. reservation_id = "sample-reservation" + # TODO(developer): Choose a transport to use. Either 'grpc' or 'rest' + transport = "grpc" + # [START_EXCLUDE] project_id = original_project_id location = original_location reservation_id = original_reservation_id + transport = original_transport # [END_EXCLUDE] from google.cloud.bigquery_reservation_v1.services import reservation_service - reservation_client = reservation_service.ReservationServiceClient() + reservation_client = reservation_service.ReservationServiceClient( + transport=transport + ) reservation_name = reservation_client.reservation_path( project_id, location, reservation_id ) diff --git a/samples/snippets/reservation_test.py b/samples/snippets/reservation_test.py index e92fe9e9..1270ba23 100644 --- a/samples/snippets/reservation_test.py +++ b/samples/snippets/reservation_test.py @@ -51,12 +51,17 @@ def reservation_id( pass +@pytest.mark.parametrize("transport", ["grpc", "rest"]) def test_reservation_samples( - capsys: pytest.CaptureFixture, project_id: str, location: str, reservation_id: str + capsys: pytest.CaptureFixture, + project_id: str, + location: str, + reservation_id: str, + transport: str, ) -> None: slot_capacity = 100 reservation = reservation_create.create_reservation( - project_id, location, reservation_id, slot_capacity + project_id, location, reservation_id, slot_capacity, transport ) assert reservation.slot_capacity == 100 assert reservation_id in reservation.name @@ -65,14 +70,16 @@ def test_reservation_samples( slot_capacity = 50 reservation = reservation_update.update_reservation( - project_id, location, reservation_id, slot_capacity + project_id, location, reservation_id, slot_capacity, transport ) assert reservation.slot_capacity == 50 assert reservation_id in reservation.name out, _ = capsys.readouterr() assert f"Updated reservation: {reservation.name}" in out - reservation_delete.delete_reservation(project_id, location, reservation_id) + reservation_delete.delete_reservation( + project_id, location, reservation_id, transport + ) out, _ = capsys.readouterr() assert "Deleted reservation" in out assert reservation_id in out diff --git a/samples/snippets/reservation_update.py b/samples/snippets/reservation_update.py index d43a96dc..8afbd9d7 100644 --- a/samples/snippets/reservation_update.py +++ b/samples/snippets/reservation_update.py @@ -16,12 +16,17 @@ def update_reservation( - project_id: str, location: str, reservation_id: str, slot_capacity: str + project_id: str, + location: str, + reservation_id: str, + slot_capacity: str, + transport: str, ) -> reservation_types.Reservation: original_project_id = project_id original_location = location original_reservation_id = reservation_id original_slot_capacity = slot_capacity + original_transport = transport # [START bigqueryreservation_reservation_update] # TODO(developer): Set project_id to the project ID containing the @@ -40,11 +45,15 @@ def update_reservation( # reservation. slot_capacity = 50 + # TODO(developer): Choose a transport to use. Either 'grpc' or 'rest' + transport = "grpc" + # [START_EXCLUDE] project_id = original_project_id location = original_location reservation_id = original_reservation_id slot_capacity = original_slot_capacity + transport = original_transport # [END_EXCLUDE] from google.cloud.bigquery_reservation_v1.services import reservation_service @@ -53,7 +62,9 @@ def update_reservation( ) from google.protobuf import field_mask_pb2 - reservation_client = reservation_service.ReservationServiceClient() + reservation_client = reservation_service.ReservationServiceClient( + transport=transport + ) reservation_name = reservation_client.reservation_path( project_id, location, reservation_id diff --git a/tests/system.py b/tests/system.py index adfe657e..a5ddc78a 100644 --- a/tests/system.py +++ b/tests/system.py @@ -26,8 +26,9 @@ def project_id(): return os.environ["PROJECT_ID"] -def test_list_reservations(project_id): - client = bigquery_reservation.ReservationServiceClient() +@pytest.mark.parametrize("transport", ["grpc", "rest"]) +def test_list_reservations(project_id: str, transport: str): + client = bigquery_reservation.ReservationServiceClient(transport=transport) parent = f"projects/{project_id}/locations/US" reservations = list(client.list_reservations(parent=parent)) diff --git a/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py b/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py index 3c022872..20286e43 100644 --- a/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.py +++ b/tests/unit/gapic/bigquery_reservation_v1/test_reservation_service.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 @@ -33,6 +35,7 @@ from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore import grpc @@ -40,6 +43,8 @@ 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.bigquery_reservation_v1.services.reservation_service import ( ReservationServiceAsyncClient, @@ -101,6 +106,7 @@ def test__get_default_mtls_endpoint(): [ (ReservationServiceClient, "grpc"), (ReservationServiceAsyncClient, "grpc_asyncio"), + (ReservationServiceClient, "rest"), ], ) def test_reservation_service_client_from_service_account_info( @@ -116,7 +122,11 @@ def test_reservation_service_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("bigqueryreservation.googleapis.com:443") + assert client.transport._host == ( + "bigqueryreservation.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://bigqueryreservation.googleapis.com" + ) @pytest.mark.parametrize( @@ -124,6 +134,7 @@ def test_reservation_service_client_from_service_account_info( [ (transports.ReservationServiceGrpcTransport, "grpc"), (transports.ReservationServiceGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.ReservationServiceRestTransport, "rest"), ], ) def test_reservation_service_client_service_account_always_use_jwt( @@ -149,6 +160,7 @@ def test_reservation_service_client_service_account_always_use_jwt( [ (ReservationServiceClient, "grpc"), (ReservationServiceAsyncClient, "grpc_asyncio"), + (ReservationServiceClient, "rest"), ], ) def test_reservation_service_client_from_service_account_file( @@ -171,13 +183,18 @@ def test_reservation_service_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("bigqueryreservation.googleapis.com:443") + assert client.transport._host == ( + "bigqueryreservation.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://bigqueryreservation.googleapis.com" + ) def test_reservation_service_client_get_transport_class(): transport = ReservationServiceClient.get_transport_class() available_transports = [ transports.ReservationServiceGrpcTransport, + transports.ReservationServiceRestTransport, ] assert transport in available_transports @@ -194,6 +211,7 @@ def test_reservation_service_client_get_transport_class(): transports.ReservationServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ReservationServiceClient, transports.ReservationServiceRestTransport, "rest"), ], ) @mock.patch.object( @@ -349,6 +367,18 @@ def test_reservation_service_client_client_options( "grpc_asyncio", "false", ), + ( + ReservationServiceClient, + transports.ReservationServiceRestTransport, + "rest", + "true", + ), + ( + ReservationServiceClient, + transports.ReservationServiceRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -548,6 +578,7 @@ def test_reservation_service_client_get_mtls_endpoint_and_cert_source(client_cla transports.ReservationServiceGrpcAsyncIOTransport, "grpc_asyncio", ), + (ReservationServiceClient, transports.ReservationServiceRestTransport, "rest"), ], ) def test_reservation_service_client_client_options_scopes( @@ -588,6 +619,12 @@ def test_reservation_service_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + ReservationServiceClient, + transports.ReservationServiceRestTransport, + "rest", + None, + ), ], ) def test_reservation_service_client_client_options_credentials_file( @@ -7069,153 +7106,6059 @@ async def test_update_bi_reservation_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.ReservationServiceGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + gcbr_reservation.CreateReservationRequest, + dict, + ], +) +def test_create_reservation_rest(request_type): + client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = ReservationServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["reservation"] = { + "name": "name_value", + "slot_capacity": 1391, + "ignore_idle_slots": True, + "concurrency": 1195, + "creation_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "multi_region_auxiliary": 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 = gcbr_reservation.Reservation( + name="name_value", + slot_capacity=1391, + ignore_idle_slots=True, + concurrency=1195, + multi_region_auxiliary=True, ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.ReservationServiceGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = ReservationServiceClient( - 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 = gcbr_reservation.Reservation.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_reservation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcbr_reservation.Reservation) + assert response.name == "name_value" + assert response.slot_capacity == 1391 + assert response.ignore_idle_slots is True + assert response.concurrency == 1195 + assert response.multi_region_auxiliary is True + + +def test_create_reservation_rest_required_fields( + request_type=gcbr_reservation.CreateReservationRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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, ) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.ReservationServiceGrpcTransport( + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_reservation._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() + ).create_reservation._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("reservation_id",)) + 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 = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = ReservationServiceClient( - client_options=options, - transport=transport, - ) + request = request_type(**request_init) - # 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 = ReservationServiceClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Designate an appropriate value for the returned response. + return_value = gcbr_reservation.Reservation() + # 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 - # It is an error to provide scopes and a transport instance. - transport = transports.ReservationServiceGrpcTransport( + response_value = Response() + response_value.status_code = 200 + + pb_return_value = gcbr_reservation.Reservation.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_reservation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_reservation_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_reservation._get_unset_required_fields({}) + assert set(unset_fields) == (set(("reservationId",)) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_reservation_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), ) - with pytest.raises(ValueError): - client = ReservationServiceClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_create_reservation" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_create_reservation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcbr_reservation.CreateReservationRequest.pb( + gcbr_reservation.CreateReservationRequest() + ) + 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 = gcbr_reservation.Reservation.to_json( + gcbr_reservation.Reservation() ) + request = gcbr_reservation.CreateReservationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcbr_reservation.Reservation() -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReservationServiceGrpcTransport( + client.create_reservation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_reservation_rest_bad_request( + transport: str = "rest", request_type=gcbr_reservation.CreateReservationRequest +): + client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - client = ReservationServiceClient(transport=transport) - assert client.transport is transport + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["reservation"] = { + "name": "name_value", + "slot_capacity": 1391, + "ignore_idle_slots": True, + "concurrency": 1195, + "creation_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "multi_region_auxiliary": True, + } + request = request_type(**request_init) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.ReservationServiceGrpcTransport( + # 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_reservation(request) + + +def test_create_reservation_rest_flattened(): + client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - channel = transport.grpc_channel - assert channel - transport = transports.ReservationServiceGrpcAsyncIOTransport( + # 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 = gcbr_reservation.Reservation() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + reservation=gcbr_reservation.Reservation(name="name_value"), + reservation_id="reservation_id_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 = gcbr_reservation.Reservation.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_reservation(**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=projects/*/locations/*}/reservations" + % client.transport._host, + args[1], + ) + + +def test_create_reservation_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_reservation( + gcbr_reservation.CreateReservationRequest(), + parent="parent_value", + reservation=gcbr_reservation.Reservation(name="name_value"), + reservation_id="reservation_id_value", + ) -@pytest.mark.parametrize( - "transport_class", - [ - transports.ReservationServiceGrpcTransport, - transports.ReservationServiceGrpcAsyncIOTransport, - ], -) -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() + +def test_create_reservation_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + reservation.ListReservationsRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = ReservationServiceClient.get_transport_class(transport_name)( +def test_list_reservations_rest(request_type): + client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = reservation.ListReservationsResponse( + 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 = reservation.ListReservationsResponse.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_reservations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReservationsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_reservations_rest_required_fields( + request_type=reservation.ListReservationsRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_reservations._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_reservations._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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = ReservationServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.ReservationServiceGrpcTransport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.ListReservationsResponse() + # 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 = reservation.ListReservationsResponse.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_reservations(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_reservations_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) + unset_fields = transport.list_reservations._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) -def test_reservation_service_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.ReservationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_reservations_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_list_reservations" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_list_reservations" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.ListReservationsRequest.pb( + reservation.ListReservationsRequest() + ) + 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 = reservation.ListReservationsResponse.to_json( + reservation.ListReservationsResponse() ) + request = reservation.ListReservationsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.ListReservationsResponse() -def test_reservation_service_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.bigquery_reservation_v1.services.reservation_service.transports.ReservationServiceTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.ReservationServiceTransport( - credentials=ga_credentials.AnonymousCredentials(), + client.list_reservations( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_reservation", - "list_reservations", - "get_reservation", - "delete_reservation", - "update_reservation", - "create_capacity_commitment", - "list_capacity_commitments", - "get_capacity_commitment", - "delete_capacity_commitment", - "update_capacity_commitment", + pre.assert_called_once() + post.assert_called_once() + + +def test_list_reservations_rest_bad_request( + transport: str = "rest", request_type=reservation.ListReservationsRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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_reservations(request) + + +def test_list_reservations_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.ListReservationsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # 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 = reservation.ListReservationsResponse.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_reservations(**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=projects/*/locations/*}/reservations" + % client.transport._host, + args[1], + ) + + +def test_list_reservations_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_reservations( + reservation.ListReservationsRequest(), + parent="parent_value", + ) + + +def test_list_reservations_rest_pager(transport: str = "rest"): + client = ReservationServiceClient( + 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 = ( + reservation.ListReservationsResponse( + reservations=[ + reservation.Reservation(), + reservation.Reservation(), + reservation.Reservation(), + ], + next_page_token="abc", + ), + reservation.ListReservationsResponse( + reservations=[], + next_page_token="def", + ), + reservation.ListReservationsResponse( + reservations=[ + reservation.Reservation(), + ], + next_page_token="ghi", + ), + reservation.ListReservationsResponse( + reservations=[ + reservation.Reservation(), + reservation.Reservation(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + reservation.ListReservationsResponse.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": "projects/sample1/locations/sample2"} + + pager = client.list_reservations(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reservation.Reservation) for i in results) + + pages = list(client.list_reservations(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", + [ + reservation.GetReservationRequest, + dict, + ], +) +def test_get_reservation_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/reservations/sample3"} + 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 = reservation.Reservation( + name="name_value", + slot_capacity=1391, + ignore_idle_slots=True, + concurrency=1195, + multi_region_auxiliary=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.Reservation.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_reservation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.Reservation) + assert response.name == "name_value" + assert response.slot_capacity == 1391 + assert response.ignore_idle_slots is True + assert response.concurrency == 1195 + assert response.multi_region_auxiliary is True + + +def test_get_reservation_rest_required_fields( + request_type=reservation.GetReservationRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_reservation._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_reservation._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.Reservation() + # 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 = reservation.Reservation.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_reservation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_reservation_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_reservation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_reservation_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_get_reservation" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_get_reservation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.GetReservationRequest.pb( + reservation.GetReservationRequest() + ) + 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 = reservation.Reservation.to_json( + reservation.Reservation() + ) + + request = reservation.GetReservationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.Reservation() + + client.get_reservation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_reservation_rest_bad_request( + transport: str = "rest", request_type=reservation.GetReservationRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/reservations/sample3"} + 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_reservation(request) + + +def test_get_reservation_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.Reservation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/reservations/sample3" + } + + # 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 = reservation.Reservation.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_reservation(**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/*/locations/*/reservations/*}" + % client.transport._host, + args[1], + ) + + +def test_get_reservation_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_reservation( + reservation.GetReservationRequest(), + name="name_value", + ) + + +def test_get_reservation_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.DeleteReservationRequest, + dict, + ], +) +def test_delete_reservation_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/reservations/sample3"} + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_reservation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_reservation_rest_required_fields( + request_type=reservation.DeleteReservationRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).delete_reservation._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() + ).delete_reservation._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_reservation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_reservation_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_reservation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_reservation_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "pre_delete_reservation" + ) as pre: + pre.assert_not_called() + pb_message = reservation.DeleteReservationRequest.pb( + reservation.DeleteReservationRequest() + ) + 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() + + request = reservation.DeleteReservationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_reservation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_reservation_rest_bad_request( + transport: str = "rest", request_type=reservation.DeleteReservationRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/reservations/sample3"} + 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.delete_reservation(request) + + +def test_delete_reservation_rest_flattened(): + client = ReservationServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/reservations/sample3" + } + + # 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 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_reservation(**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/*/locations/*/reservations/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_reservation_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.delete_reservation( + reservation.DeleteReservationRequest(), + name="name_value", + ) + + +def test_delete_reservation_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcbr_reservation.UpdateReservationRequest, + dict, + ], +) +def test_update_reservation_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "reservation": { + "name": "projects/sample1/locations/sample2/reservations/sample3" + } + } + request_init["reservation"] = { + "name": "projects/sample1/locations/sample2/reservations/sample3", + "slot_capacity": 1391, + "ignore_idle_slots": True, + "concurrency": 1195, + "creation_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "multi_region_auxiliary": 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 = gcbr_reservation.Reservation( + name="name_value", + slot_capacity=1391, + ignore_idle_slots=True, + concurrency=1195, + multi_region_auxiliary=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = gcbr_reservation.Reservation.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_reservation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, gcbr_reservation.Reservation) + assert response.name == "name_value" + assert response.slot_capacity == 1391 + assert response.ignore_idle_slots is True + assert response.concurrency == 1195 + assert response.multi_region_auxiliary is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_reservation_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_update_reservation" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_update_reservation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcbr_reservation.UpdateReservationRequest.pb( + gcbr_reservation.UpdateReservationRequest() + ) + 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 = gcbr_reservation.Reservation.to_json( + gcbr_reservation.Reservation() + ) + + request = gcbr_reservation.UpdateReservationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = gcbr_reservation.Reservation() + + client.update_reservation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_reservation_rest_bad_request( + transport: str = "rest", request_type=gcbr_reservation.UpdateReservationRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "reservation": { + "name": "projects/sample1/locations/sample2/reservations/sample3" + } + } + request_init["reservation"] = { + "name": "projects/sample1/locations/sample2/reservations/sample3", + "slot_capacity": 1391, + "ignore_idle_slots": True, + "concurrency": 1195, + "creation_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "multi_region_auxiliary": 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_reservation(request) + + +def test_update_reservation_rest_flattened(): + client = ReservationServiceClient( + 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 = gcbr_reservation.Reservation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "reservation": { + "name": "projects/sample1/locations/sample2/reservations/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + reservation=gcbr_reservation.Reservation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = gcbr_reservation.Reservation.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_reservation(**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/{reservation.name=projects/*/locations/*/reservations/*}" + % client.transport._host, + args[1], + ) + + +def test_update_reservation_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_reservation( + gcbr_reservation.UpdateReservationRequest(), + reservation=gcbr_reservation.Reservation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_reservation_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.CreateCapacityCommitmentRequest, + dict, + ], +) +def test_create_capacity_commitment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["capacity_commitment"] = { + "name": "name_value", + "slot_count": 1098, + "plan": 3, + "state": 1, + "commitment_start_time": {"seconds": 751, "nanos": 543}, + "commitment_end_time": {}, + "failure_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "renewal_plan": 3, + "multi_region_auxiliary": 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 = reservation.CapacityCommitment( + name="name_value", + slot_count=1098, + plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + state=reservation.CapacityCommitment.State.PENDING, + renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + multi_region_auxiliary=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.CapacityCommitment.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_capacity_commitment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.CapacityCommitment) + assert response.name == "name_value" + assert response.slot_count == 1098 + assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.state == reservation.CapacityCommitment.State.PENDING + assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.multi_region_auxiliary is True + + +def test_create_capacity_commitment_rest_required_fields( + request_type=reservation.CreateCapacityCommitmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).create_capacity_commitment._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() + ).create_capacity_commitment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "capacity_commitment_id", + "enforce_single_admin_project_per_org", + ) + ) + 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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.CapacityCommitment() + # 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 = reservation.CapacityCommitment.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_capacity_commitment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_capacity_commitment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_capacity_commitment._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "capacityCommitmentId", + "enforceSingleAdminProjectPerOrg", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_capacity_commitment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_create_capacity_commitment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_create_capacity_commitment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.CreateCapacityCommitmentRequest.pb( + reservation.CreateCapacityCommitmentRequest() + ) + 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 = reservation.CapacityCommitment.to_json( + reservation.CapacityCommitment() + ) + + request = reservation.CreateCapacityCommitmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.CapacityCommitment() + + client.create_capacity_commitment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_capacity_commitment_rest_bad_request( + transport: str = "rest", request_type=reservation.CreateCapacityCommitmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["capacity_commitment"] = { + "name": "name_value", + "slot_count": 1098, + "plan": 3, + "state": 1, + "commitment_start_time": {"seconds": 751, "nanos": 543}, + "commitment_end_time": {}, + "failure_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "renewal_plan": 3, + "multi_region_auxiliary": 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.create_capacity_commitment(request) + + +def test_create_capacity_commitment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.CapacityCommitment() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + capacity_commitment=reservation.CapacityCommitment(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 = reservation.CapacityCommitment.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_capacity_commitment(**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=projects/*/locations/*}/capacityCommitments" + % client.transport._host, + args[1], + ) + + +def test_create_capacity_commitment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_capacity_commitment( + reservation.CreateCapacityCommitmentRequest(), + parent="parent_value", + capacity_commitment=reservation.CapacityCommitment(name="name_value"), + ) + + +def test_create_capacity_commitment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.ListCapacityCommitmentsRequest, + dict, + ], +) +def test_list_capacity_commitments_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = reservation.ListCapacityCommitmentsResponse( + 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 = reservation.ListCapacityCommitmentsResponse.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_capacity_commitments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListCapacityCommitmentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_capacity_commitments_rest_required_fields( + request_type=reservation.ListCapacityCommitmentsRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_capacity_commitments._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_capacity_commitments._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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.ListCapacityCommitmentsResponse() + # 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 = reservation.ListCapacityCommitmentsResponse.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_capacity_commitments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_capacity_commitments_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_capacity_commitments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_capacity_commitments_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_list_capacity_commitments" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_list_capacity_commitments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.ListCapacityCommitmentsRequest.pb( + reservation.ListCapacityCommitmentsRequest() + ) + 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 = reservation.ListCapacityCommitmentsResponse.to_json( + reservation.ListCapacityCommitmentsResponse() + ) + + request = reservation.ListCapacityCommitmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.ListCapacityCommitmentsResponse() + + client.list_capacity_commitments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_capacity_commitments_rest_bad_request( + transport: str = "rest", request_type=reservation.ListCapacityCommitmentsRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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_capacity_commitments(request) + + +def test_list_capacity_commitments_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.ListCapacityCommitmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # 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 = reservation.ListCapacityCommitmentsResponse.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_capacity_commitments(**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=projects/*/locations/*}/capacityCommitments" + % client.transport._host, + args[1], + ) + + +def test_list_capacity_commitments_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_capacity_commitments( + reservation.ListCapacityCommitmentsRequest(), + parent="parent_value", + ) + + +def test_list_capacity_commitments_rest_pager(transport: str = "rest"): + client = ReservationServiceClient( + 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 = ( + reservation.ListCapacityCommitmentsResponse( + capacity_commitments=[ + reservation.CapacityCommitment(), + reservation.CapacityCommitment(), + reservation.CapacityCommitment(), + ], + next_page_token="abc", + ), + reservation.ListCapacityCommitmentsResponse( + capacity_commitments=[], + next_page_token="def", + ), + reservation.ListCapacityCommitmentsResponse( + capacity_commitments=[ + reservation.CapacityCommitment(), + ], + next_page_token="ghi", + ), + reservation.ListCapacityCommitmentsResponse( + capacity_commitments=[ + reservation.CapacityCommitment(), + reservation.CapacityCommitment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + reservation.ListCapacityCommitmentsResponse.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": "projects/sample1/locations/sample2"} + + pager = client.list_capacity_commitments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reservation.CapacityCommitment) for i in results) + + pages = list(client.list_capacity_commitments(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", + [ + reservation.GetCapacityCommitmentRequest, + dict, + ], +) +def test_get_capacity_commitment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + 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 = reservation.CapacityCommitment( + name="name_value", + slot_count=1098, + plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + state=reservation.CapacityCommitment.State.PENDING, + renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + multi_region_auxiliary=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.CapacityCommitment.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_capacity_commitment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.CapacityCommitment) + assert response.name == "name_value" + assert response.slot_count == 1098 + assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.state == reservation.CapacityCommitment.State.PENDING + assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.multi_region_auxiliary is True + + +def test_get_capacity_commitment_rest_required_fields( + request_type=reservation.GetCapacityCommitmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_capacity_commitment._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_capacity_commitment._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.CapacityCommitment() + # 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 = reservation.CapacityCommitment.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_capacity_commitment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_capacity_commitment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_capacity_commitment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_capacity_commitment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_get_capacity_commitment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_get_capacity_commitment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.GetCapacityCommitmentRequest.pb( + reservation.GetCapacityCommitmentRequest() + ) + 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 = reservation.CapacityCommitment.to_json( + reservation.CapacityCommitment() + ) + + request = reservation.GetCapacityCommitmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.CapacityCommitment() + + client.get_capacity_commitment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_capacity_commitment_rest_bad_request( + transport: str = "rest", request_type=reservation.GetCapacityCommitmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + 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_capacity_commitment(request) + + +def test_get_capacity_commitment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.CapacityCommitment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + + # 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 = reservation.CapacityCommitment.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_capacity_commitment(**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/*/locations/*/capacityCommitments/*}" + % client.transport._host, + args[1], + ) + + +def test_get_capacity_commitment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_capacity_commitment( + reservation.GetCapacityCommitmentRequest(), + name="name_value", + ) + + +def test_get_capacity_commitment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.DeleteCapacityCommitmentRequest, + dict, + ], +) +def test_delete_capacity_commitment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_capacity_commitment(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_capacity_commitment_rest_required_fields( + request_type=reservation.DeleteCapacityCommitmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).delete_capacity_commitment._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() + ).delete_capacity_commitment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("force",)) + 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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_capacity_commitment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_capacity_commitment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_capacity_commitment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("force",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_capacity_commitment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "pre_delete_capacity_commitment" + ) as pre: + pre.assert_not_called() + pb_message = reservation.DeleteCapacityCommitmentRequest.pb( + reservation.DeleteCapacityCommitmentRequest() + ) + 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() + + request = reservation.DeleteCapacityCommitmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_capacity_commitment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_capacity_commitment_rest_bad_request( + transport: str = "rest", request_type=reservation.DeleteCapacityCommitmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + 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.delete_capacity_commitment(request) + + +def test_delete_capacity_commitment_rest_flattened(): + client = ReservationServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + + # 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 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_capacity_commitment(**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/*/locations/*/capacityCommitments/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_capacity_commitment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.delete_capacity_commitment( + reservation.DeleteCapacityCommitmentRequest(), + name="name_value", + ) + + +def test_delete_capacity_commitment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.UpdateCapacityCommitmentRequest, + dict, + ], +) +def test_update_capacity_commitment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "capacity_commitment": { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + } + request_init["capacity_commitment"] = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3", + "slot_count": 1098, + "plan": 3, + "state": 1, + "commitment_start_time": {"seconds": 751, "nanos": 543}, + "commitment_end_time": {}, + "failure_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "renewal_plan": 3, + "multi_region_auxiliary": 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 = reservation.CapacityCommitment( + name="name_value", + slot_count=1098, + plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + state=reservation.CapacityCommitment.State.PENDING, + renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + multi_region_auxiliary=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.CapacityCommitment.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_capacity_commitment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.CapacityCommitment) + assert response.name == "name_value" + assert response.slot_count == 1098 + assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.state == reservation.CapacityCommitment.State.PENDING + assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.multi_region_auxiliary is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_capacity_commitment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_update_capacity_commitment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_update_capacity_commitment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.UpdateCapacityCommitmentRequest.pb( + reservation.UpdateCapacityCommitmentRequest() + ) + 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 = reservation.CapacityCommitment.to_json( + reservation.CapacityCommitment() + ) + + request = reservation.UpdateCapacityCommitmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.CapacityCommitment() + + client.update_capacity_commitment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_capacity_commitment_rest_bad_request( + transport: str = "rest", request_type=reservation.UpdateCapacityCommitmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "capacity_commitment": { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + } + request_init["capacity_commitment"] = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3", + "slot_count": 1098, + "plan": 3, + "state": 1, + "commitment_start_time": {"seconds": 751, "nanos": 543}, + "commitment_end_time": {}, + "failure_status": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + "renewal_plan": 3, + "multi_region_auxiliary": 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_capacity_commitment(request) + + +def test_update_capacity_commitment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.CapacityCommitment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "capacity_commitment": { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + capacity_commitment=reservation.CapacityCommitment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = reservation.CapacityCommitment.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_capacity_commitment(**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/{capacity_commitment.name=projects/*/locations/*/capacityCommitments/*}" + % client.transport._host, + args[1], + ) + + +def test_update_capacity_commitment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_capacity_commitment( + reservation.UpdateCapacityCommitmentRequest(), + capacity_commitment=reservation.CapacityCommitment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_capacity_commitment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.SplitCapacityCommitmentRequest, + dict, + ], +) +def test_split_capacity_commitment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + 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 = reservation.SplitCapacityCommitmentResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.SplitCapacityCommitmentResponse.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.split_capacity_commitment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.SplitCapacityCommitmentResponse) + + +def test_split_capacity_commitment_rest_required_fields( + request_type=reservation.SplitCapacityCommitmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).split_capacity_commitment._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() + ).split_capacity_commitment._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.SplitCapacityCommitmentResponse() + # 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 = reservation.SplitCapacityCommitmentResponse.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.split_capacity_commitment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_split_capacity_commitment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.split_capacity_commitment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_split_capacity_commitment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_split_capacity_commitment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_split_capacity_commitment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.SplitCapacityCommitmentRequest.pb( + reservation.SplitCapacityCommitmentRequest() + ) + 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 = reservation.SplitCapacityCommitmentResponse.to_json( + reservation.SplitCapacityCommitmentResponse() + ) + + request = reservation.SplitCapacityCommitmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.SplitCapacityCommitmentResponse() + + client.split_capacity_commitment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_split_capacity_commitment_rest_bad_request( + transport: str = "rest", request_type=reservation.SplitCapacityCommitmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + 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.split_capacity_commitment(request) + + +def test_split_capacity_commitment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.SplitCapacityCommitmentResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/capacityCommitments/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + slot_count=1098, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.SplitCapacityCommitmentResponse.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.split_capacity_commitment(**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/*/locations/*/capacityCommitments/*}:split" + % client.transport._host, + args[1], + ) + + +def test_split_capacity_commitment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.split_capacity_commitment( + reservation.SplitCapacityCommitmentRequest(), + name="name_value", + slot_count=1098, + ) + + +def test_split_capacity_commitment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.MergeCapacityCommitmentsRequest, + dict, + ], +) +def test_merge_capacity_commitments_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = reservation.CapacityCommitment( + name="name_value", + slot_count=1098, + plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + state=reservation.CapacityCommitment.State.PENDING, + renewal_plan=reservation.CapacityCommitment.CommitmentPlan.FLEX, + multi_region_auxiliary=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.CapacityCommitment.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.merge_capacity_commitments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.CapacityCommitment) + assert response.name == "name_value" + assert response.slot_count == 1098 + assert response.plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.state == reservation.CapacityCommitment.State.PENDING + assert response.renewal_plan == reservation.CapacityCommitment.CommitmentPlan.FLEX + assert response.multi_region_auxiliary is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_merge_capacity_commitments_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_merge_capacity_commitments" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_merge_capacity_commitments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.MergeCapacityCommitmentsRequest.pb( + reservation.MergeCapacityCommitmentsRequest() + ) + 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 = reservation.CapacityCommitment.to_json( + reservation.CapacityCommitment() + ) + + request = reservation.MergeCapacityCommitmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.CapacityCommitment() + + client.merge_capacity_commitments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_merge_capacity_commitments_rest_bad_request( + transport: str = "rest", request_type=reservation.MergeCapacityCommitmentsRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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.merge_capacity_commitments(request) + + +def test_merge_capacity_commitments_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.CapacityCommitment() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + capacity_commitment_ids=["capacity_commitment_ids_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 = reservation.CapacityCommitment.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.merge_capacity_commitments(**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=projects/*/locations/*}/capacityCommitments:merge" + % client.transport._host, + args[1], + ) + + +def test_merge_capacity_commitments_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.merge_capacity_commitments( + reservation.MergeCapacityCommitmentsRequest(), + parent="parent_value", + capacity_commitment_ids=["capacity_commitment_ids_value"], + ) + + +def test_merge_capacity_commitments_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.CreateAssignmentRequest, + dict, + ], +) +def test_create_assignment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/reservations/sample3"} + request_init["assignment"] = { + "name": "name_value", + "assignee": "assignee_value", + "job_type": 1, + "state": 1, + } + 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 = reservation.Assignment( + name="name_value", + assignee="assignee_value", + job_type=reservation.Assignment.JobType.PIPELINE, + state=reservation.Assignment.State.PENDING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.Assignment.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_assignment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.Assignment) + assert response.name == "name_value" + assert response.assignee == "assignee_value" + assert response.job_type == reservation.Assignment.JobType.PIPELINE + assert response.state == reservation.Assignment.State.PENDING + + +def test_create_assignment_rest_required_fields( + request_type=reservation.CreateAssignmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).create_assignment._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() + ).create_assignment._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("assignment_id",)) + 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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.Assignment() + # 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 = reservation.Assignment.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_assignment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_create_assignment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_assignment._get_unset_required_fields({}) + assert set(unset_fields) == (set(("assignmentId",)) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_assignment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_create_assignment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_create_assignment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.CreateAssignmentRequest.pb( + reservation.CreateAssignmentRequest() + ) + 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 = reservation.Assignment.to_json( + reservation.Assignment() + ) + + request = reservation.CreateAssignmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.Assignment() + + client.create_assignment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_create_assignment_rest_bad_request( + transport: str = "rest", request_type=reservation.CreateAssignmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/reservations/sample3"} + request_init["assignment"] = { + "name": "name_value", + "assignee": "assignee_value", + "job_type": 1, + "state": 1, + } + 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_assignment(request) + + +def test_create_assignment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.Assignment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/reservations/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + assignment=reservation.Assignment(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 = reservation.Assignment.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_assignment(**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=projects/*/locations/*/reservations/*}/assignments" + % client.transport._host, + args[1], + ) + + +def test_create_assignment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_assignment( + reservation.CreateAssignmentRequest(), + parent="parent_value", + assignment=reservation.Assignment(name="name_value"), + ) + + +def test_create_assignment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.ListAssignmentsRequest, + dict, + ], +) +def test_list_assignments_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/reservations/sample3"} + 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 = reservation.ListAssignmentsResponse( + 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 = reservation.ListAssignmentsResponse.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_assignments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAssignmentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_list_assignments_rest_required_fields( + request_type=reservation.ListAssignmentsRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_assignments._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_assignments._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 "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.ListAssignmentsResponse() + # 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 = reservation.ListAssignmentsResponse.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_assignments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_assignments_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_assignments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_assignments_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_list_assignments" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_list_assignments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.ListAssignmentsRequest.pb( + reservation.ListAssignmentsRequest() + ) + 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 = reservation.ListAssignmentsResponse.to_json( + reservation.ListAssignmentsResponse() + ) + + request = reservation.ListAssignmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.ListAssignmentsResponse() + + client.list_assignments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_assignments_rest_bad_request( + transport: str = "rest", request_type=reservation.ListAssignmentsRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/reservations/sample3"} + 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_assignments(request) + + +def test_list_assignments_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.ListAssignmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/reservations/sample3" + } + + # 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 = reservation.ListAssignmentsResponse.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_assignments(**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=projects/*/locations/*/reservations/*}/assignments" + % client.transport._host, + args[1], + ) + + +def test_list_assignments_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_assignments( + reservation.ListAssignmentsRequest(), + parent="parent_value", + ) + + +def test_list_assignments_rest_pager(transport: str = "rest"): + client = ReservationServiceClient( + 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 = ( + reservation.ListAssignmentsResponse( + assignments=[ + reservation.Assignment(), + reservation.Assignment(), + reservation.Assignment(), + ], + next_page_token="abc", + ), + reservation.ListAssignmentsResponse( + assignments=[], + next_page_token="def", + ), + reservation.ListAssignmentsResponse( + assignments=[ + reservation.Assignment(), + ], + next_page_token="ghi", + ), + reservation.ListAssignmentsResponse( + assignments=[ + reservation.Assignment(), + reservation.Assignment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + reservation.ListAssignmentsResponse.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": "projects/sample1/locations/sample2/reservations/sample3" + } + + pager = client.list_assignments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reservation.Assignment) for i in results) + + pages = list(client.list_assignments(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", + [ + reservation.DeleteAssignmentRequest, + dict, + ], +) +def test_delete_assignment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + 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 = None + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.delete_assignment(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_assignment_rest_required_fields( + request_type=reservation.DeleteAssignmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).delete_assignment._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() + ).delete_assignment._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # 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": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = "" + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_assignment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_delete_assignment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_assignment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_assignment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "pre_delete_assignment" + ) as pre: + pre.assert_not_called() + pb_message = reservation.DeleteAssignmentRequest.pb( + reservation.DeleteAssignmentRequest() + ) + 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() + + request = reservation.DeleteAssignmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_assignment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_delete_assignment_rest_bad_request( + transport: str = "rest", request_type=reservation.DeleteAssignmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + 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.delete_assignment(request) + + +def test_delete_assignment_rest_flattened(): + client = ReservationServiceClient( + 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 = None + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + + # 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 + json_return_value = "" + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_assignment(**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/*/locations/*/reservations/*/assignments/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_assignment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.delete_assignment( + reservation.DeleteAssignmentRequest(), + name="name_value", + ) + + +def test_delete_assignment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.SearchAssignmentsRequest, + dict, + ], +) +def test_search_assignments_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = reservation.SearchAssignmentsResponse( + 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 = reservation.SearchAssignmentsResponse.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.search_assignments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAssignmentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_search_assignments_rest_required_fields( + request_type=reservation.SearchAssignmentsRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).search_assignments._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() + ).search_assignments._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", + "query", + ) + ) + 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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.SearchAssignmentsResponse() + # 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 = reservation.SearchAssignmentsResponse.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.search_assignments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_assignments_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_assignments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "query", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_assignments_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_search_assignments" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_search_assignments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.SearchAssignmentsRequest.pb( + reservation.SearchAssignmentsRequest() + ) + 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 = reservation.SearchAssignmentsResponse.to_json( + reservation.SearchAssignmentsResponse() + ) + + request = reservation.SearchAssignmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.SearchAssignmentsResponse() + + client.search_assignments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_assignments_rest_bad_request( + transport: str = "rest", request_type=reservation.SearchAssignmentsRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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.search_assignments(request) + + +def test_search_assignments_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.SearchAssignmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + query="query_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 = reservation.SearchAssignmentsResponse.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.search_assignments(**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=projects/*/locations/*}:searchAssignments" + % client.transport._host, + args[1], + ) + + +def test_search_assignments_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.search_assignments( + reservation.SearchAssignmentsRequest(), + parent="parent_value", + query="query_value", + ) + + +def test_search_assignments_rest_pager(transport: str = "rest"): + client = ReservationServiceClient( + 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 = ( + reservation.SearchAssignmentsResponse( + assignments=[ + reservation.Assignment(), + reservation.Assignment(), + reservation.Assignment(), + ], + next_page_token="abc", + ), + reservation.SearchAssignmentsResponse( + assignments=[], + next_page_token="def", + ), + reservation.SearchAssignmentsResponse( + assignments=[ + reservation.Assignment(), + ], + next_page_token="ghi", + ), + reservation.SearchAssignmentsResponse( + assignments=[ + reservation.Assignment(), + reservation.Assignment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + reservation.SearchAssignmentsResponse.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": "projects/sample1/locations/sample2"} + + pager = client.search_assignments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reservation.Assignment) for i in results) + + pages = list(client.search_assignments(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", + [ + reservation.SearchAllAssignmentsRequest, + dict, + ], +) +def test_search_all_assignments_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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 = reservation.SearchAllAssignmentsResponse( + 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 = reservation.SearchAllAssignmentsResponse.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.search_all_assignments(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.SearchAllAssignmentsPager) + assert response.next_page_token == "next_page_token_value" + + +def test_search_all_assignments_rest_required_fields( + request_type=reservation.SearchAllAssignmentsRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).search_all_assignments._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() + ).search_all_assignments._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", + "query", + ) + ) + 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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.SearchAllAssignmentsResponse() + # 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 = reservation.SearchAllAssignmentsResponse.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.search_all_assignments(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_search_all_assignments_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.search_all_assignments._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + "query", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_search_all_assignments_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_search_all_assignments" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_search_all_assignments" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.SearchAllAssignmentsRequest.pb( + reservation.SearchAllAssignmentsRequest() + ) + 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 = reservation.SearchAllAssignmentsResponse.to_json( + reservation.SearchAllAssignmentsResponse() + ) + + request = reservation.SearchAllAssignmentsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.SearchAllAssignmentsResponse() + + client.search_all_assignments( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_search_all_assignments_rest_bad_request( + transport: str = "rest", request_type=reservation.SearchAllAssignmentsRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + 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.search_all_assignments(request) + + +def test_search_all_assignments_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.SearchAllAssignmentsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + query="query_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 = reservation.SearchAllAssignmentsResponse.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.search_all_assignments(**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=projects/*/locations/*}:searchAllAssignments" + % client.transport._host, + args[1], + ) + + +def test_search_all_assignments_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.search_all_assignments( + reservation.SearchAllAssignmentsRequest(), + parent="parent_value", + query="query_value", + ) + + +def test_search_all_assignments_rest_pager(transport: str = "rest"): + client = ReservationServiceClient( + 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 = ( + reservation.SearchAllAssignmentsResponse( + assignments=[ + reservation.Assignment(), + reservation.Assignment(), + reservation.Assignment(), + ], + next_page_token="abc", + ), + reservation.SearchAllAssignmentsResponse( + assignments=[], + next_page_token="def", + ), + reservation.SearchAllAssignmentsResponse( + assignments=[ + reservation.Assignment(), + ], + next_page_token="ghi", + ), + reservation.SearchAllAssignmentsResponse( + assignments=[ + reservation.Assignment(), + reservation.Assignment(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + reservation.SearchAllAssignmentsResponse.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": "projects/sample1/locations/sample2"} + + pager = client.search_all_assignments(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, reservation.Assignment) for i in results) + + pages = list(client.search_all_assignments(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", + [ + reservation.MoveAssignmentRequest, + dict, + ], +) +def test_move_assignment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + 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 = reservation.Assignment( + name="name_value", + assignee="assignee_value", + job_type=reservation.Assignment.JobType.PIPELINE, + state=reservation.Assignment.State.PENDING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.Assignment.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.move_assignment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.Assignment) + assert response.name == "name_value" + assert response.assignee == "assignee_value" + assert response.job_type == reservation.Assignment.JobType.PIPELINE + assert response.state == reservation.Assignment.State.PENDING + + +def test_move_assignment_rest_required_fields( + request_type=reservation.MoveAssignmentRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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() + ).move_assignment._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() + ).move_assignment._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.Assignment() + # 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 = reservation.Assignment.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.move_assignment(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_move_assignment_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.move_assignment._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_move_assignment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_move_assignment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_move_assignment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.MoveAssignmentRequest.pb( + reservation.MoveAssignmentRequest() + ) + 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 = reservation.Assignment.to_json( + reservation.Assignment() + ) + + request = reservation.MoveAssignmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.Assignment() + + client.move_assignment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_move_assignment_rest_bad_request( + transport: str = "rest", request_type=reservation.MoveAssignmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + 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.move_assignment(request) + + +def test_move_assignment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.Assignment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + destination_id="destination_id_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 = reservation.Assignment.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.move_assignment(**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/*/locations/*/reservations/*/assignments/*}:move" + % client.transport._host, + args[1], + ) + + +def test_move_assignment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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.move_assignment( + reservation.MoveAssignmentRequest(), + name="name_value", + destination_id="destination_id_value", + ) + + +def test_move_assignment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.UpdateAssignmentRequest, + dict, + ], +) +def test_update_assignment_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "assignment": { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + } + request_init["assignment"] = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4", + "assignee": "assignee_value", + "job_type": 1, + "state": 1, + } + 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 = reservation.Assignment( + name="name_value", + assignee="assignee_value", + job_type=reservation.Assignment.JobType.PIPELINE, + state=reservation.Assignment.State.PENDING, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.Assignment.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_assignment(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.Assignment) + assert response.name == "name_value" + assert response.assignee == "assignee_value" + assert response.job_type == reservation.Assignment.JobType.PIPELINE + assert response.state == reservation.Assignment.State.PENDING + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_assignment_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_update_assignment" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_update_assignment" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.UpdateAssignmentRequest.pb( + reservation.UpdateAssignmentRequest() + ) + 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 = reservation.Assignment.to_json( + reservation.Assignment() + ) + + request = reservation.UpdateAssignmentRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.Assignment() + + client.update_assignment( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_assignment_rest_bad_request( + transport: str = "rest", request_type=reservation.UpdateAssignmentRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "assignment": { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + } + request_init["assignment"] = { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4", + "assignee": "assignee_value", + "job_type": 1, + "state": 1, + } + 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_assignment(request) + + +def test_update_assignment_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.Assignment() + + # get arguments that satisfy an http rule for this method + sample_request = { + "assignment": { + "name": "projects/sample1/locations/sample2/reservations/sample3/assignments/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + assignment=reservation.Assignment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = reservation.Assignment.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_assignment(**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/{assignment.name=projects/*/locations/*/reservations/*/assignments/*}" + % client.transport._host, + args[1], + ) + + +def test_update_assignment_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_assignment( + reservation.UpdateAssignmentRequest(), + assignment=reservation.Assignment(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_assignment_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.GetBiReservationRequest, + dict, + ], +) +def test_get_bi_reservation_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/biReservation"} + 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 = reservation.BiReservation( + name="name_value", + size=443, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.BiReservation.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_bi_reservation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.BiReservation) + assert response.name == "name_value" + assert response.size == 443 + + +def test_get_bi_reservation_rest_required_fields( + request_type=reservation.GetBiReservationRequest, +): + transport_class = transports.ReservationServiceRestTransport + + 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_bi_reservation._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_bi_reservation._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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = reservation.BiReservation() + # 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 = reservation.BiReservation.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_bi_reservation(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_bi_reservation_rest_unset_required_fields(): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_bi_reservation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_bi_reservation_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_get_bi_reservation" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_get_bi_reservation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.GetBiReservationRequest.pb( + reservation.GetBiReservationRequest() + ) + 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 = reservation.BiReservation.to_json( + reservation.BiReservation() + ) + + request = reservation.GetBiReservationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.BiReservation() + + client.get_bi_reservation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_bi_reservation_rest_bad_request( + transport: str = "rest", request_type=reservation.GetBiReservationRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/biReservation"} + 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_bi_reservation(request) + + +def test_get_bi_reservation_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.BiReservation() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/biReservation"} + + # 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 = reservation.BiReservation.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_bi_reservation(**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/*/locations/*/biReservation}" + % client.transport._host, + args[1], + ) + + +def test_get_bi_reservation_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_bi_reservation( + reservation.GetBiReservationRequest(), + name="name_value", + ) + + +def test_get_bi_reservation_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + reservation.UpdateBiReservationRequest, + dict, + ], +) +def test_update_bi_reservation_rest(request_type): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "bi_reservation": {"name": "projects/sample1/locations/sample2/biReservation"} + } + request_init["bi_reservation"] = { + "name": "projects/sample1/locations/sample2/biReservation", + "update_time": {"seconds": 751, "nanos": 543}, + "size": 443, + "preferred_tables": [ + { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "table_id": "table_id_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 = reservation.BiReservation( + name="name_value", + size=443, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = reservation.BiReservation.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_bi_reservation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, reservation.BiReservation) + assert response.name == "name_value" + assert response.size == 443 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_bi_reservation_rest_interceptors(null_interceptor): + transport = transports.ReservationServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationServiceRestInterceptor(), + ) + client = ReservationServiceClient(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.ReservationServiceRestInterceptor, "post_update_bi_reservation" + ) as post, mock.patch.object( + transports.ReservationServiceRestInterceptor, "pre_update_bi_reservation" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = reservation.UpdateBiReservationRequest.pb( + reservation.UpdateBiReservationRequest() + ) + 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 = reservation.BiReservation.to_json( + reservation.BiReservation() + ) + + request = reservation.UpdateBiReservationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = reservation.BiReservation() + + client.update_bi_reservation( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_bi_reservation_rest_bad_request( + transport: str = "rest", request_type=reservation.UpdateBiReservationRequest +): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "bi_reservation": {"name": "projects/sample1/locations/sample2/biReservation"} + } + request_init["bi_reservation"] = { + "name": "projects/sample1/locations/sample2/biReservation", + "update_time": {"seconds": 751, "nanos": 543}, + "size": 443, + "preferred_tables": [ + { + "project_id": "project_id_value", + "dataset_id": "dataset_id_value", + "table_id": "table_id_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_bi_reservation(request) + + +def test_update_bi_reservation_rest_flattened(): + client = ReservationServiceClient( + 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 = reservation.BiReservation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "bi_reservation": { + "name": "projects/sample1/locations/sample2/biReservation" + } + } + + # get truthy value for each flattened field + mock_args = dict( + bi_reservation=reservation.BiReservation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_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 = reservation.BiReservation.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_bi_reservation(**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/{bi_reservation.name=projects/*/locations/*/biReservation}" + % client.transport._host, + args[1], + ) + + +def test_update_bi_reservation_rest_flattened_error(transport: str = "rest"): + client = ReservationServiceClient( + 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_bi_reservation( + reservation.UpdateBiReservationRequest(), + bi_reservation=reservation.BiReservation(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_bi_reservation_rest_error(): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ReservationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReservationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReservationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReservationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReservationServiceClient( + 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 = ReservationServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReservationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReservationServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReservationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReservationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReservationServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.ReservationServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ReservationServiceGrpcTransport, + transports.ReservationServiceGrpcAsyncIOTransport, + transports.ReservationServiceRestTransport, + ], +) +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 = ReservationServiceClient.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 = ReservationServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.ReservationServiceGrpcTransport, + ) + + +def test_reservation_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReservationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_reservation_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.bigquery_reservation_v1.services.reservation_service.transports.ReservationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ReservationServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_reservation", + "list_reservations", + "get_reservation", + "delete_reservation", + "update_reservation", + "create_capacity_commitment", + "list_capacity_commitments", + "get_capacity_commitment", + "delete_capacity_commitment", + "update_capacity_commitment", "split_capacity_commitment", "merge_capacity_commitments", "create_assignment", @@ -7322,6 +13265,7 @@ def test_reservation_service_transport_auth_adc(transport_class): [ transports.ReservationServiceGrpcTransport, transports.ReservationServiceGrpcAsyncIOTransport, + transports.ReservationServiceRestTransport, ], ) def test_reservation_service_transport_auth_gdch_credentials(transport_class): @@ -7424,11 +13368,23 @@ def test_reservation_service_grpc_transport_client_cert_source_for_mtls( ) +def test_reservation_service_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.ReservationServiceRestTransport( + 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_reservation_service_host_no_port(transport_name): @@ -7439,7 +13395,11 @@ def test_reservation_service_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("bigqueryreservation.googleapis.com:443") + assert client.transport._host == ( + "bigqueryreservation.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://bigqueryreservation.googleapis.com" + ) @pytest.mark.parametrize( @@ -7447,6 +13407,7 @@ def test_reservation_service_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_reservation_service_host_with_port(transport_name): @@ -7457,7 +13418,93 @@ def test_reservation_service_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("bigqueryreservation.googleapis.com:8000") + assert client.transport._host == ( + "bigqueryreservation.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://bigqueryreservation.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_reservation_service_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReservationServiceClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReservationServiceClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.create_reservation._session + session2 = client2.transport.create_reservation._session + assert session1 != session2 + session1 = client1.transport.list_reservations._session + session2 = client2.transport.list_reservations._session + assert session1 != session2 + session1 = client1.transport.get_reservation._session + session2 = client2.transport.get_reservation._session + assert session1 != session2 + session1 = client1.transport.delete_reservation._session + session2 = client2.transport.delete_reservation._session + assert session1 != session2 + session1 = client1.transport.update_reservation._session + session2 = client2.transport.update_reservation._session + assert session1 != session2 + session1 = client1.transport.create_capacity_commitment._session + session2 = client2.transport.create_capacity_commitment._session + assert session1 != session2 + session1 = client1.transport.list_capacity_commitments._session + session2 = client2.transport.list_capacity_commitments._session + assert session1 != session2 + session1 = client1.transport.get_capacity_commitment._session + session2 = client2.transport.get_capacity_commitment._session + assert session1 != session2 + session1 = client1.transport.delete_capacity_commitment._session + session2 = client2.transport.delete_capacity_commitment._session + assert session1 != session2 + session1 = client1.transport.update_capacity_commitment._session + session2 = client2.transport.update_capacity_commitment._session + assert session1 != session2 + session1 = client1.transport.split_capacity_commitment._session + session2 = client2.transport.split_capacity_commitment._session + assert session1 != session2 + session1 = client1.transport.merge_capacity_commitments._session + session2 = client2.transport.merge_capacity_commitments._session + assert session1 != session2 + session1 = client1.transport.create_assignment._session + session2 = client2.transport.create_assignment._session + assert session1 != session2 + session1 = client1.transport.list_assignments._session + session2 = client2.transport.list_assignments._session + assert session1 != session2 + session1 = client1.transport.delete_assignment._session + session2 = client2.transport.delete_assignment._session + assert session1 != session2 + session1 = client1.transport.search_assignments._session + session2 = client2.transport.search_assignments._session + assert session1 != session2 + session1 = client1.transport.search_all_assignments._session + session2 = client2.transport.search_all_assignments._session + assert session1 != session2 + session1 = client1.transport.move_assignment._session + session2 = client2.transport.move_assignment._session + assert session1 != session2 + session1 = client1.transport.update_assignment._session + session2 = client2.transport.update_assignment._session + assert session1 != session2 + session1 = client1.transport.get_bi_reservation._session + session2 = client2.transport.get_bi_reservation._session + assert session1 != session2 + session1 = client1.transport.update_bi_reservation._session + session2 = client2.transport.update_bi_reservation._session + assert session1 != session2 def test_reservation_service_grpc_transport_channel(): @@ -7838,6 +13885,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -7855,6 +13903,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: