diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_metadata.json b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_metadata.json index 2aee1418cc48..d63d3aa71f7d 100644 --- a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_metadata.json +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/gapic_metadata.json @@ -216,6 +216,111 @@ ] } } + }, + "rest": { + "libraryClient": "BareMetalSolutionClient", + "rpcs": { + "DetachLun": { + "methods": [ + "detach_lun" + ] + }, + "GetInstance": { + "methods": [ + "get_instance" + ] + }, + "GetLun": { + "methods": [ + "get_lun" + ] + }, + "GetNetwork": { + "methods": [ + "get_network" + ] + }, + "GetNfsShare": { + "methods": [ + "get_nfs_share" + ] + }, + "GetVolume": { + "methods": [ + "get_volume" + ] + }, + "ListInstances": { + "methods": [ + "list_instances" + ] + }, + "ListLuns": { + "methods": [ + "list_luns" + ] + }, + "ListNetworkUsage": { + "methods": [ + "list_network_usage" + ] + }, + "ListNetworks": { + "methods": [ + "list_networks" + ] + }, + "ListNfsShares": { + "methods": [ + "list_nfs_shares" + ] + }, + "ListVolumes": { + "methods": [ + "list_volumes" + ] + }, + "ResetInstance": { + "methods": [ + "reset_instance" + ] + }, + "ResizeVolume": { + "methods": [ + "resize_volume" + ] + }, + "StartInstance": { + "methods": [ + "start_instance" + ] + }, + "StopInstance": { + "methods": [ + "stop_instance" + ] + }, + "UpdateInstance": { + "methods": [ + "update_instance" + ] + }, + "UpdateNetwork": { + "methods": [ + "update_network" + ] + }, + "UpdateNfsShare": { + "methods": [ + "update_nfs_share" + ] + }, + "UpdateVolume": { + "methods": [ + "update_volume" + ] + } + } } } } diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py index cb50278d064d..9c11f808221b 100644 --- a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/client.py @@ -66,6 +66,7 @@ from .transports.base import DEFAULT_CLIENT_INFO, BareMetalSolutionTransport from .transports.grpc import BareMetalSolutionGrpcTransport from .transports.grpc_asyncio import BareMetalSolutionGrpcAsyncIOTransport +from .transports.rest import BareMetalSolutionRestTransport class BareMetalSolutionClientMeta(type): @@ -81,6 +82,7 @@ class BareMetalSolutionClientMeta(type): ) # type: Dict[str, Type[BareMetalSolutionTransport]] _transport_registry["grpc"] = BareMetalSolutionGrpcTransport _transport_registry["grpc_asyncio"] = BareMetalSolutionGrpcAsyncIOTransport + _transport_registry["rest"] = BareMetalSolutionRestTransport def get_transport_class( cls, diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/__init__.py b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/__init__.py index 6009d7fbcf3b..6d53544ec0cd 100644 --- a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/__init__.py +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/__init__.py @@ -19,14 +19,18 @@ from .base import BareMetalSolutionTransport from .grpc import BareMetalSolutionGrpcTransport from .grpc_asyncio import BareMetalSolutionGrpcAsyncIOTransport +from .rest import BareMetalSolutionRestInterceptor, BareMetalSolutionRestTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[BareMetalSolutionTransport]] _transport_registry["grpc"] = BareMetalSolutionGrpcTransport _transport_registry["grpc_asyncio"] = BareMetalSolutionGrpcAsyncIOTransport +_transport_registry["rest"] = BareMetalSolutionRestTransport __all__ = ( "BareMetalSolutionTransport", "BareMetalSolutionGrpcTransport", "BareMetalSolutionGrpcAsyncIOTransport", + "BareMetalSolutionRestTransport", + "BareMetalSolutionRestInterceptor", ) diff --git a/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/rest.py b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/rest.py new file mode 100644 index 000000000000..a9905d2e103f --- /dev/null +++ b/packages/google-cloud-bare-metal-solution/google/cloud/bare_metal_solution_v2/services/bare_metal_solution/transports/rest.py @@ -0,0 +1,2825 @@ +# -*- 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, + operations_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.longrunning import operations_pb2 # type: ignore + +from google.cloud.bare_metal_solution_v2.types import nfs_share as gcb_nfs_share +from google.cloud.bare_metal_solution_v2.types import instance +from google.cloud.bare_metal_solution_v2.types import instance as gcb_instance +from google.cloud.bare_metal_solution_v2.types import lun +from google.cloud.bare_metal_solution_v2.types import network +from google.cloud.bare_metal_solution_v2.types import network as gcb_network +from google.cloud.bare_metal_solution_v2.types import nfs_share +from google.cloud.bare_metal_solution_v2.types import volume +from google.cloud.bare_metal_solution_v2.types import volume as gcb_volume + +from .base import BareMetalSolutionTransport +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class BareMetalSolutionRestInterceptor: + """Interceptor for BareMetalSolution. + + 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 BareMetalSolutionRestTransport. + + .. code-block:: python + class MyCustomBareMetalSolutionInterceptor(BareMetalSolutionRestInterceptor): + def pre_detach_lun(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_detach_lun(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_lun(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_lun(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_network(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_network(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_nfs_share(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_nfs_share(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_volume(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_volume(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_instances(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_instances(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_luns(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_luns(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_networks(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_networks(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_network_usage(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_network_usage(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_nfs_shares(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_nfs_shares(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_volumes(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_volumes(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reset_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reset_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resize_volume(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resize_volume(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_stop_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_stop_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_instance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_network(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_network(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_nfs_share(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_nfs_share(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_update_volume(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_volume(self, response): + logging.log(f"Received response: {response}") + return response + + transport = BareMetalSolutionRestTransport(interceptor=MyCustomBareMetalSolutionInterceptor()) + client = BareMetalSolutionClient(transport=transport) + + + """ + + def pre_detach_lun( + self, + request: gcb_instance.DetachLunRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcb_instance.DetachLunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for detach_lun + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_detach_lun( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for detach_lun + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_get_instance( + self, request: instance.GetInstanceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[instance.GetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_get_instance(self, response: instance.Instance) -> instance.Instance: + """Post-rpc interceptor for get_instance + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_get_lun( + self, request: lun.GetLunRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[lun.GetLunRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_lun + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_get_lun(self, response: lun.Lun) -> lun.Lun: + """Post-rpc interceptor for get_lun + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_get_network( + self, request: network.GetNetworkRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[network.GetNetworkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_network + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_get_network(self, response: network.Network) -> network.Network: + """Post-rpc interceptor for get_network + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_get_nfs_share( + self, request: nfs_share.GetNfsShareRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[nfs_share.GetNfsShareRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_nfs_share + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_get_nfs_share(self, response: nfs_share.NfsShare) -> nfs_share.NfsShare: + """Post-rpc interceptor for get_nfs_share + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_get_volume( + self, request: volume.GetVolumeRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[volume.GetVolumeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_volume + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_get_volume(self, response: volume.Volume) -> volume.Volume: + """Post-rpc interceptor for get_volume + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_list_instances( + self, + request: instance.ListInstancesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[instance.ListInstancesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_list_instances( + self, response: instance.ListInstancesResponse + ) -> instance.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_list_luns( + self, request: lun.ListLunsRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[lun.ListLunsRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_luns + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_list_luns(self, response: lun.ListLunsResponse) -> lun.ListLunsResponse: + """Post-rpc interceptor for list_luns + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_list_networks( + self, request: network.ListNetworksRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[network.ListNetworksRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_networks + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_list_networks( + self, response: network.ListNetworksResponse + ) -> network.ListNetworksResponse: + """Post-rpc interceptor for list_networks + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_list_network_usage( + self, + request: network.ListNetworkUsageRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[network.ListNetworkUsageRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_network_usage + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_list_network_usage( + self, response: network.ListNetworkUsageResponse + ) -> network.ListNetworkUsageResponse: + """Post-rpc interceptor for list_network_usage + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_list_nfs_shares( + self, + request: nfs_share.ListNfsSharesRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[nfs_share.ListNfsSharesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_nfs_shares + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_list_nfs_shares( + self, response: nfs_share.ListNfsSharesResponse + ) -> nfs_share.ListNfsSharesResponse: + """Post-rpc interceptor for list_nfs_shares + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_list_volumes( + self, request: volume.ListVolumesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[volume.ListVolumesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_volumes + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_list_volumes( + self, response: volume.ListVolumesResponse + ) -> volume.ListVolumesResponse: + """Post-rpc interceptor for list_volumes + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_reset_instance( + self, + request: instance.ResetInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[instance.ResetInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for reset_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_reset_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for reset_instance + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_resize_volume( + self, + request: gcb_volume.ResizeVolumeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcb_volume.ResizeVolumeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for resize_volume + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_resize_volume( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for resize_volume + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_start_instance( + self, + request: instance.StartInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[instance.StartInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for start_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_start_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for start_instance + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_stop_instance( + self, request: instance.StopInstanceRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[instance.StopInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for stop_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_stop_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for stop_instance + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_update_instance( + self, + request: gcb_instance.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcb_instance.UpdateInstanceRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_instance + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_update_network( + self, + request: gcb_network.UpdateNetworkRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcb_network.UpdateNetworkRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_network + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_update_network( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_network + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_update_nfs_share( + self, + request: gcb_nfs_share.UpdateNfsShareRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcb_nfs_share.UpdateNfsShareRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_nfs_share + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_update_nfs_share( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_nfs_share + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + def pre_update_volume( + self, + request: gcb_volume.UpdateVolumeRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[gcb_volume.UpdateVolumeRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for update_volume + + Override in a subclass to manipulate the request or metadata + before they are sent to the BareMetalSolution server. + """ + return request, metadata + + def post_update_volume( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_volume + + Override in a subclass to manipulate the response + after it is returned by the BareMetalSolution server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class BareMetalSolutionRestStub: + _session: AuthorizedSession + _host: str + _interceptor: BareMetalSolutionRestInterceptor + + +class BareMetalSolutionRestTransport(BareMetalSolutionTransport): + """REST backend transport for BareMetalSolution. + + Performs management operations on Bare Metal Solution servers. + + The ``baremetalsolution.googleapis.com`` service provides management + capabilities for Bare Metal Solution servers. To access the API + methods, you must assign Bare Metal Solution IAM roles containing + the desired permissions to your staff in your Google Cloud project. + You must also enable the Bare Metal Solution API. Once enabled, the + methods act upon specific servers in your Bare Metal Solution + environment. + + 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 = "baremetalsolution.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[BareMetalSolutionRestInterceptor] = 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 + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or BareMetalSolutionRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = {} + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v2", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _DetachLun(BareMetalSolutionRestStub): + def __hash__(self): + return hash("DetachLun") + + __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: gcb_instance.DetachLunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the detach lun method over HTTP. + + Args: + request (~.gcb_instance.DetachLunRequest): + The request object. Message for detach specific LUN from + an Instance. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{instance=projects/*/locations/*/instances/*}:detachLun", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_detach_lun(request, metadata) + pb_request = gcb_instance.DetachLunRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_detach_lun(resp) + return resp + + class _GetInstance(BareMetalSolutionRestStub): + def __hash__(self): + return hash("GetInstance") + + __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: instance.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instance.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.instance.GetInstanceRequest): + The request object. Message for requesting server + information. + + 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: + ~.instance.Instance: + A server. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/instances/*}", + }, + ] + request, metadata = self._interceptor.pre_get_instance(request, metadata) + pb_request = instance.GetInstanceRequest.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 = instance.Instance() + pb_resp = instance.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_instance(resp) + return resp + + class _GetLun(BareMetalSolutionRestStub): + def __hash__(self): + return hash("GetLun") + + __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: lun.GetLunRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lun.Lun: + r"""Call the get lun method over HTTP. + + Args: + request (~.lun.GetLunRequest): + The request object. Message for requesting storage lun + information. + + 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: + ~.lun.Lun: + A storage volume logical unit number + (LUN). + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/volumes/*/luns/*}", + }, + ] + request, metadata = self._interceptor.pre_get_lun(request, metadata) + pb_request = lun.GetLunRequest.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 = lun.Lun() + pb_resp = lun.Lun.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_lun(resp) + return resp + + class _GetNetwork(BareMetalSolutionRestStub): + def __hash__(self): + return hash("GetNetwork") + + __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: network.GetNetworkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> network.Network: + r"""Call the get network method over HTTP. + + Args: + request (~.network.GetNetworkRequest): + The request object. Message for requesting network + information. + + 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: + ~.network.Network: + A Network. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/networks/*}", + }, + ] + request, metadata = self._interceptor.pre_get_network(request, metadata) + pb_request = network.GetNetworkRequest.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 = network.Network() + pb_resp = network.Network.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_network(resp) + return resp + + class _GetNfsShare(BareMetalSolutionRestStub): + def __hash__(self): + return hash("GetNfsShare") + + __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: nfs_share.GetNfsShareRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> nfs_share.NfsShare: + r"""Call the get nfs share method over HTTP. + + Args: + request (~.nfs_share.GetNfsShareRequest): + The request object. Message for requesting NFS share + information. + + 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: + ~.nfs_share.NfsShare: + An NFS share. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/nfsShares/*}", + }, + ] + request, metadata = self._interceptor.pre_get_nfs_share(request, metadata) + pb_request = nfs_share.GetNfsShareRequest.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 = nfs_share.NfsShare() + pb_resp = nfs_share.NfsShare.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_nfs_share(resp) + return resp + + class _GetVolume(BareMetalSolutionRestStub): + def __hash__(self): + return hash("GetVolume") + + __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: volume.GetVolumeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> volume.Volume: + r"""Call the get volume method over HTTP. + + Args: + request (~.volume.GetVolumeRequest): + The request object. Message for requesting storage volume + information. + + 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: + ~.volume.Volume: + A storage volume. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{name=projects/*/locations/*/volumes/*}", + }, + ] + request, metadata = self._interceptor.pre_get_volume(request, metadata) + pb_request = volume.GetVolumeRequest.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 = volume.Volume() + pb_resp = volume.Volume.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_volume(resp) + return resp + + class _ListInstances(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ListInstances") + + __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: instance.ListInstancesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> instance.ListInstancesResponse: + r"""Call the list instances method over HTTP. + + Args: + request (~.instance.ListInstancesRequest): + The request object. Message for requesting the list of + servers. + + 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: + ~.instance.ListInstancesResponse: + Response message for the list of + servers. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/instances", + }, + ] + request, metadata = self._interceptor.pre_list_instances(request, metadata) + pb_request = instance.ListInstancesRequest.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 = instance.ListInstancesResponse() + pb_resp = instance.ListInstancesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_instances(resp) + return resp + + class _ListLuns(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ListLuns") + + __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: lun.ListLunsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lun.ListLunsResponse: + r"""Call the list luns method over HTTP. + + Args: + request (~.lun.ListLunsRequest): + The request object. Message for requesting a list of + storage volume luns. + + 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: + ~.lun.ListLunsResponse: + Response message containing the list + of storage volume luns. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*/volumes/*}/luns", + }, + ] + request, metadata = self._interceptor.pre_list_luns(request, metadata) + pb_request = lun.ListLunsRequest.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 = lun.ListLunsResponse() + pb_resp = lun.ListLunsResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_luns(resp) + return resp + + class _ListNetworks(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ListNetworks") + + __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: network.ListNetworksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> network.ListNetworksResponse: + r"""Call the list networks method over HTTP. + + Args: + request (~.network.ListNetworksRequest): + The request object. Message for requesting a list of + networks. + + 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: + ~.network.ListNetworksResponse: + Response message containing the list + of networks. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/networks", + }, + ] + request, metadata = self._interceptor.pre_list_networks(request, metadata) + pb_request = network.ListNetworksRequest.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 = network.ListNetworksResponse() + pb_resp = network.ListNetworksResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_networks(resp) + return resp + + class _ListNetworkUsage(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ListNetworkUsage") + + __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: network.ListNetworkUsageRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> network.ListNetworkUsageResponse: + r"""Call the list network usage method over HTTP. + + Args: + request (~.network.ListNetworkUsageRequest): + The request object. Request to get networks with IPs. + 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: + ~.network.ListNetworkUsageResponse: + Response with Networks with IPs + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{location=projects/*/locations/*}/networks:listNetworkUsage", + }, + ] + request, metadata = self._interceptor.pre_list_network_usage( + request, metadata + ) + pb_request = network.ListNetworkUsageRequest.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 = network.ListNetworkUsageResponse() + pb_resp = network.ListNetworkUsageResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_network_usage(resp) + return resp + + class _ListNfsShares(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ListNfsShares") + + __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: nfs_share.ListNfsSharesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> nfs_share.ListNfsSharesResponse: + r"""Call the list nfs shares method over HTTP. + + Args: + request (~.nfs_share.ListNfsSharesRequest): + The request object. Message for requesting a list of NFS + shares. + + 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: + ~.nfs_share.ListNfsSharesResponse: + Response message containing the list + of NFS shares. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/nfsShares", + }, + ] + request, metadata = self._interceptor.pre_list_nfs_shares(request, metadata) + pb_request = nfs_share.ListNfsSharesRequest.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 = nfs_share.ListNfsSharesResponse() + pb_resp = nfs_share.ListNfsSharesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_nfs_shares(resp) + return resp + + class _ListVolumes(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ListVolumes") + + __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: volume.ListVolumesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> volume.ListVolumesResponse: + r"""Call the list volumes method over HTTP. + + Args: + request (~.volume.ListVolumesRequest): + The request object. Message for requesting a list of + storage volumes. + + 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: + ~.volume.ListVolumesResponse: + Response message containing the list + of storage volumes. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v2/{parent=projects/*/locations/*}/volumes", + }, + ] + request, metadata = self._interceptor.pre_list_volumes(request, metadata) + pb_request = volume.ListVolumesRequest.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 = volume.ListVolumesResponse() + pb_resp = volume.ListVolumesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_volumes(resp) + return resp + + class _ResetInstance(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ResetInstance") + + __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: instance.ResetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the reset instance method over HTTP. + + Args: + request (~.instance.ResetInstanceRequest): + The request object. Message requesting to reset a server. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/instances/*}:reset", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_reset_instance(request, metadata) + pb_request = instance.ResetInstanceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_reset_instance(resp) + return resp + + class _ResizeVolume(BareMetalSolutionRestStub): + def __hash__(self): + return hash("ResizeVolume") + + __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: gcb_volume.ResizeVolumeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the resize volume method over HTTP. + + Args: + request (~.gcb_volume.ResizeVolumeRequest): + The request object. Request for emergency resize Volume. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{volume=projects/*/locations/*/volumes/*}:resize", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_resize_volume(request, metadata) + pb_request = gcb_volume.ResizeVolumeRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_resize_volume(resp) + return resp + + class _StartInstance(BareMetalSolutionRestStub): + def __hash__(self): + return hash("StartInstance") + + __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: instance.StartInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the start instance method over HTTP. + + Args: + request (~.instance.StartInstanceRequest): + The request object. Message requesting to start a server. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/instances/*}:start", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_start_instance(request, metadata) + pb_request = instance.StartInstanceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_start_instance(resp) + return resp + + class _StopInstance(BareMetalSolutionRestStub): + def __hash__(self): + return hash("StopInstance") + + __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: instance.StopInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the stop instance method over HTTP. + + Args: + request (~.instance.StopInstanceRequest): + The request object. Message requesting to stop a server. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v2/{name=projects/*/locations/*/instances/*}:stop", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_stop_instance(request, metadata) + pb_request = instance.StopInstanceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_stop_instance(resp) + return resp + + class _UpdateInstance(BareMetalSolutionRestStub): + def __hash__(self): + return hash("UpdateInstance") + + __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: gcb_instance.UpdateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update instance method over HTTP. + + Args: + request (~.gcb_instance.UpdateInstanceRequest): + The request object. Message requesting to updating a + server. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{instance.name=projects/*/locations/*/instances/*}", + "body": "instance", + }, + ] + request, metadata = self._interceptor.pre_update_instance(request, metadata) + pb_request = gcb_instance.UpdateInstanceRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_instance(resp) + return resp + + class _UpdateNetwork(BareMetalSolutionRestStub): + def __hash__(self): + return hash("UpdateNetwork") + + __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: gcb_network.UpdateNetworkRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update network method over HTTP. + + Args: + request (~.gcb_network.UpdateNetworkRequest): + The request object. Message requesting to updating a + network. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{network.name=projects/*/locations/*/networks/*}", + "body": "network", + }, + ] + request, metadata = self._interceptor.pre_update_network(request, metadata) + pb_request = gcb_network.UpdateNetworkRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_network(resp) + return resp + + class _UpdateNfsShare(BareMetalSolutionRestStub): + def __hash__(self): + return hash("UpdateNfsShare") + + __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: gcb_nfs_share.UpdateNfsShareRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update nfs share method over HTTP. + + Args: + request (~.gcb_nfs_share.UpdateNfsShareRequest): + The request object. Message requesting to updating a NFS + share. + + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{nfs_share.name=projects/*/locations/*/nfsShares/*}", + "body": "nfs_share", + }, + ] + request, metadata = self._interceptor.pre_update_nfs_share( + request, metadata + ) + pb_request = gcb_nfs_share.UpdateNfsShareRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_nfs_share(resp) + return resp + + class _UpdateVolume(BareMetalSolutionRestStub): + def __hash__(self): + return hash("UpdateVolume") + + __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: gcb_volume.UpdateVolumeRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the update volume method over HTTP. + + Args: + request (~.gcb_volume.UpdateVolumeRequest): + The request object. Message for updating a volume. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "patch", + "uri": "/v2/{volume.name=projects/*/locations/*/volumes/*}", + "body": "volume", + }, + ] + request, metadata = self._interceptor.pre_update_volume(request, metadata) + pb_request = gcb_volume.UpdateVolumeRequest.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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_update_volume(resp) + return resp + + @property + def detach_lun( + self, + ) -> Callable[[gcb_instance.DetachLunRequest], operations_pb2.Operation]: + # 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._DetachLun(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_instance( + self, + ) -> Callable[[instance.GetInstanceRequest], instance.Instance]: + # 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._GetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_lun(self) -> Callable[[lun.GetLunRequest], lun.Lun]: + # 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._GetLun(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_network(self) -> Callable[[network.GetNetworkRequest], network.Network]: + # 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._GetNetwork(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_nfs_share( + self, + ) -> Callable[[nfs_share.GetNfsShareRequest], nfs_share.NfsShare]: + # 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._GetNfsShare(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_volume(self) -> Callable[[volume.GetVolumeRequest], volume.Volume]: + # 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._GetVolume(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_instances( + self, + ) -> Callable[[instance.ListInstancesRequest], instance.ListInstancesResponse]: + # 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._ListInstances(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_luns(self) -> Callable[[lun.ListLunsRequest], lun.ListLunsResponse]: + # 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._ListLuns(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_networks( + self, + ) -> Callable[[network.ListNetworksRequest], network.ListNetworksResponse]: + # 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._ListNetworks(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_network_usage( + self, + ) -> Callable[[network.ListNetworkUsageRequest], network.ListNetworkUsageResponse]: + # 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._ListNetworkUsage(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_nfs_shares( + self, + ) -> Callable[[nfs_share.ListNfsSharesRequest], nfs_share.ListNfsSharesResponse]: + # 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._ListNfsShares(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_volumes( + self, + ) -> Callable[[volume.ListVolumesRequest], volume.ListVolumesResponse]: + # 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._ListVolumes(self._session, self._host, self._interceptor) # type: ignore + + @property + def reset_instance( + self, + ) -> Callable[[instance.ResetInstanceRequest], operations_pb2.Operation]: + # 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._ResetInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def resize_volume( + self, + ) -> Callable[[gcb_volume.ResizeVolumeRequest], operations_pb2.Operation]: + # 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._ResizeVolume(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_instance( + self, + ) -> Callable[[instance.StartInstanceRequest], operations_pb2.Operation]: + # 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._StartInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def stop_instance( + self, + ) -> Callable[[instance.StopInstanceRequest], operations_pb2.Operation]: + # 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._StopInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_instance( + self, + ) -> Callable[[gcb_instance.UpdateInstanceRequest], operations_pb2.Operation]: + # 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._UpdateInstance(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_network( + self, + ) -> Callable[[gcb_network.UpdateNetworkRequest], operations_pb2.Operation]: + # 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._UpdateNetwork(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_nfs_share( + self, + ) -> Callable[[gcb_nfs_share.UpdateNfsShareRequest], operations_pb2.Operation]: + # 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._UpdateNfsShare(self._session, self._host, self._interceptor) # type: ignore + + @property + def update_volume( + self, + ) -> Callable[[gcb_volume.UpdateVolumeRequest], operations_pb2.Operation]: + # 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._UpdateVolume(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("BareMetalSolutionRestTransport",) diff --git a/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py b/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py index 074bb037ed31..02d3e1c7dbc3 100644 --- a/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.py +++ b/packages/google-cloud-bare-metal-solution/tests/unit/gapic/bare_metal_solution_v2/test_bare_metal_solution.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 ( @@ -42,12 +44,15 @@ from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import field_mask_pb2 # type: ignore +from google.protobuf import json_format from google.protobuf import timestamp_pb2 # type: ignore import grpc from grpc.experimental import aio from proto.marshal.rules import wrappers from proto.marshal.rules.dates import DurationRule, TimestampRule import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session from google.cloud.bare_metal_solution_v2.services.bare_metal_solution import ( BareMetalSolutionAsyncClient, @@ -117,6 +122,7 @@ def test__get_default_mtls_endpoint(): [ (BareMetalSolutionClient, "grpc"), (BareMetalSolutionAsyncClient, "grpc_asyncio"), + (BareMetalSolutionClient, "rest"), ], ) def test_bare_metal_solution_client_from_service_account_info( @@ -132,7 +138,11 @@ def test_bare_metal_solution_client_from_service_account_info( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("baremetalsolution.googleapis.com:443") + assert client.transport._host == ( + "baremetalsolution.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://baremetalsolution.googleapis.com" + ) @pytest.mark.parametrize( @@ -140,6 +150,7 @@ def test_bare_metal_solution_client_from_service_account_info( [ (transports.BareMetalSolutionGrpcTransport, "grpc"), (transports.BareMetalSolutionGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.BareMetalSolutionRestTransport, "rest"), ], ) def test_bare_metal_solution_client_service_account_always_use_jwt( @@ -165,6 +176,7 @@ def test_bare_metal_solution_client_service_account_always_use_jwt( [ (BareMetalSolutionClient, "grpc"), (BareMetalSolutionAsyncClient, "grpc_asyncio"), + (BareMetalSolutionClient, "rest"), ], ) def test_bare_metal_solution_client_from_service_account_file( @@ -187,13 +199,18 @@ def test_bare_metal_solution_client_from_service_account_file( assert client.transport._credentials == creds assert isinstance(client, client_class) - assert client.transport._host == ("baremetalsolution.googleapis.com:443") + assert client.transport._host == ( + "baremetalsolution.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://baremetalsolution.googleapis.com" + ) def test_bare_metal_solution_client_get_transport_class(): transport = BareMetalSolutionClient.get_transport_class() available_transports = [ transports.BareMetalSolutionGrpcTransport, + transports.BareMetalSolutionRestTransport, ] assert transport in available_transports @@ -210,6 +227,7 @@ def test_bare_metal_solution_client_get_transport_class(): transports.BareMetalSolutionGrpcAsyncIOTransport, "grpc_asyncio", ), + (BareMetalSolutionClient, transports.BareMetalSolutionRestTransport, "rest"), ], ) @mock.patch.object( @@ -365,6 +383,18 @@ def test_bare_metal_solution_client_client_options( "grpc_asyncio", "false", ), + ( + BareMetalSolutionClient, + transports.BareMetalSolutionRestTransport, + "rest", + "true", + ), + ( + BareMetalSolutionClient, + transports.BareMetalSolutionRestTransport, + "rest", + "false", + ), ], ) @mock.patch.object( @@ -564,6 +594,7 @@ def test_bare_metal_solution_client_get_mtls_endpoint_and_cert_source(client_cla transports.BareMetalSolutionGrpcAsyncIOTransport, "grpc_asyncio", ), + (BareMetalSolutionClient, transports.BareMetalSolutionRestTransport, "rest"), ], ) def test_bare_metal_solution_client_client_options_scopes( @@ -604,6 +635,12 @@ def test_bare_metal_solution_client_client_options_scopes( "grpc_asyncio", grpc_helpers_async, ), + ( + BareMetalSolutionClient, + transports.BareMetalSolutionRestTransport, + "rest", + None, + ), ], ) def test_bare_metal_solution_client_client_options_credentials_file( @@ -6472,131 +6509,6185 @@ async def test_update_nfs_share_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.BareMetalSolutionGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + instance.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest(request_type): + client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = BareMetalSolutionClient( - 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 response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.BareMetalSolutionGrpcTransport( + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = instance.ListInstancesResponse.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_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_instances_rest_required_fields( + request_type=instance.ListInstancesRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + 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_instances._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_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - with pytest.raises(ValueError): - client = BareMetalSolutionClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = instance.ListInstancesResponse() + # 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 = instance.ListInstancesResponse.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_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) ) + & set(("parent",)) + ) - # It is an error to provide an api_key and a transport instance. - transport = transports.BareMetalSolutionGrpcTransport( + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = BareMetalSolutionClient( - client_options=options, - transport=transport, + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_list_instances" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_list_instances" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = instance.ListInstancesRequest.pb(instance.ListInstancesRequest()) + 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 = instance.ListInstancesResponse.to_json( + instance.ListInstancesResponse() ) - # 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 = BareMetalSolutionClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + request = instance.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.ListInstancesResponse() + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], ) - # It is an error to provide scopes and a transport instance. - transport = transports.BareMetalSolutionGrpcTransport( + pre.assert_called_once() + post.assert_called_once() + + +def test_list_instances_rest_bad_request( + transport: str = "rest", request_type=instance.ListInstancesRequest +): + client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = BareMetalSolutionClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.BareMetalSolutionGrpcTransport( + # 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_instances(request) + + +def test_list_instances_rest_flattened(): + client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - client = BareMetalSolutionClient(transport=transport) - assert client.transport is transport + # 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 = instance.ListInstancesResponse() -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.BareMetalSolutionGrpcTransport( + # 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 = instance.ListInstancesResponse.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_instances(**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/v2/{parent=projects/*/locations/*}/instances" % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel - transport = transports.BareMetalSolutionGrpcAsyncIOTransport( + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + instance.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - channel = transport.grpc_channel - assert channel + # 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 = ( + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + instance.Instance(), + ], + next_page_token="abc", + ), + instance.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + ], + next_page_token="ghi", + ), + instance.ListInstancesResponse( + instances=[ + instance.Instance(), + instance.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(instance.ListInstancesResponse.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 -@pytest.mark.parametrize( - "transport_class", - [ - transports.BareMetalSolutionGrpcTransport, - transports.BareMetalSolutionGrpcAsyncIOTransport, - ], -) -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() + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, instance.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( - "transport_name", + "request_type", [ - "grpc", + instance.GetInstanceRequest, + dict, ], ) -def test_transport_kind(transport_name): - transport = BareMetalSolutionClient.get_transport_class(transport_name)( +def test_get_instance_rest(request_type): + client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert transport.kind == transport_name + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = instance.Instance( + name="name_value", + id="id_value", + machine_type="machine_type_value", + state=instance.Instance.State.PROVISIONING, + hyperthreading_enabled=True, + interactive_serial_console_enabled=True, + os_image="os_image_value", + pod="pod_value", + network_template="network_template_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = instance.Instance.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_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, instance.Instance) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.machine_type == "machine_type_value" + assert response.state == instance.Instance.State.PROVISIONING + assert response.hyperthreading_enabled is True + assert response.interactive_serial_console_enabled is True + assert response.os_image == "os_image_value" + assert response.pod == "pod_value" + assert response.network_template == "network_template_value" + + +def test_get_instance_rest_required_fields(request_type=instance.GetInstanceRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_instance._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_instance._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" -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. client = BareMetalSolutionClient( credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert isinstance( - client.transport, - transports.BareMetalSolutionGrpcTransport, - ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = instance.Instance() + # 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 -def test_bare_metal_solution_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.BareMetalSolutionTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", - ) + response_value = Response() + response_value.status_code = 200 + pb_return_value = instance.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) -def test_bare_metal_solution_base_transport(): + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_get_instance" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_get_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = instance.GetInstanceRequest.pb(instance.GetInstanceRequest()) + 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 = instance.Instance.to_json(instance.Instance()) + + request = instance.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = instance.Instance() + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_instance_rest_bad_request( + transport: str = "rest", request_type=instance.GetInstanceRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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_instance(request) + + +def test_get_instance_rest_flattened(): + client = BareMetalSolutionClient( + 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 = instance.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/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 = instance.Instance.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_instance(**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/v2/{name=projects/*/locations/*/instances/*}" % client.transport._host, + args[1], + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_instance( + instance.GetInstanceRequest(), + name="name_value", + ) + + +def test_get_instance_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_instance.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "id": "id_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "machine_type": "machine_type_value", + "state": 1, + "hyperthreading_enabled": True, + "labels": {}, + "luns": [ + { + "name": "name_value", + "id": "id_value", + "state": 1, + "size_gb": 739, + "multiprotocol_type": 1, + "storage_volume": "storage_volume_value", + "shareable": True, + "boot_lun": True, + "storage_type": 1, + "wwid": "wwid_value", + } + ], + "networks": [ + { + "name": "name_value", + "id": "id_value", + "type_": 1, + "ip_address": "ip_address_value", + "mac_address": ["mac_address_value1", "mac_address_value2"], + "state": 1, + "vlan_id": "vlan_id_value", + "cidr": "cidr_value", + "vrf": { + "name": "name_value", + "state": 1, + "qos_policy": {"bandwidth_gbps": 0.1472}, + "vlan_attachments": [ + { + "peer_vlan_id": 1256, + "peer_ip": "peer_ip_value", + "router_ip": "router_ip_value", + } + ], + }, + "labels": {}, + "services_cidr": "services_cidr_value", + "reservations": [ + { + "start_address": "start_address_value", + "end_address": "end_address_value", + "note": "note_value", + } + ], + } + ], + "interactive_serial_console_enabled": True, + "os_image": "os_image_value", + "pod": "pod_value", + "network_template": "network_template_value", + "logical_interfaces": [ + { + "logical_network_interfaces": [ + { + "network": "network_value", + "ip_address": "ip_address_value", + "default_gateway": True, + "network_type": 1, + "id": "id_value", + } + ], + "name": "name_value", + "interface_index": 1576, + } + ], + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_instance_rest_required_fields( + request_type=gcb_instance.UpdateInstanceRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_instance_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("instance",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_update_instance" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_update_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcb_instance.UpdateInstanceRequest.pb( + gcb_instance.UpdateInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gcb_instance.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_instance_rest_bad_request( + transport: str = "rest", request_type=gcb_instance.UpdateInstanceRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "name": "projects/sample1/locations/sample2/instances/sample3", + "id": "id_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "machine_type": "machine_type_value", + "state": 1, + "hyperthreading_enabled": True, + "labels": {}, + "luns": [ + { + "name": "name_value", + "id": "id_value", + "state": 1, + "size_gb": 739, + "multiprotocol_type": 1, + "storage_volume": "storage_volume_value", + "shareable": True, + "boot_lun": True, + "storage_type": 1, + "wwid": "wwid_value", + } + ], + "networks": [ + { + "name": "name_value", + "id": "id_value", + "type_": 1, + "ip_address": "ip_address_value", + "mac_address": ["mac_address_value1", "mac_address_value2"], + "state": 1, + "vlan_id": "vlan_id_value", + "cidr": "cidr_value", + "vrf": { + "name": "name_value", + "state": 1, + "qos_policy": {"bandwidth_gbps": 0.1472}, + "vlan_attachments": [ + { + "peer_vlan_id": 1256, + "peer_ip": "peer_ip_value", + "router_ip": "router_ip_value", + } + ], + }, + "labels": {}, + "services_cidr": "services_cidr_value", + "reservations": [ + { + "start_address": "start_address_value", + "end_address": "end_address_value", + "note": "note_value", + } + ], + } + ], + "interactive_serial_console_enabled": True, + "os_image": "os_image_value", + "pod": "pod_value", + "network_template": "network_template_value", + "logical_interfaces": [ + { + "logical_network_interfaces": [ + { + "network": "network_value", + "ip_address": "ip_address_value", + "default_gateway": True, + "network_type": 1, + "id": "id_value", + } + ], + "name": "name_value", + "interface_index": 1576, + } + ], + } + 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_instance(request) + + +def test_update_instance_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + instance=gcb_instance.Instance(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_instance(**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/v2/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_update_instance_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_instance( + gcb_instance.UpdateInstanceRequest(), + instance=gcb_instance.Instance(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_instance_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.ResetInstanceRequest, + dict, + ], +) +def test_reset_instance_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.reset_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_reset_instance_rest_required_fields( + request_type=instance.ResetInstanceRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + 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() + ).reset_instance._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() + ).reset_instance._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.reset_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_reset_instance_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.reset_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reset_instance_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_reset_instance" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_reset_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = instance.ResetInstanceRequest.pb(instance.ResetInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = instance.ResetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.reset_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_reset_instance_rest_bad_request( + transport: str = "rest", request_type=instance.ResetInstanceRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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.reset_instance(request) + + +def test_reset_instance_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.reset_instance(**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/v2/{name=projects/*/locations/*/instances/*}:reset" + % client.transport._host, + args[1], + ) + + +def test_reset_instance_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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.reset_instance( + instance.ResetInstanceRequest(), + name="name_value", + ) + + +def test_reset_instance_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.StartInstanceRequest, + dict, + ], +) +def test_start_instance_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.start_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_start_instance_rest_required_fields( + request_type=instance.StartInstanceRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + 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() + ).start_instance._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() + ).start_instance._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.start_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_start_instance_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.start_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_instance_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_start_instance" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_start_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = instance.StartInstanceRequest.pb(instance.StartInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = instance.StartInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.start_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_start_instance_rest_bad_request( + transport: str = "rest", request_type=instance.StartInstanceRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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.start_instance(request) + + +def test_start_instance_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.start_instance(**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/v2/{name=projects/*/locations/*/instances/*}:start" + % client.transport._host, + args[1], + ) + + +def test_start_instance_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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.start_instance( + instance.StartInstanceRequest(), + name="name_value", + ) + + +def test_start_instance_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + instance.StopInstanceRequest, + dict, + ], +) +def test_stop_instance_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.stop_instance(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_stop_instance_rest_required_fields(request_type=instance.StopInstanceRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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() + ).stop_instance._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() + ).stop_instance._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.stop_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_stop_instance_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.stop_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_stop_instance_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_stop_instance" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_stop_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = instance.StopInstanceRequest.pb(instance.StopInstanceRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = instance.StopInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.stop_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_stop_instance_rest_bad_request( + transport: str = "rest", request_type=instance.StopInstanceRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/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.stop_instance(request) + + +def test_stop_instance_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.stop_instance(**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/v2/{name=projects/*/locations/*/instances/*}:stop" + % client.transport._host, + args[1], + ) + + +def test_stop_instance_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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.stop_instance( + instance.StopInstanceRequest(), + name="name_value", + ) + + +def test_stop_instance_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_instance.DetachLunRequest, + dict, + ], +) +def test_detach_lun_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.detach_lun(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_detach_lun_rest_required_fields(request_type=gcb_instance.DetachLunRequest): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request_init["instance"] = "" + request_init["lun"] = "" + 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() + ).detach_lun._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + jsonified_request["lun"] = "lun_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).detach_lun._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "lun" in jsonified_request + assert jsonified_request["lun"] == "lun_value" + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.detach_lun(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_detach_lun_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.detach_lun._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instance", + "lun", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_detach_lun_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_detach_lun" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_detach_lun" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcb_instance.DetachLunRequest.pb(gcb_instance.DetachLunRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gcb_instance.DetachLunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.detach_lun( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_detach_lun_rest_bad_request( + transport: str = "rest", request_type=gcb_instance.DetachLunRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/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.detach_lun(request) + + +def test_detach_lun_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + instance="instance_value", + lun="lun_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 = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.detach_lun(**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/v2/{instance=projects/*/locations/*/instances/*}:detachLun" + % client.transport._host, + args[1], + ) + + +def test_detach_lun_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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.detach_lun( + gcb_instance.DetachLunRequest(), + instance="instance_value", + lun="lun_value", + ) + + +def test_detach_lun_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + volume.ListVolumesRequest, + dict, + ], +) +def test_list_volumes_rest(request_type): + client = BareMetalSolutionClient( + 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 = volume.ListVolumesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = volume.ListVolumesResponse.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_volumes(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListVolumesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_volumes_rest_required_fields(request_type=volume.ListVolumesRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_volumes._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_volumes._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = volume.ListVolumesResponse() + # 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 = volume.ListVolumesResponse.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_volumes(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_volumes_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_volumes._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_volumes_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_list_volumes" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_list_volumes" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = volume.ListVolumesRequest.pb(volume.ListVolumesRequest()) + 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 = volume.ListVolumesResponse.to_json( + volume.ListVolumesResponse() + ) + + request = volume.ListVolumesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = volume.ListVolumesResponse() + + client.list_volumes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_volumes_rest_bad_request( + transport: str = "rest", request_type=volume.ListVolumesRequest +): + client = BareMetalSolutionClient( + 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_volumes(request) + + +def test_list_volumes_rest_flattened(): + client = BareMetalSolutionClient( + 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 = volume.ListVolumesResponse() + + # 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 = volume.ListVolumesResponse.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_volumes(**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/v2/{parent=projects/*/locations/*}/volumes" % client.transport._host, + args[1], + ) + + +def test_list_volumes_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_volumes( + volume.ListVolumesRequest(), + parent="parent_value", + ) + + +def test_list_volumes_rest_pager(transport: str = "rest"): + client = BareMetalSolutionClient( + 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 = ( + volume.ListVolumesResponse( + volumes=[ + volume.Volume(), + volume.Volume(), + volume.Volume(), + ], + next_page_token="abc", + ), + volume.ListVolumesResponse( + volumes=[], + next_page_token="def", + ), + volume.ListVolumesResponse( + volumes=[ + volume.Volume(), + ], + next_page_token="ghi", + ), + volume.ListVolumesResponse( + volumes=[ + volume.Volume(), + volume.Volume(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(volume.ListVolumesResponse.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_volumes(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, volume.Volume) for i in results) + + pages = list(client.list_volumes(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", + [ + volume.GetVolumeRequest, + dict, + ], +) +def test_get_volume_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/volumes/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 = volume.Volume( + name="name_value", + id="id_value", + storage_type=volume.Volume.StorageType.SSD, + state=volume.Volume.State.CREATING, + requested_size_gib=1917, + current_size_gib=1710, + emergency_size_gib=1898, + auto_grown_size_gib=2032, + remaining_space_gib=1974, + snapshot_auto_delete_behavior=volume.Volume.SnapshotAutoDeleteBehavior.DISABLED, + snapshot_enabled=True, + pod="pod_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = volume.Volume.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_volume(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, volume.Volume) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.storage_type == volume.Volume.StorageType.SSD + assert response.state == volume.Volume.State.CREATING + assert response.requested_size_gib == 1917 + assert response.current_size_gib == 1710 + assert response.emergency_size_gib == 1898 + assert response.auto_grown_size_gib == 2032 + assert response.remaining_space_gib == 1974 + assert ( + response.snapshot_auto_delete_behavior + == volume.Volume.SnapshotAutoDeleteBehavior.DISABLED + ) + assert response.snapshot_enabled is True + assert response.pod == "pod_value" + + +def test_get_volume_rest_required_fields(request_type=volume.GetVolumeRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_volume._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_volume._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = volume.Volume() + # 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 = volume.Volume.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_volume(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_volume_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_volume._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_volume_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_get_volume" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_get_volume" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = volume.GetVolumeRequest.pb(volume.GetVolumeRequest()) + 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 = volume.Volume.to_json(volume.Volume()) + + request = volume.GetVolumeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = volume.Volume() + + client.get_volume( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_volume_rest_bad_request( + transport: str = "rest", request_type=volume.GetVolumeRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/volumes/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_volume(request) + + +def test_get_volume_rest_flattened(): + client = BareMetalSolutionClient( + 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 = volume.Volume() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/volumes/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 = volume.Volume.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_volume(**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/v2/{name=projects/*/locations/*/volumes/*}" % client.transport._host, + args[1], + ) + + +def test_get_volume_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_volume( + volume.GetVolumeRequest(), + name="name_value", + ) + + +def test_get_volume_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_volume.UpdateVolumeRequest, + dict, + ], +) +def test_update_volume_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "volume": {"name": "projects/sample1/locations/sample2/volumes/sample3"} + } + request_init["volume"] = { + "name": "projects/sample1/locations/sample2/volumes/sample3", + "id": "id_value", + "storage_type": 1, + "state": 1, + "requested_size_gib": 1917, + "current_size_gib": 1710, + "emergency_size_gib": 1898, + "auto_grown_size_gib": 2032, + "remaining_space_gib": 1974, + "snapshot_reservation_detail": { + "reserved_space_gib": 1884, + "reserved_space_used_percent": 2859, + "reserved_space_remaining_gib": 2933, + "reserved_space_percent": 2331, + }, + "snapshot_auto_delete_behavior": 1, + "labels": {}, + "snapshot_enabled": True, + "pod": "pod_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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_volume(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_volume_rest_required_fields( + request_type=gcb_volume.UpdateVolumeRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_volume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_volume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_volume(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_volume_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_volume._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("volume",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_volume_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_update_volume" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_update_volume" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcb_volume.UpdateVolumeRequest.pb(gcb_volume.UpdateVolumeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gcb_volume.UpdateVolumeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_volume( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_volume_rest_bad_request( + transport: str = "rest", request_type=gcb_volume.UpdateVolumeRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "volume": {"name": "projects/sample1/locations/sample2/volumes/sample3"} + } + request_init["volume"] = { + "name": "projects/sample1/locations/sample2/volumes/sample3", + "id": "id_value", + "storage_type": 1, + "state": 1, + "requested_size_gib": 1917, + "current_size_gib": 1710, + "emergency_size_gib": 1898, + "auto_grown_size_gib": 2032, + "remaining_space_gib": 1974, + "snapshot_reservation_detail": { + "reserved_space_gib": 1884, + "reserved_space_used_percent": 2859, + "reserved_space_remaining_gib": 2933, + "reserved_space_percent": 2331, + }, + "snapshot_auto_delete_behavior": 1, + "labels": {}, + "snapshot_enabled": True, + "pod": "pod_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_volume(request) + + +def test_update_volume_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "volume": {"name": "projects/sample1/locations/sample2/volumes/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + volume=gcb_volume.Volume(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_volume(**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/v2/{volume.name=projects/*/locations/*/volumes/*}" + % client.transport._host, + args[1], + ) + + +def test_update_volume_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_volume( + gcb_volume.UpdateVolumeRequest(), + volume=gcb_volume.Volume(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_volume_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_volume.ResizeVolumeRequest, + dict, + ], +) +def test_resize_volume_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"volume": "projects/sample1/locations/sample2/volumes/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.resize_volume(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_resize_volume_rest_required_fields( + request_type=gcb_volume.ResizeVolumeRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request_init["volume"] = "" + 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() + ).resize_volume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["volume"] = "volume_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resize_volume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "volume" in jsonified_request + assert jsonified_request["volume"] == "volume_value" + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # 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 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.resize_volume(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_resize_volume_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resize_volume._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("volume",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resize_volume_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_resize_volume" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_resize_volume" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcb_volume.ResizeVolumeRequest.pb(gcb_volume.ResizeVolumeRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gcb_volume.ResizeVolumeRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.resize_volume( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_resize_volume_rest_bad_request( + transport: str = "rest", request_type=gcb_volume.ResizeVolumeRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"volume": "projects/sample1/locations/sample2/volumes/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.resize_volume(request) + + +def test_resize_volume_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "volume": "projects/sample1/locations/sample2/volumes/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + volume="volume_value", + size_gib=844, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.resize_volume(**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/v2/{volume=projects/*/locations/*/volumes/*}:resize" + % client.transport._host, + args[1], + ) + + +def test_resize_volume_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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.resize_volume( + gcb_volume.ResizeVolumeRequest(), + volume="volume_value", + size_gib=844, + ) + + +def test_resize_volume_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + network.ListNetworksRequest, + dict, + ], +) +def test_list_networks_rest(request_type): + client = BareMetalSolutionClient( + 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 = network.ListNetworksResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = network.ListNetworksResponse.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_networks(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNetworksPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_networks_rest_required_fields(request_type=network.ListNetworksRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_networks._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_networks._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = network.ListNetworksResponse() + # 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 = network.ListNetworksResponse.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_networks(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_networks_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_networks._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_networks_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_list_networks" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_list_networks" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = network.ListNetworksRequest.pb(network.ListNetworksRequest()) + 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 = network.ListNetworksResponse.to_json( + network.ListNetworksResponse() + ) + + request = network.ListNetworksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = network.ListNetworksResponse() + + client.list_networks( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_networks_rest_bad_request( + transport: str = "rest", request_type=network.ListNetworksRequest +): + client = BareMetalSolutionClient( + 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_networks(request) + + +def test_list_networks_rest_flattened(): + client = BareMetalSolutionClient( + 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 = network.ListNetworksResponse() + + # 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 = network.ListNetworksResponse.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_networks(**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/v2/{parent=projects/*/locations/*}/networks" % client.transport._host, + args[1], + ) + + +def test_list_networks_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_networks( + network.ListNetworksRequest(), + parent="parent_value", + ) + + +def test_list_networks_rest_pager(transport: str = "rest"): + client = BareMetalSolutionClient( + 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 = ( + network.ListNetworksResponse( + networks=[ + network.Network(), + network.Network(), + network.Network(), + ], + next_page_token="abc", + ), + network.ListNetworksResponse( + networks=[], + next_page_token="def", + ), + network.ListNetworksResponse( + networks=[ + network.Network(), + ], + next_page_token="ghi", + ), + network.ListNetworksResponse( + networks=[ + network.Network(), + network.Network(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(network.ListNetworksResponse.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_networks(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, network.Network) for i in results) + + pages = list(client.list_networks(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", + [ + network.ListNetworkUsageRequest, + dict, + ], +) +def test_list_network_usage_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"location": "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 = network.ListNetworkUsageResponse() + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = network.ListNetworkUsageResponse.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_network_usage(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, network.ListNetworkUsageResponse) + + +def test_list_network_usage_rest_required_fields( + request_type=network.ListNetworkUsageRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request_init["location"] = "" + 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_network_usage._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["location"] = "location_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_network_usage._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "location" in jsonified_request + assert jsonified_request["location"] == "location_value" + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = network.ListNetworkUsageResponse() + # 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 = network.ListNetworkUsageResponse.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_network_usage(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_network_usage_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_network_usage._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("location",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_network_usage_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_list_network_usage" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_list_network_usage" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = network.ListNetworkUsageRequest.pb( + network.ListNetworkUsageRequest() + ) + 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 = network.ListNetworkUsageResponse.to_json( + network.ListNetworkUsageResponse() + ) + + request = network.ListNetworkUsageRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = network.ListNetworkUsageResponse() + + client.list_network_usage( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_network_usage_rest_bad_request( + transport: str = "rest", request_type=network.ListNetworkUsageRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"location": "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_network_usage(request) + + +def test_list_network_usage_rest_flattened(): + client = BareMetalSolutionClient( + 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 = network.ListNetworkUsageResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"location": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + location="location_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 = network.ListNetworkUsageResponse.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_network_usage(**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/v2/{location=projects/*/locations/*}/networks:listNetworkUsage" + % client.transport._host, + args[1], + ) + + +def test_list_network_usage_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_network_usage( + network.ListNetworkUsageRequest(), + location="location_value", + ) + + +def test_list_network_usage_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + network.GetNetworkRequest, + dict, + ], +) +def test_get_network_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/networks/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 = network.Network( + name="name_value", + id="id_value", + type_=network.Network.Type.CLIENT, + ip_address="ip_address_value", + mac_address=["mac_address_value"], + state=network.Network.State.PROVISIONING, + vlan_id="vlan_id_value", + cidr="cidr_value", + services_cidr="services_cidr_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = network.Network.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_network(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, network.Network) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.type_ == network.Network.Type.CLIENT + assert response.ip_address == "ip_address_value" + assert response.mac_address == ["mac_address_value"] + assert response.state == network.Network.State.PROVISIONING + assert response.vlan_id == "vlan_id_value" + assert response.cidr == "cidr_value" + assert response.services_cidr == "services_cidr_value" + + +def test_get_network_rest_required_fields(request_type=network.GetNetworkRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_network._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_network._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = network.Network() + # 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 = network.Network.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_network(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_network_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_network._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_network_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_get_network" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_get_network" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = network.GetNetworkRequest.pb(network.GetNetworkRequest()) + 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 = network.Network.to_json(network.Network()) + + request = network.GetNetworkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = network.Network() + + client.get_network( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_network_rest_bad_request( + transport: str = "rest", request_type=network.GetNetworkRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/networks/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_network(request) + + +def test_get_network_rest_flattened(): + client = BareMetalSolutionClient( + 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 = network.Network() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/networks/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 = network.Network.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_network(**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/v2/{name=projects/*/locations/*/networks/*}" % client.transport._host, + args[1], + ) + + +def test_get_network_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_network( + network.GetNetworkRequest(), + name="name_value", + ) + + +def test_get_network_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + gcb_network.UpdateNetworkRequest, + dict, + ], +) +def test_update_network_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "network": {"name": "projects/sample1/locations/sample2/networks/sample3"} + } + request_init["network"] = { + "name": "projects/sample1/locations/sample2/networks/sample3", + "id": "id_value", + "type_": 1, + "ip_address": "ip_address_value", + "mac_address": ["mac_address_value1", "mac_address_value2"], + "state": 1, + "vlan_id": "vlan_id_value", + "cidr": "cidr_value", + "vrf": { + "name": "name_value", + "state": 1, + "qos_policy": {"bandwidth_gbps": 0.1472}, + "vlan_attachments": [ + { + "peer_vlan_id": 1256, + "peer_ip": "peer_ip_value", + "router_ip": "router_ip_value", + } + ], + }, + "labels": {}, + "services_cidr": "services_cidr_value", + "reservations": [ + { + "start_address": "start_address_value", + "end_address": "end_address_value", + "note": "note_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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_network(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_network_rest_required_fields( + request_type=gcb_network.UpdateNetworkRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_network._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_network._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_network(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_network_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_network._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("network",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_network_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_update_network" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_update_network" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcb_network.UpdateNetworkRequest.pb( + gcb_network.UpdateNetworkRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gcb_network.UpdateNetworkRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_network( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_network_rest_bad_request( + transport: str = "rest", request_type=gcb_network.UpdateNetworkRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "network": {"name": "projects/sample1/locations/sample2/networks/sample3"} + } + request_init["network"] = { + "name": "projects/sample1/locations/sample2/networks/sample3", + "id": "id_value", + "type_": 1, + "ip_address": "ip_address_value", + "mac_address": ["mac_address_value1", "mac_address_value2"], + "state": 1, + "vlan_id": "vlan_id_value", + "cidr": "cidr_value", + "vrf": { + "name": "name_value", + "state": 1, + "qos_policy": {"bandwidth_gbps": 0.1472}, + "vlan_attachments": [ + { + "peer_vlan_id": 1256, + "peer_ip": "peer_ip_value", + "router_ip": "router_ip_value", + } + ], + }, + "labels": {}, + "services_cidr": "services_cidr_value", + "reservations": [ + { + "start_address": "start_address_value", + "end_address": "end_address_value", + "note": "note_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_network(request) + + +def test_update_network_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "network": {"name": "projects/sample1/locations/sample2/networks/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + network=gcb_network.Network(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_network(**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/v2/{network.name=projects/*/locations/*/networks/*}" + % client.transport._host, + args[1], + ) + + +def test_update_network_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_network( + gcb_network.UpdateNetworkRequest(), + network=gcb_network.Network(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_network_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + lun.GetLunRequest, + dict, + ], +) +def test_get_lun_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/volumes/sample3/luns/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 = lun.Lun( + name="name_value", + id="id_value", + state=lun.Lun.State.CREATING, + size_gb=739, + multiprotocol_type=lun.Lun.MultiprotocolType.LINUX, + storage_volume="storage_volume_value", + shareable=True, + boot_lun=True, + storage_type=lun.Lun.StorageType.SSD, + wwid="wwid_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = lun.Lun.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_lun(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, lun.Lun) + assert response.name == "name_value" + assert response.id == "id_value" + assert response.state == lun.Lun.State.CREATING + assert response.size_gb == 739 + assert response.multiprotocol_type == lun.Lun.MultiprotocolType.LINUX + assert response.storage_volume == "storage_volume_value" + assert response.shareable is True + assert response.boot_lun is True + assert response.storage_type == lun.Lun.StorageType.SSD + assert response.wwid == "wwid_value" + + +def test_get_lun_rest_required_fields(request_type=lun.GetLunRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_lun._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_lun._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lun.Lun() + # 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 = lun.Lun.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_lun(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_lun_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_lun._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_lun_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_get_lun" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_get_lun" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lun.GetLunRequest.pb(lun.GetLunRequest()) + 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 = lun.Lun.to_json(lun.Lun()) + + request = lun.GetLunRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lun.Lun() + + client.get_lun( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_lun_rest_bad_request( + transport: str = "rest", request_type=lun.GetLunRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/volumes/sample3/luns/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.get_lun(request) + + +def test_get_lun_rest_flattened(): + client = BareMetalSolutionClient( + 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 = lun.Lun() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/volumes/sample3/luns/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 + pb_return_value = lun.Lun.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_lun(**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/v2/{name=projects/*/locations/*/volumes/*/luns/*}" + % client.transport._host, + args[1], + ) + + +def test_get_lun_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_lun( + lun.GetLunRequest(), + name="name_value", + ) + + +def test_get_lun_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + lun.ListLunsRequest, + dict, + ], +) +def test_list_luns_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/volumes/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 = lun.ListLunsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = lun.ListLunsResponse.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_luns(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListLunsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_luns_rest_required_fields(request_type=lun.ListLunsRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_luns._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_luns._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = lun.ListLunsResponse() + # 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 = lun.ListLunsResponse.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_luns(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_luns_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_luns._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_luns_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_list_luns" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_list_luns" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = lun.ListLunsRequest.pb(lun.ListLunsRequest()) + 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 = lun.ListLunsResponse.to_json(lun.ListLunsResponse()) + + request = lun.ListLunsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = lun.ListLunsResponse() + + client.list_luns( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_luns_rest_bad_request( + transport: str = "rest", request_type=lun.ListLunsRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/volumes/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_luns(request) + + +def test_list_luns_rest_flattened(): + client = BareMetalSolutionClient( + 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 = lun.ListLunsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/volumes/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 = lun.ListLunsResponse.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_luns(**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/v2/{parent=projects/*/locations/*/volumes/*}/luns" + % client.transport._host, + args[1], + ) + + +def test_list_luns_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_luns( + lun.ListLunsRequest(), + parent="parent_value", + ) + + +def test_list_luns_rest_pager(transport: str = "rest"): + client = BareMetalSolutionClient( + 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 = ( + lun.ListLunsResponse( + luns=[ + lun.Lun(), + lun.Lun(), + lun.Lun(), + ], + next_page_token="abc", + ), + lun.ListLunsResponse( + luns=[], + next_page_token="def", + ), + lun.ListLunsResponse( + luns=[ + lun.Lun(), + ], + next_page_token="ghi", + ), + lun.ListLunsResponse( + luns=[ + lun.Lun(), + lun.Lun(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(lun.ListLunsResponse.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/volumes/sample3" + } + + pager = client.list_luns(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, lun.Lun) for i in results) + + pages = list(client.list_luns(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", + [ + nfs_share.GetNfsShareRequest, + dict, + ], +) +def test_get_nfs_share_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/nfsShares/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 = nfs_share.NfsShare( + name="name_value", + nfs_share_id="nfs_share_id_value", + state=nfs_share.NfsShare.State.PROVISIONED, + volume="volume_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = nfs_share.NfsShare.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_nfs_share(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, nfs_share.NfsShare) + assert response.name == "name_value" + assert response.nfs_share_id == "nfs_share_id_value" + assert response.state == nfs_share.NfsShare.State.PROVISIONED + assert response.volume == "volume_value" + + +def test_get_nfs_share_rest_required_fields(request_type=nfs_share.GetNfsShareRequest): + transport_class = transports.BareMetalSolutionRestTransport + + 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_nfs_share._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_nfs_share._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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = nfs_share.NfsShare() + # 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 = nfs_share.NfsShare.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_nfs_share(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_nfs_share_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_nfs_share._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_nfs_share_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_get_nfs_share" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_get_nfs_share" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = nfs_share.GetNfsShareRequest.pb(nfs_share.GetNfsShareRequest()) + 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 = nfs_share.NfsShare.to_json(nfs_share.NfsShare()) + + request = nfs_share.GetNfsShareRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = nfs_share.NfsShare() + + client.get_nfs_share( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_nfs_share_rest_bad_request( + transport: str = "rest", request_type=nfs_share.GetNfsShareRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/nfsShares/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_nfs_share(request) + + +def test_get_nfs_share_rest_flattened(): + client = BareMetalSolutionClient( + 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 = nfs_share.NfsShare() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/nfsShares/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 = nfs_share.NfsShare.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_nfs_share(**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/v2/{name=projects/*/locations/*/nfsShares/*}" % client.transport._host, + args[1], + ) + + +def test_get_nfs_share_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_nfs_share( + nfs_share.GetNfsShareRequest(), + name="name_value", + ) + + +def test_get_nfs_share_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + nfs_share.ListNfsSharesRequest, + dict, + ], +) +def test_list_nfs_shares_rest(request_type): + client = BareMetalSolutionClient( + 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 = nfs_share.ListNfsSharesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = nfs_share.ListNfsSharesResponse.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_nfs_shares(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNfsSharesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_nfs_shares_rest_required_fields( + request_type=nfs_share.ListNfsSharesRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + 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_nfs_shares._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_nfs_shares._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = nfs_share.ListNfsSharesResponse() + # 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 = nfs_share.ListNfsSharesResponse.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_nfs_shares(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_nfs_shares_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_nfs_shares._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_nfs_shares_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(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.BareMetalSolutionRestInterceptor, "post_list_nfs_shares" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_list_nfs_shares" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = nfs_share.ListNfsSharesRequest.pb(nfs_share.ListNfsSharesRequest()) + 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 = nfs_share.ListNfsSharesResponse.to_json( + nfs_share.ListNfsSharesResponse() + ) + + request = nfs_share.ListNfsSharesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = nfs_share.ListNfsSharesResponse() + + client.list_nfs_shares( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_nfs_shares_rest_bad_request( + transport: str = "rest", request_type=nfs_share.ListNfsSharesRequest +): + client = BareMetalSolutionClient( + 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_nfs_shares(request) + + +def test_list_nfs_shares_rest_flattened(): + client = BareMetalSolutionClient( + 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 = nfs_share.ListNfsSharesResponse() + + # 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 = nfs_share.ListNfsSharesResponse.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_nfs_shares(**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/v2/{parent=projects/*/locations/*}/nfsShares" % client.transport._host, + args[1], + ) + + +def test_list_nfs_shares_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_nfs_shares( + nfs_share.ListNfsSharesRequest(), + parent="parent_value", + ) + + +def test_list_nfs_shares_rest_pager(transport: str = "rest"): + client = BareMetalSolutionClient( + 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 = ( + nfs_share.ListNfsSharesResponse( + nfs_shares=[ + nfs_share.NfsShare(), + nfs_share.NfsShare(), + nfs_share.NfsShare(), + ], + next_page_token="abc", + ), + nfs_share.ListNfsSharesResponse( + nfs_shares=[], + next_page_token="def", + ), + nfs_share.ListNfsSharesResponse( + nfs_shares=[ + nfs_share.NfsShare(), + ], + next_page_token="ghi", + ), + nfs_share.ListNfsSharesResponse( + nfs_shares=[ + nfs_share.NfsShare(), + nfs_share.NfsShare(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(nfs_share.ListNfsSharesResponse.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_nfs_shares(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, nfs_share.NfsShare) for i in results) + + pages = list(client.list_nfs_shares(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", + [ + gcb_nfs_share.UpdateNfsShareRequest, + dict, + ], +) +def test_update_nfs_share_rest(request_type): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = { + "nfs_share": {"name": "projects/sample1/locations/sample2/nfsShares/sample3"} + } + request_init["nfs_share"] = { + "name": "projects/sample1/locations/sample2/nfsShares/sample3", + "nfs_share_id": "nfs_share_id_value", + "state": 1, + "volume": "volume_value", + "allowed_clients": [ + { + "network": "network_value", + "share_ip": "share_ip_value", + "allowed_clients_cidr": "allowed_clients_cidr_value", + "mount_permissions": 1, + "allow_dev": True, + "allow_suid": True, + "no_root_squash": True, + } + ], + "labels": {}, + } + 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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.update_nfs_share(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_update_nfs_share_rest_required_fields( + request_type=gcb_nfs_share.UpdateNfsShareRequest, +): + transport_class = transports.BareMetalSolutionRestTransport + + request_init = {} + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_nfs_share._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_nfs_share._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("update_mask",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_nfs_share(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_nfs_share_rest_unset_required_fields(): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_nfs_share._get_unset_required_fields({}) + assert set(unset_fields) == (set(("updateMask",)) & set(("nfsShare",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_nfs_share_rest_interceptors(null_interceptor): + transport = transports.BareMetalSolutionRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.BareMetalSolutionRestInterceptor(), + ) + client = BareMetalSolutionClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "post_update_nfs_share" + ) as post, mock.patch.object( + transports.BareMetalSolutionRestInterceptor, "pre_update_nfs_share" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = gcb_nfs_share.UpdateNfsShareRequest.pb( + gcb_nfs_share.UpdateNfsShareRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) + + request = gcb_nfs_share.UpdateNfsShareRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.update_nfs_share( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_update_nfs_share_rest_bad_request( + transport: str = "rest", request_type=gcb_nfs_share.UpdateNfsShareRequest +): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "nfs_share": {"name": "projects/sample1/locations/sample2/nfsShares/sample3"} + } + request_init["nfs_share"] = { + "name": "projects/sample1/locations/sample2/nfsShares/sample3", + "nfs_share_id": "nfs_share_id_value", + "state": 1, + "volume": "volume_value", + "allowed_clients": [ + { + "network": "network_value", + "share_ip": "share_ip_value", + "allowed_clients_cidr": "allowed_clients_cidr_value", + "mount_permissions": 1, + "allow_dev": True, + "allow_suid": True, + "no_root_squash": True, + } + ], + "labels": {}, + } + 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_nfs_share(request) + + +def test_update_nfs_share_rest_flattened(): + client = BareMetalSolutionClient( + 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 = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "nfs_share": { + "name": "projects/sample1/locations/sample2/nfsShares/sample3" + } + } + + # get truthy value for each flattened field + mock_args = dict( + nfs_share=gcb_nfs_share.NfsShare(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 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_nfs_share(**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/v2/{nfs_share.name=projects/*/locations/*/nfsShares/*}" + % client.transport._host, + args[1], + ) + + +def test_update_nfs_share_rest_flattened_error(transport: str = "rest"): + client = BareMetalSolutionClient( + 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_nfs_share( + gcb_nfs_share.UpdateNfsShareRequest(), + nfs_share=gcb_nfs_share.NfsShare(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_nfs_share_rest_error(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.BareMetalSolutionGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.BareMetalSolutionGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BareMetalSolutionClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.BareMetalSolutionGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = BareMetalSolutionClient( + 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 = BareMetalSolutionClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.BareMetalSolutionGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = BareMetalSolutionClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.BareMetalSolutionGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = BareMetalSolutionClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.BareMetalSolutionGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.BareMetalSolutionGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.BareMetalSolutionGrpcTransport, + transports.BareMetalSolutionGrpcAsyncIOTransport, + transports.BareMetalSolutionRestTransport, + ], +) +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 = BareMetalSolutionClient.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 = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.BareMetalSolutionGrpcTransport, + ) + + +def test_bare_metal_solution_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.BareMetalSolutionTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_bare_metal_solution_base_transport(): # Instantiate the base transport. with mock.patch( "google.cloud.bare_metal_solution_v2.services.bare_metal_solution.transports.BareMetalSolutionTransport.__init__" @@ -6720,6 +12811,7 @@ def test_bare_metal_solution_transport_auth_adc(transport_class): [ transports.BareMetalSolutionGrpcTransport, transports.BareMetalSolutionGrpcAsyncIOTransport, + transports.BareMetalSolutionRestTransport, ], ) def test_bare_metal_solution_transport_auth_gdch_credentials(transport_class): @@ -6819,11 +12911,40 @@ def test_bare_metal_solution_grpc_transport_client_cert_source_for_mtls( ) +def test_bare_metal_solution_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.BareMetalSolutionRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +def test_bare_metal_solution_rest_lro_client(): + client = BareMetalSolutionClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.AbstractOperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + @pytest.mark.parametrize( "transport_name", [ "grpc", "grpc_asyncio", + "rest", ], ) def test_bare_metal_solution_host_no_port(transport_name): @@ -6834,7 +12955,11 @@ def test_bare_metal_solution_host_no_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("baremetalsolution.googleapis.com:443") + assert client.transport._host == ( + "baremetalsolution.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://baremetalsolution.googleapis.com" + ) @pytest.mark.parametrize( @@ -6842,6 +12967,7 @@ def test_bare_metal_solution_host_no_port(transport_name): [ "grpc", "grpc_asyncio", + "rest", ], ) def test_bare_metal_solution_host_with_port(transport_name): @@ -6852,7 +12978,90 @@ def test_bare_metal_solution_host_with_port(transport_name): ), transport=transport_name, ) - assert client.transport._host == ("baremetalsolution.googleapis.com:8000") + assert client.transport._host == ( + "baremetalsolution.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://baremetalsolution.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_bare_metal_solution_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = BareMetalSolutionClient( + credentials=creds1, + transport=transport_name, + ) + client2 = BareMetalSolutionClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.list_instances._session + session2 = client2.transport.list_instances._session + assert session1 != session2 + session1 = client1.transport.get_instance._session + session2 = client2.transport.get_instance._session + assert session1 != session2 + session1 = client1.transport.update_instance._session + session2 = client2.transport.update_instance._session + assert session1 != session2 + session1 = client1.transport.reset_instance._session + session2 = client2.transport.reset_instance._session + assert session1 != session2 + session1 = client1.transport.start_instance._session + session2 = client2.transport.start_instance._session + assert session1 != session2 + session1 = client1.transport.stop_instance._session + session2 = client2.transport.stop_instance._session + assert session1 != session2 + session1 = client1.transport.detach_lun._session + session2 = client2.transport.detach_lun._session + assert session1 != session2 + session1 = client1.transport.list_volumes._session + session2 = client2.transport.list_volumes._session + assert session1 != session2 + session1 = client1.transport.get_volume._session + session2 = client2.transport.get_volume._session + assert session1 != session2 + session1 = client1.transport.update_volume._session + session2 = client2.transport.update_volume._session + assert session1 != session2 + session1 = client1.transport.resize_volume._session + session2 = client2.transport.resize_volume._session + assert session1 != session2 + session1 = client1.transport.list_networks._session + session2 = client2.transport.list_networks._session + assert session1 != session2 + session1 = client1.transport.list_network_usage._session + session2 = client2.transport.list_network_usage._session + assert session1 != session2 + session1 = client1.transport.get_network._session + session2 = client2.transport.get_network._session + assert session1 != session2 + session1 = client1.transport.update_network._session + session2 = client2.transport.update_network._session + assert session1 != session2 + session1 = client1.transport.get_lun._session + session2 = client2.transport.get_lun._session + assert session1 != session2 + session1 = client1.transport.list_luns._session + session2 = client2.transport.list_luns._session + assert session1 != session2 + session1 = client1.transport.get_nfs_share._session + session2 = client2.transport.get_nfs_share._session + assert session1 != session2 + session1 = client1.transport.list_nfs_shares._session + session2 = client2.transport.list_nfs_shares._session + assert session1 != session2 + session1 = client1.transport.update_nfs_share._session + session2 = client2.transport.update_nfs_share._session + assert session1 != session2 def test_bare_metal_solution_grpc_transport_channel(): @@ -7320,6 +13529,7 @@ async def test_transport_close_async(): def test_transport_close(): transports = { + "rest": "_session", "grpc": "_grpc_channel", } @@ -7337,6 +13547,7 @@ def test_transport_close(): def test_client_ctx(): transports = [ + "rest", "grpc", ] for transport in transports: