From 6c696a2f789777ed7ecdd0cf0af5dc2a6fc97d73 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 May 2024 11:27:28 -0400 Subject: [PATCH 1/3] fix!: [google-maps-fleetengine-delivery] An existing method `UpdateVehicleLocation` is removed from service `VehicleService` (#12667) BEGIN_COMMIT_OVERRIDE fix!: An existing method `UpdateVehicleLocation` is removed from service `VehicleService` fix!: An existing method `SearchFuzzedVehicles` is removed from service `VehicleService` fix!: An existing message `UpdateVehicleLocationRequest` is removed END_COMMIT_OVERRIDE - [ ] Regenerate this pull request now. fix!: An existing method `SearchFuzzedVehicles` is removed from service `VehicleService` fix!: An existing message `UpdateVehicleLocationRequest` is removed PiperOrigin-RevId: 631557549 Source-Link: https://github.com/googleapis/googleapis/commit/3d50414a7ff3f0b8ffe8ad7858257396e4f18131 Source-Link: https://github.com/googleapis/googleapis-gen/commit/5ce63d4e636a975175bde2d16c15e70dd5a81ff4 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtZmxlZXRlbmdpbmUtZGVsaXZlcnkvLk93bEJvdC55YW1sIiwiaCI6IjVjZTYzZDRlNjM2YTk3NTE3NWJkZTJkMTZjMTVlNzBkZDVhODFmZjQifQ== --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> --- .../maps/fleetengine_delivery/__init__.py | 4 - .../fleetengine_delivery/gapic_version.py | 2 +- .../maps/fleetengine_delivery_v1/__init__.py | 4 - .../gapic_metadata.json | 15 - .../fleetengine_delivery_v1/gapic_version.py | 2 +- .../services/delivery_service/async_client.py | 404 +- .../services/delivery_service/client.py | 253 +- .../services/delivery_service/pagers.py | 128 - .../delivery_service/transports/base.py | 26 - .../delivery_service/transports/grpc.py | 51 +- .../transports/grpc_asyncio.py | 199 +- .../delivery_service/transports/rest.py | 130 - .../fleetengine_delivery_v1/types/__init__.py | 4 - .../types/delivery_api.py | 96 - ...ted_delivery_service_search_tasks_async.py | 54 - ...ated_delivery_service_search_tasks_sync.py | 54 - ...metadata_maps.fleetengine.delivery.v1.json | 163 +- .../fixup_fleetengine_delivery_v1_keywords.py | 1 - .../test_delivery_service.py | 4271 +++++++++-------- 19 files changed, 2712 insertions(+), 3149 deletions(-) delete mode 100644 packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_async.py delete mode 100644 packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_sync.py diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/__init__.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/__init__.py index 6afeb1310b2f..52b98b75d2b5 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/__init__.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/__init__.py @@ -44,8 +44,6 @@ ListDeliveryVehiclesResponse, ListTasksRequest, ListTasksResponse, - SearchTasksRequest, - SearchTasksResponse, UpdateDeliveryVehicleRequest, UpdateTaskRequest, ) @@ -81,8 +79,6 @@ "ListDeliveryVehiclesResponse", "ListTasksRequest", "ListTasksResponse", - "SearchTasksRequest", - "SearchTasksResponse", "UpdateDeliveryVehicleRequest", "UpdateTaskRequest", "DeliveryVehicle", diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py index ec8d212c9160..558c8aab67c5 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.8" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/__init__.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/__init__.py index 6a4a75b8f3d8..425525a2bf02 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/__init__.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/__init__.py @@ -39,8 +39,6 @@ ListDeliveryVehiclesResponse, ListTasksRequest, ListTasksResponse, - SearchTasksRequest, - SearchTasksResponse, UpdateDeliveryVehicleRequest, UpdateTaskRequest, ) @@ -75,8 +73,6 @@ "ListTasksRequest", "ListTasksResponse", "LocationInfo", - "SearchTasksRequest", - "SearchTasksResponse", "Task", "TaskAttribute", "TaskTrackingInfo", diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_metadata.json b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_metadata.json index 6ce35415d5e4..8b15810ecafd 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_metadata.json +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_metadata.json @@ -50,11 +50,6 @@ "list_tasks" ] }, - "SearchTasks": { - "methods": [ - "search_tasks" - ] - }, "UpdateDeliveryVehicle": { "methods": [ "update_delivery_vehicle" @@ -110,11 +105,6 @@ "list_tasks" ] }, - "SearchTasks": { - "methods": [ - "search_tasks" - ] - }, "UpdateDeliveryVehicle": { "methods": [ "update_delivery_vehicle" @@ -170,11 +160,6 @@ "list_tasks" ] }, - "SearchTasks": { - "methods": [ - "search_tasks" - ] - }, "UpdateDeliveryVehicle": { "methods": [ "update_delivery_vehicle" diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py index ec8d212c9160..558c8aab67c5 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.8" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py index 6a2b5c2fba76..37a55c41d45a 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/async_client.py @@ -17,6 +17,7 @@ import functools import re from typing import ( + Callable, Dict, Mapping, MutableMapping, @@ -27,7 +28,6 @@ Type, Union, ) -import warnings from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -217,7 +217,11 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, DeliveryServiceTransport] = "grpc_asyncio", + transport: Optional[ + Union[ + str, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport] + ] + ] = "grpc_asyncio", client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -229,9 +233,11 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.DeliveryServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. + transport (Optional[Union[str,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DeliveryServiceTransport constructor. + If set to None, a transport is chosen automatically. client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. @@ -380,8 +386,8 @@ async def sample_create_delivery_vehicle(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_id]) if request is not None and has_flattened_params: raise ValueError( @@ -389,7 +395,10 @@ async def sample_create_delivery_vehicle(): "the individual field arguments should be set." ) - request = delivery_api.CreateDeliveryVehicleRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.CreateDeliveryVehicleRequest): + request = delivery_api.CreateDeliveryVehicleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -402,20 +411,9 @@ async def sample_create_delivery_vehicle(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_delivery_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_delivery_vehicle + ] # Certain fields should be provided within the metadata header; # add these here. @@ -508,8 +506,8 @@ async def sample_get_delivery_vehicle(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( @@ -517,7 +515,10 @@ async def sample_get_delivery_vehicle(): "the individual field arguments should be set." ) - request = delivery_api.GetDeliveryVehicleRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.GetDeliveryVehicleRequest): + request = delivery_api.GetDeliveryVehicleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -526,20 +527,9 @@ async def sample_get_delivery_vehicle(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_delivery_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_delivery_vehicle + ] # Certain fields should be provided within the metadata header; # add these here. @@ -653,8 +643,8 @@ async def sample_update_delivery_vehicle(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([delivery_vehicle, update_mask]) if request is not None and has_flattened_params: raise ValueError( @@ -662,7 +652,10 @@ async def sample_update_delivery_vehicle(): "the individual field arguments should be set." ) - request = delivery_api.UpdateDeliveryVehicleRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.UpdateDeliveryVehicleRequest): + request = delivery_api.UpdateDeliveryVehicleRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -673,20 +666,9 @@ async def sample_update_delivery_vehicle(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_delivery_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_delivery_vehicle + ] # Certain fields should be provided within the metadata header; # add these here. @@ -767,24 +749,16 @@ async def sample_batch_create_tasks(): The BatchCreateTask response message. """ # Create or coerce a protobuf request object. - request = delivery_api.BatchCreateTasksRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.BatchCreateTasksRequest): + request = delivery_api.BatchCreateTasksRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.batch_create_tasks, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_create_tasks + ] # Certain fields should be provided within the metadata header; # add these here. @@ -927,8 +901,8 @@ async def sample_create_task(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, task, task_id]) if request is not None and has_flattened_params: raise ValueError( @@ -936,7 +910,10 @@ async def sample_create_task(): "the individual field arguments should be set." ) - request = delivery_api.CreateTaskRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.CreateTaskRequest): + request = delivery_api.CreateTaskRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -949,20 +926,9 @@ async def sample_create_task(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_task, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_task + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1060,8 +1026,8 @@ async def sample_get_task(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( @@ -1069,7 +1035,10 @@ async def sample_get_task(): "the individual field arguments should be set." ) - request = delivery_api.GetTaskRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.GetTaskRequest): + request = delivery_api.GetTaskRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1078,20 +1047,7 @@ async def sample_get_task(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_task, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_task] # Certain fields should be provided within the metadata header; # add these here. @@ -1113,140 +1069,6 @@ async def sample_get_task(): # Done; return the response. return response - async def search_tasks( - self, - request: Optional[Union[delivery_api.SearchTasksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchTasksAsyncPager: - r"""Deprecated: Use ``GetTaskTrackingInfo`` instead. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import fleetengine_delivery_v1 - - async def sample_search_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.SearchTasksRequest( - parent="parent_value", - tracking_id="tracking_id_value", - ) - - # Make the request - page_result = client.search_tasks(request=request) - - # Handle the response - async for response in page_result: - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_delivery_v1.types.SearchTasksRequest, dict]]): - The request object. Deprecated: Issue ``GetTaskTrackingInfoRequest``\ s to - ``GetTaskTrackingInfo`` instead. - parent (:class:`str`): - Required. Must be in the format - ``providers/{provider}``. The provider must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry_async.AsyncRetry): 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: - google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.SearchTasksAsyncPager: - The SearchTasks response. It contains the set of Tasks that meet the search - criteria in the SearchTasksRequest. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - warnings.warn( - "DeliveryServiceAsyncClient.search_tasks is deprecated", DeprecationWarning - ) - - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = delivery_api.SearchTasksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_tasks, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.SearchTasksAsyncPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - async def update_task( self, request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, @@ -1354,8 +1176,8 @@ async def sample_update_task(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([task, update_mask]) if request is not None and has_flattened_params: raise ValueError( @@ -1363,7 +1185,10 @@ async def sample_update_task(): "the individual field arguments should be set." ) - request = delivery_api.UpdateTaskRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.UpdateTaskRequest): + request = delivery_api.UpdateTaskRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1374,20 +1199,9 @@ async def sample_update_task(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_task, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_task + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1477,8 +1291,8 @@ async def sample_list_tasks(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( @@ -1486,7 +1300,10 @@ async def sample_list_tasks(): "the individual field arguments should be set." ) - request = delivery_api.ListTasksRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.ListTasksRequest): + request = delivery_api.ListTasksRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1495,20 +1312,9 @@ async def sample_list_tasks(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_tasks, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_tasks + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1606,8 +1412,8 @@ async def sample_get_task_tracking_info(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( @@ -1615,7 +1421,10 @@ async def sample_get_task_tracking_info(): "the individual field arguments should be set." ) - request = delivery_api.GetTaskTrackingInfoRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.GetTaskTrackingInfoRequest): + request = delivery_api.GetTaskTrackingInfoRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1624,20 +1433,9 @@ async def sample_get_task_tracking_info(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_task_tracking_info, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_task_tracking_info + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1725,8 +1523,8 @@ async def sample_list_delivery_vehicles(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( @@ -1734,7 +1532,10 @@ async def sample_list_delivery_vehicles(): "the individual field arguments should be set." ) - request = delivery_api.ListDeliveryVehiclesRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, delivery_api.ListDeliveryVehiclesRequest): + request = delivery_api.ListDeliveryVehiclesRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. @@ -1743,20 +1544,9 @@ async def sample_list_delivery_vehicles(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_delivery_vehicles, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_delivery_vehicles + ] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py index 1a08e0703cc1..8d7009205760 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/client.py @@ -17,6 +17,7 @@ import os import re from typing import ( + Callable, Dict, Mapping, MutableMapping, @@ -574,7 +575,11 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, DeliveryServiceTransport]] = None, + transport: Optional[ + Union[ + str, DeliveryServiceTransport, Callable[..., DeliveryServiceTransport] + ] + ] = None, client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -586,9 +591,11 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, DeliveryServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. + transport (Optional[Union[str,DeliveryServiceTransport,Callable[..., DeliveryServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the DeliveryServiceTransport constructor. + If set to None, a transport is chosen automatically. client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. @@ -697,8 +704,15 @@ def __init__( api_key_value ) - Transport = type(self).get_transport_class(cast(str, transport)) - self._transport = Transport( + transport_init: Union[ + Type[DeliveryServiceTransport], Callable[..., DeliveryServiceTransport] + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., DeliveryServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( credentials=credentials, credentials_file=self._client_options.credentials_file, host=self._api_endpoint, @@ -815,8 +829,8 @@ def sample_create_delivery_vehicle(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, delivery_vehicle, delivery_vehicle_id]) if request is not None and has_flattened_params: raise ValueError( @@ -824,10 +838,8 @@ def sample_create_delivery_vehicle(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.CreateDeliveryVehicleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.CreateDeliveryVehicleRequest): request = delivery_api.CreateDeliveryVehicleRequest(request) # If we have keyword arguments corresponding to fields on the @@ -940,8 +952,8 @@ def sample_get_delivery_vehicle(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( @@ -949,10 +961,8 @@ def sample_get_delivery_vehicle(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.GetDeliveryVehicleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.GetDeliveryVehicleRequest): request = delivery_api.GetDeliveryVehicleRequest(request) # If we have keyword arguments corresponding to fields on the @@ -1082,8 +1092,8 @@ def sample_update_delivery_vehicle(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([delivery_vehicle, update_mask]) if request is not None and has_flattened_params: raise ValueError( @@ -1091,10 +1101,8 @@ def sample_update_delivery_vehicle(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.UpdateDeliveryVehicleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.UpdateDeliveryVehicleRequest): request = delivery_api.UpdateDeliveryVehicleRequest(request) # If we have keyword arguments corresponding to fields on the @@ -1191,10 +1199,8 @@ def sample_batch_create_tasks(): The BatchCreateTask response message. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.BatchCreateTasksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.BatchCreateTasksRequest): request = delivery_api.BatchCreateTasksRequest(request) @@ -1349,8 +1355,8 @@ def sample_create_task(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent, task, task_id]) if request is not None and has_flattened_params: raise ValueError( @@ -1358,10 +1364,8 @@ def sample_create_task(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.CreateTaskRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.CreateTaskRequest): request = delivery_api.CreateTaskRequest(request) # If we have keyword arguments corresponding to fields on the @@ -1479,8 +1483,8 @@ def sample_get_task(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( @@ -1488,10 +1492,8 @@ def sample_get_task(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.GetTaskRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.GetTaskRequest): request = delivery_api.GetTaskRequest(request) # If we have keyword arguments corresponding to fields on the @@ -1529,137 +1531,6 @@ def sample_get_task(): # Done; return the response. return response - def search_tasks( - self, - request: Optional[Union[delivery_api.SearchTasksRequest, dict]] = None, - *, - parent: Optional[str] = None, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.SearchTasksPager: - r"""Deprecated: Use ``GetTaskTrackingInfo`` instead. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import fleetengine_delivery_v1 - - def sample_search_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.SearchTasksRequest( - parent="parent_value", - tracking_id="tracking_id_value", - ) - - # Make the request - page_result = client.search_tasks(request=request) - - # Handle the response - for response in page_result: - print(response) - - Args: - request (Union[google.maps.fleetengine_delivery_v1.types.SearchTasksRequest, dict]): - The request object. Deprecated: Issue ``GetTaskTrackingInfoRequest``\ s to - ``GetTaskTrackingInfo`` instead. - parent (str): - Required. Must be in the format - ``providers/{provider}``. The provider must be the - Google Cloud Project ID. For example, - ``sample-cloud-project``. - - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - retry (google.api_core.retry.Retry): Designation of what errors, if any, - should be retried. - timeout (float): The timeout for this request. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.SearchTasksPager: - The SearchTasks response. It contains the set of Tasks that meet the search - criteria in the SearchTasksRequest. - - Iterating over this object will yield results and - resolve additional pages automatically. - - """ - warnings.warn( - "DeliveryServiceClient.search_tasks is deprecated", DeprecationWarning - ) - - # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - if request is not None and has_flattened_params: - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.SearchTasksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, delivery_api.SearchTasksRequest): - request = delivery_api.SearchTasksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_tasks] - - header_params = {} - - routing_param_regex = re.compile("^(?P<provider_id>providers/[^/]+)$") - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.SearchTasksPager( - method=rpc, - request=request, - response=response, - metadata=metadata, - ) - - # Done; return the response. - return response - def update_task( self, request: Optional[Union[delivery_api.UpdateTaskRequest, dict]] = None, @@ -1767,8 +1638,8 @@ def sample_update_task(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([task, update_mask]) if request is not None and has_flattened_params: raise ValueError( @@ -1776,10 +1647,8 @@ def sample_update_task(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.UpdateTaskRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.UpdateTaskRequest): request = delivery_api.UpdateTaskRequest(request) # If we have keyword arguments corresponding to fields on the @@ -1885,8 +1754,8 @@ def sample_list_tasks(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( @@ -1894,10 +1763,8 @@ def sample_list_tasks(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.ListTasksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.ListTasksRequest): request = delivery_api.ListTasksRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2011,8 +1878,8 @@ def sample_get_task_tracking_info(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([name]) if request is not None and has_flattened_params: raise ValueError( @@ -2020,10 +1887,8 @@ def sample_get_task_tracking_info(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.GetTaskTrackingInfoRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.GetTaskTrackingInfoRequest): request = delivery_api.GetTaskTrackingInfoRequest(request) # If we have keyword arguments corresponding to fields on the @@ -2127,8 +1992,8 @@ def sample_list_delivery_vehicles(): """ # Create or coerce a protobuf request object. - # Quick check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. has_flattened_params = any([parent]) if request is not None and has_flattened_params: raise ValueError( @@ -2136,10 +2001,8 @@ def sample_list_delivery_vehicles(): "the individual field arguments should be set." ) - # Minor optimization to avoid making a copy if the user passes - # in a delivery_api.ListDeliveryVehiclesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, delivery_api.ListDeliveryVehiclesRequest): request = delivery_api.ListDeliveryVehiclesRequest(request) # If we have keyword arguments corresponding to fields on the diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py index 922c49f9d89a..70f7e807101b 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/pagers.py @@ -31,134 +31,6 @@ ) -class SearchTasksPager: - """A pager for iterating through ``search_tasks`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.SearchTasksResponse` object, and - provides an ``__iter__`` method to iterate through its - ``tasks`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``SearchTasks`` requests and continue to iterate - through the ``tasks`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.SearchTasksResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., delivery_api.SearchTasksResponse], - request: delivery_api.SearchTasksRequest, - response: delivery_api.SearchTasksResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_delivery_v1.types.SearchTasksRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.SearchTasksResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = delivery_api.SearchTasksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterator[delivery_api.SearchTasksResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterator[tasks.Task]: - for page in self.pages: - yield from page.tasks - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class SearchTasksAsyncPager: - """A pager for iterating through ``search_tasks`` requests. - - This class thinly wraps an initial - :class:`google.maps.fleetengine_delivery_v1.types.SearchTasksResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``tasks`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``SearchTasks`` requests and continue to iterate - through the ``tasks`` field on the - corresponding responses. - - All the usual :class:`google.maps.fleetengine_delivery_v1.types.SearchTasksResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[delivery_api.SearchTasksResponse]], - request: delivery_api.SearchTasksRequest, - response: delivery_api.SearchTasksResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiates the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (google.maps.fleetengine_delivery_v1.types.SearchTasksRequest): - The initial request object. - response (google.maps.fleetengine_delivery_v1.types.SearchTasksResponse): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = delivery_api.SearchTasksRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterator[delivery_api.SearchTasksResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterator[tasks.Task]: - async def async_generator(): - async for page in self.pages: - for response in page.tasks: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - class ListTasksPager: """A pager for iterating through ``list_tasks`` requests. diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py index f97bb8b1d30c..e78e4907b3b0 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/base.py @@ -215,20 +215,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), - self.search_tasks: gapic_v1.method.wrap_method( - self.search_tasks, - default_retry=retries.Retry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=60.0, - ), - default_timeout=60.0, - client_info=client_info, - ), self.update_task: gapic_v1.method.wrap_method( self.update_task, default_retry=retries.Retry( @@ -360,18 +346,6 @@ def get_task( ]: raise NotImplementedError() - @property - def search_tasks( - self, - ) -> Callable[ - [delivery_api.SearchTasksRequest], - Union[ - delivery_api.SearchTasksResponse, - Awaitable[delivery_api.SearchTasksResponse], - ], - ]: - raise NotImplementedError() - @property def update_task( self, diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py index 0ab883d6c8e7..1f4dc3bd9d4a 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc.py @@ -54,7 +54,7 @@ def __init__( credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, api_mtls_endpoint: Optional[str] = None, client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, @@ -74,14 +74,17 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. 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. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from @@ -91,11 +94,11 @@ def __init__( private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if a ``channel`` instance is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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): @@ -121,7 +124,7 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, grpc.Channel): # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. @@ -162,7 +165,9 @@ def __init__( ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -401,32 +406,6 @@ def get_task(self) -> Callable[[delivery_api.GetTaskRequest], tasks.Task]: ) return self._stubs["get_task"] - @property - def search_tasks( - self, - ) -> Callable[[delivery_api.SearchTasksRequest], delivery_api.SearchTasksResponse]: - r"""Return a callable for the search tasks method over gRPC. - - Deprecated: Use ``GetTaskTrackingInfo`` instead. - - Returns: - Callable[[~.SearchTasksRequest], - ~.SearchTasksResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "search_tasks" not in self._stubs: - self._stubs["search_tasks"] = self.grpc_channel.unary_unary( - "/maps.fleetengine.delivery.v1.DeliveryService/SearchTasks", - request_serializer=delivery_api.SearchTasksRequest.serialize, - response_deserializer=delivery_api.SearchTasksResponse.deserialize, - ) - return self._stubs["search_tasks"] - @property def update_task(self) -> Callable[[delivery_api.UpdateTaskRequest], tasks.Task]: r"""Return a callable for the update task method over gRPC. diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py index 31fc9611734e..67458a2a9550 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/grpc_asyncio.py @@ -16,7 +16,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore @@ -69,7 +71,6 @@ def create_channel( 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 optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -99,7 +100,7 @@ def __init__( credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, api_mtls_endpoint: Optional[str] = None, client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, @@ -119,15 +120,18 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. 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. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from @@ -137,11 +141,11 @@ def __init__( private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if a ``channel`` instance is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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): @@ -167,7 +171,7 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, aio.Channel): # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. @@ -207,7 +211,9 @@ def __init__( ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -412,34 +418,6 @@ def get_task( ) return self._stubs["get_task"] - @property - def search_tasks( - self, - ) -> Callable[ - [delivery_api.SearchTasksRequest], Awaitable[delivery_api.SearchTasksResponse] - ]: - r"""Return a callable for the search tasks method over gRPC. - - Deprecated: Use ``GetTaskTrackingInfo`` instead. - - Returns: - Callable[[~.SearchTasksRequest], - Awaitable[~.SearchTasksResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "search_tasks" not in self._stubs: - self._stubs["search_tasks"] = self.grpc_channel.unary_unary( - "/maps.fleetengine.delivery.v1.DeliveryService/SearchTasks", - request_serializer=delivery_api.SearchTasksRequest.serialize, - response_deserializer=delivery_api.SearchTasksResponse.deserialize, - ) - return self._stubs["search_tasks"] - @property def update_task( self, @@ -553,6 +531,151 @@ def list_delivery_vehicles( ) return self._stubs["list_delivery_vehicles"] + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_delivery_vehicle: gapic_v1.method_async.wrap_method( + self.create_delivery_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_delivery_vehicle: gapic_v1.method_async.wrap_method( + self.get_delivery_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_delivery_vehicle: gapic_v1.method_async.wrap_method( + self.update_delivery_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.batch_create_tasks: gapic_v1.method_async.wrap_method( + self.batch_create_tasks, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.create_task: gapic_v1.method_async.wrap_method( + self.create_task, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_task: gapic_v1.method_async.wrap_method( + self.get_task, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.update_task: gapic_v1.method_async.wrap_method( + self.update_task, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_tasks: gapic_v1.method_async.wrap_method( + self.list_tasks, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_task_tracking_info: gapic_v1.method_async.wrap_method( + self.get_task_tracking_info, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.list_delivery_vehicles: gapic_v1.method_async.wrap_method( + self.list_delivery_vehicles, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + } + def close(self): return self.grpc_channel.close() diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py index 3c76254836eb..80eec93ef857 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/services/delivery_service/transports/rest.py @@ -132,14 +132,6 @@ def post_list_tasks(self, response): logging.log(f"Received response: {response}") return response - def pre_search_tasks(self, request, metadata): - logging.log(f"Received request: {request}") - return request, metadata - - def post_search_tasks(self, response): - logging.log(f"Received response: {response}") - return response - def pre_update_delivery_vehicle(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -340,29 +332,6 @@ def post_list_tasks( """ return response - def pre_search_tasks( - self, - request: delivery_api.SearchTasksRequest, - metadata: Sequence[Tuple[str, str]], - ) -> Tuple[delivery_api.SearchTasksRequest, Sequence[Tuple[str, str]]]: - """Pre-rpc interceptor for search_tasks - - Override in a subclass to manipulate the request or metadata - before they are sent to the DeliveryService server. - """ - return request, metadata - - def post_search_tasks( - self, response: delivery_api.SearchTasksResponse - ) -> delivery_api.SearchTasksResponse: - """Post-rpc interceptor for search_tasks - - Override in a subclass to manipulate the response - after it is returned by the DeliveryService server but before - it is returned to user code. - """ - return response - def pre_update_delivery_vehicle( self, request: delivery_api.UpdateDeliveryVehicleRequest, @@ -1283,97 +1252,6 @@ def __call__( resp = self._interceptor.post_list_tasks(resp) return resp - class _SearchTasks(DeliveryServiceRestStub): - def __hash__(self): - return hash("SearchTasks") - - __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { - "trackingId": "", - } - - @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: delivery_api.SearchTasksRequest, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Optional[float] = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> delivery_api.SearchTasksResponse: - r"""Call the search tasks method over HTTP. - - Args: - request (~.delivery_api.SearchTasksRequest): - The request object. Deprecated: Issue ``GetTaskTrackingInfoRequest``\ s to - ``GetTaskTrackingInfo`` instead. - 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: - ~.delivery_api.SearchTasksResponse: - The ``SearchTasks`` response. It contains the set of - Tasks that meet the search criteria in the - ``SearchTasksRequest``. - - """ - - http_options: List[Dict[str, str]] = [ - { - "method": "get", - "uri": "/v1/{parent=providers/*}/tasks:search", - }, - ] - request, metadata = self._interceptor.pre_search_tasks(request, metadata) - pb_request = delivery_api.SearchTasksRequest.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"], - 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 = delivery_api.SearchTasksResponse() - pb_resp = delivery_api.SearchTasksResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_search_tasks(resp) - return resp - class _UpdateDeliveryVehicle(DeliveryServiceRestStub): def __hash__(self): return hash("UpdateDeliveryVehicle") @@ -1663,14 +1541,6 @@ def list_tasks( # In C++ this would require a dynamic_cast return self._ListTasks(self._session, self._host, self._interceptor) # type: ignore - @property - def search_tasks( - self, - ) -> Callable[[delivery_api.SearchTasksRequest], delivery_api.SearchTasksResponse]: - # 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._SearchTasks(self._session, self._host, self._interceptor) # type: ignore - @property def update_delivery_vehicle( self, diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/__init__.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/__init__.py index 2ece31ed2383..ba147eb22b17 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/__init__.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/__init__.py @@ -33,8 +33,6 @@ ListDeliveryVehiclesResponse, ListTasksRequest, ListTasksResponse, - SearchTasksRequest, - SearchTasksResponse, UpdateDeliveryVehicleRequest, UpdateTaskRequest, ) @@ -66,8 +64,6 @@ "ListDeliveryVehiclesResponse", "ListTasksRequest", "ListTasksResponse", - "SearchTasksRequest", - "SearchTasksResponse", "UpdateDeliveryVehicleRequest", "UpdateTaskRequest", "DeliveryVehicle", diff --git a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py index f324f646ba7b..39f2254f731f 100644 --- a/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py +++ b/packages/google-maps-fleetengine-delivery/google/maps/fleetengine_delivery_v1/types/delivery_api.py @@ -39,8 +39,6 @@ "BatchCreateTasksResponse", "CreateTaskRequest", "GetTaskRequest", - "SearchTasksRequest", - "SearchTasksResponse", "UpdateTaskRequest", "ListTasksRequest", "ListTasksResponse", @@ -426,100 +424,6 @@ class GetTaskRequest(proto.Message): ) -class SearchTasksRequest(proto.Message): - r"""Deprecated: Issue ``GetTaskTrackingInfoRequest``\ s to - ``GetTaskTrackingInfo`` instead. - - Attributes: - header (google.maps.fleetengine_delivery_v1.types.DeliveryRequestHeader): - Optional. The standard Delivery API request - header. - parent (str): - Required. Must be in the format ``providers/{provider}``. - The provider must be the Google Cloud Project ID. For - example, ``sample-cloud-project``. - tracking_id (str): - Required. The identifier of the set of related Tasks being - requested. Tracking IDs are subject to the following - restrictions: - - - Must be a valid Unicode string. - - Limited to a maximum length of 64 characters. - - Normalized according to [Unicode Normalization Form C] - (http://www.unicode.org/reports/tr15/). - - May not contain any of the following ASCII characters: - '/', ':', '?', ',', or '#'. - page_size (int): - Optional. The maximum number of Tasks to - return. The service may return fewer than this - value. If you don't specify this value, then the - server determines the number of results to - return. - page_token (str): - Optional. A page token, received from a previous - ``SearchTasks`` call. You must provide this value to - retrieve the subsequent page. - - When paginating, all other parameters provided to - ``SearchTasks`` must match the call that provided the page - token. - """ - - header: mfd_header.DeliveryRequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mfd_header.DeliveryRequestHeader, - ) - parent: str = proto.Field( - proto.STRING, - number=3, - ) - tracking_id: str = proto.Field( - proto.STRING, - number=4, - ) - page_size: int = proto.Field( - proto.INT32, - number=5, - ) - page_token: str = proto.Field( - proto.STRING, - number=6, - ) - - -class SearchTasksResponse(proto.Message): - r"""The ``SearchTasks`` response. It contains the set of Tasks that meet - the search criteria in the ``SearchTasksRequest``. - - Attributes: - tasks (MutableSequence[google.maps.fleetengine_delivery_v1.types.Task]): - The set of Tasks for the requested ``tracking_id``. A - successful response can also be empty. An empty response - indicates that no Tasks are associated with the supplied - ``tracking_id``. - next_page_token (str): - Pass this token in the ``SearchTasksRequest`` to continue to - list results. If all results have been returned, then this - field is either an empty string, or it doesn't appear in the - response. - """ - - @property - def raw_page(self): - return self - - tasks: MutableSequence[mfd_tasks.Task] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message=mfd_tasks.Task, - ) - next_page_token: str = proto.Field( - proto.STRING, - number=2, - ) - - class UpdateTaskRequest(proto.Message): r"""The ``UpdateTask`` request message. diff --git a/packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_async.py b/packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_async.py deleted file mode 100644 index 8c2f1cb7f5a7..000000000000 --- a/packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_async.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchTasks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_SearchTasks_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import fleetengine_delivery_v1 - - -async def sample_search_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.SearchTasksRequest( - parent="parent_value", - tracking_id="tracking_id_value", - ) - - # Make the request - page_result = client.search_tasks(request=request) - - # Handle the response - async for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_SearchTasks_async] diff --git a/packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_sync.py b/packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_sync.py deleted file mode 100644 index adca27490b17..000000000000 --- a/packages/google-maps-fleetengine-delivery/samples/generated_samples/fleetengine_v1_generated_delivery_service_search_tasks_sync.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchTasks -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-fleetengine-delivery - - -# [START fleetengine_v1_generated_DeliveryService_SearchTasks_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import fleetengine_delivery_v1 - - -def sample_search_tasks(): - # Create a client - client = fleetengine_delivery_v1.DeliveryServiceClient() - - # Initialize request argument(s) - request = fleetengine_delivery_v1.SearchTasksRequest( - parent="parent_value", - tracking_id="tracking_id_value", - ) - - # Make the request - page_result = client.search_tasks(request=request) - - # Handle the response - for response in page_result: - print(response) - -# [END fleetengine_v1_generated_DeliveryService_SearchTasks_sync] diff --git a/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json b/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json index e7c649067416..884ac226d0e4 100644 --- a/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json +++ b/packages/google-maps-fleetengine-delivery/samples/generated_samples/snippet_metadata_maps.fleetengine.delivery.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-maps-fleetengine-delivery", - "version": "0.1.8" + "version": "0.1.0" }, "snippets": [ { @@ -1323,167 +1323,6 @@ ], "title": "fleetengine_v1_generated_delivery_service_list_tasks_sync.py" }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient", - "shortName": "DeliveryServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceAsyncClient.search_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.SearchTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "SearchTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.SearchTasksRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.SearchTasksAsyncPager", - "shortName": "search_tasks" - }, - "description": "Sample for SearchTasks", - "file": "fleetengine_v1_generated_delivery_service_search_tasks_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_SearchTasks_async", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_search_tasks_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient", - "shortName": "DeliveryServiceClient" - }, - "fullName": "google.maps.fleetengine_delivery_v1.DeliveryServiceClient.search_tasks", - "method": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService.SearchTasks", - "service": { - "fullName": "maps.fleetengine.delivery.v1.DeliveryService", - "shortName": "DeliveryService" - }, - "shortName": "SearchTasks" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_delivery_v1.types.SearchTasksRequest" - }, - { - "name": "parent", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_delivery_v1.services.delivery_service.pagers.SearchTasksPager", - "shortName": "search_tasks" - }, - "description": "Sample for SearchTasks", - "file": "fleetengine_v1_generated_delivery_service_search_tasks_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_DeliveryService_SearchTasks_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_delivery_service_search_tasks_sync.py" - }, { "canonical": true, "clientMethod": { diff --git a/packages/google-maps-fleetengine-delivery/scripts/fixup_fleetengine_delivery_v1_keywords.py b/packages/google-maps-fleetengine-delivery/scripts/fixup_fleetengine_delivery_v1_keywords.py index 733bb5702c4c..8dc89e72edee 100644 --- a/packages/google-maps-fleetengine-delivery/scripts/fixup_fleetengine_delivery_v1_keywords.py +++ b/packages/google-maps-fleetengine-delivery/scripts/fixup_fleetengine_delivery_v1_keywords.py @@ -47,7 +47,6 @@ class fleetengine_deliveryCallTransformer(cst.CSTTransformer): 'get_task_tracking_info': ('name', 'header', ), 'list_delivery_vehicles': ('parent', 'header', 'page_size', 'page_token', 'filter', 'viewport', ), 'list_tasks': ('parent', 'header', 'page_size', 'page_token', 'filter', ), - 'search_tasks': ('parent', 'tracking_id', 'header', 'page_size', 'page_token', ), 'update_delivery_vehicle': ('delivery_vehicle', 'update_mask', 'header', ), 'update_task': ('task', 'update_mask', 'header', ), } diff --git a/packages/google-maps-fleetengine-delivery/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py b/packages/google-maps-fleetengine-delivery/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py index 90e425880e9b..497378bbdeb5 100644 --- a/packages/google-maps-fleetengine-delivery/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py +++ b/packages/google-maps-fleetengine-delivery/tests/unit/gapic/fleetengine_delivery_v1/test_delivery_service.py @@ -1211,6 +1211,9 @@ def test_create_delivery_vehicle_empty_call(): with mock.patch.object( type(client.transport.create_delivery_vehicle), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_delivery_vehicle() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1237,6 +1240,9 @@ def test_create_delivery_vehicle_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.create_delivery_vehicle), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_delivery_vehicle(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1246,6 +1252,46 @@ def test_create_delivery_vehicle_non_empty_request_with_auto_populated_field(): ) +def test_create_delivery_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_delivery_vehicle + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_delivery_vehicle + ] = mock_rpc + request = {} + client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_create_delivery_vehicle_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1274,6 +1320,52 @@ async def test_create_delivery_vehicle_empty_call_async(): assert args[0] == delivery_api.CreateDeliveryVehicleRequest() +@pytest.mark.asyncio +async def test_create_delivery_vehicle_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_delivery_vehicle + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_delivery_vehicle + ] = mock_object + + request = {} + await client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_create_delivery_vehicle_async( transport: str = "grpc_asyncio", @@ -1516,6 +1608,9 @@ def test_get_delivery_vehicle_empty_call(): with mock.patch.object( type(client.transport.get_delivery_vehicle), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_delivery_vehicle() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1541,6 +1636,9 @@ def test_get_delivery_vehicle_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.get_delivery_vehicle), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_delivery_vehicle(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1549,6 +1647,45 @@ def test_get_delivery_vehicle_non_empty_request_with_auto_populated_field(): ) +def test_get_delivery_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_delivery_vehicle in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_delivery_vehicle + ] = mock_rpc + request = {} + client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_get_delivery_vehicle_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1577,6 +1714,52 @@ async def test_get_delivery_vehicle_empty_call_async(): assert args[0] == delivery_api.GetDeliveryVehicleRequest() +@pytest.mark.asyncio +async def test_get_delivery_vehicle_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_delivery_vehicle + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_delivery_vehicle + ] = mock_object + + request = {} + await client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_get_delivery_vehicle_async( transport: str = "grpc_asyncio", request_type=delivery_api.GetDeliveryVehicleRequest @@ -1796,6 +1979,9 @@ def test_update_delivery_vehicle_empty_call(): with mock.patch.object( type(client.transport.update_delivery_vehicle), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_delivery_vehicle() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1819,12 +2005,55 @@ def test_update_delivery_vehicle_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.update_delivery_vehicle), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_delivery_vehicle(request=request) call.assert_called() _, args, _ = call.mock_calls[0] assert args[0] == delivery_api.UpdateDeliveryVehicleRequest() +def test_update_delivery_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_delivery_vehicle + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_delivery_vehicle + ] = mock_rpc + request = {} + client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_update_delivery_vehicle_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1853,6 +2082,52 @@ async def test_update_delivery_vehicle_empty_call_async(): assert args[0] == delivery_api.UpdateDeliveryVehicleRequest() +@pytest.mark.asyncio +async def test_update_delivery_vehicle_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_delivery_vehicle + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_delivery_vehicle + ] = mock_object + + request = {} + await client.update_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_update_delivery_vehicle_async( transport: str = "grpc_asyncio", @@ -2074,6 +2349,9 @@ def test_batch_create_tasks_empty_call(): with mock.patch.object( type(client.transport.batch_create_tasks), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.batch_create_tasks() call.assert_called() _, args, _ = call.mock_calls[0] @@ -2099,6 +2377,9 @@ def test_batch_create_tasks_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.batch_create_tasks), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.batch_create_tasks(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -2107,6 +2388,45 @@ def test_batch_create_tasks_non_empty_request_with_auto_populated_field(): ) +def test_batch_create_tasks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_tasks in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_tasks + ] = mock_rpc + request = {} + client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_tasks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_batch_create_tasks_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -2130,6 +2450,52 @@ async def test_batch_create_tasks_empty_call_async(): assert args[0] == delivery_api.BatchCreateTasksRequest() +@pytest.mark.asyncio +async def test_batch_create_tasks_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_create_tasks + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_create_tasks + ] = mock_object + + request = {} + await client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.batch_create_tasks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_batch_create_tasks_async( transport: str = "grpc_asyncio", request_type=delivery_api.BatchCreateTasksRequest @@ -2255,6 +2621,9 @@ def test_create_task_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_task() call.assert_called() _, args, _ = call.mock_calls[0] @@ -2279,6 +2648,9 @@ def test_create_task_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_task), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_task(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -2288,6 +2660,41 @@ def test_create_task_non_empty_request_with_auto_populated_field(): ) +def test_create_task_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_task] = mock_rpc + request = {} + client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_create_task_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -2317,6 +2724,52 @@ async def test_create_task_empty_call_async(): assert args[0] == delivery_api.CreateTaskRequest() +@pytest.mark.asyncio +async def test_create_task_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_task + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_task + ] = mock_object + + request = {} + await client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_create_task_async( transport: str = "grpc_asyncio", request_type=delivery_api.CreateTaskRequest @@ -2556,6 +3009,9 @@ def test_get_task_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_task() call.assert_called() _, args, _ = call.mock_calls[0] @@ -2579,6 +3035,9 @@ def test_get_task_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_task), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_task(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -2587,6 +3046,41 @@ def test_get_task_non_empty_request_with_auto_populated_field(): ) +def test_get_task_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_task] = mock_rpc + request = {} + client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_get_task_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -2616,6 +3110,50 @@ async def test_get_task_empty_call_async(): assert args[0] == delivery_api.GetTaskRequest() +@pytest.mark.asyncio +async def test_get_task_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_task + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_task + ] = mock_object + + request = {} + await client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_get_task_async( transport: str = "grpc_asyncio", request_type=delivery_api.GetTaskRequest @@ -2777,11 +3315,11 @@ async def test_get_task_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - delivery_api.SearchTasksRequest, + delivery_api.UpdateTaskRequest, dict, ], ) -def test_search_tasks(request_type, transport: str = "grpc"): +def test_update_task(request_type, transport: str = "grpc"): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2792,25 +3330,40 @@ def test_search_tasks(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: + with mock.patch.object(type(client.transport.update_task), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = delivery_api.SearchTasksResponse( - next_page_token="next_page_token_value", + call.return_value = tasks.Task( + name="name_value", + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id="tracking_id_value", + delivery_vehicle_id="delivery_vehicle_id_value", ) - response = client.search_tasks(request) + response = client.update_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = delivery_api.SearchTasksRequest() + request = delivery_api.UpdateTaskRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTasksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, tasks.Task) + assert response.name == "name_value" + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert ( + response.task_outcome_location_source + == tasks.Task.TaskOutcomeLocationSource.PROVIDER + ) + assert response.tracking_id == "tracking_id_value" + assert response.delivery_vehicle_id == "delivery_vehicle_id_value" -def test_search_tasks_empty_call(): +def test_update_task_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DeliveryServiceClient( @@ -2819,14 +3372,17 @@ def test_search_tasks_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: - client.search_tasks() + with mock.patch.object(type(client.transport.update_task), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_task() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.SearchTasksRequest() + assert args[0] == delivery_api.UpdateTaskRequest() -def test_search_tasks_non_empty_request_with_auto_populated_field(): +def test_update_task_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = DeliveryServiceClient( @@ -2837,26 +3393,56 @@ def test_search_tasks_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = delivery_api.SearchTasksRequest( - parent="parent_value", - tracking_id="tracking_id_value", - page_token="page_token_value", - ) + request = delivery_api.UpdateTaskRequest() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: - client.search_tasks(request=request) + with mock.patch.object(type(client.transport.update_task), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.update_task(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.SearchTasksRequest( - parent="parent_value", - tracking_id="tracking_id_value", - page_token="page_token_value", + assert args[0] == delivery_api.UpdateTaskRequest() + + +def test_update_task_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) + client._transport._wrapped_methods[client._transport.update_task] = mock_rpc + request = {} + client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 @pytest.mark.asyncio -async def test_search_tasks_empty_call_async(): +async def test_update_task_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DeliveryServiceAsyncClient( @@ -2865,22 +3451,74 @@ async def test_search_tasks_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: + with mock.patch.object(type(client.transport.update_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - delivery_api.SearchTasksResponse( - next_page_token="next_page_token_value", + tasks.Task( + name="name_value", + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id="tracking_id_value", + delivery_vehicle_id="delivery_vehicle_id_value", ) ) - response = await client.search_tasks() + response = await client.update_task() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.SearchTasksRequest() + assert args[0] == delivery_api.UpdateTaskRequest() + + +@pytest.mark.asyncio +async def test_update_task_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_task + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_task + ] = mock_object + + request = {} + await client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 @pytest.mark.asyncio -async def test_search_tasks_async( - transport: str = "grpc_asyncio", request_type=delivery_api.SearchTasksRequest +async def test_update_task_async( + transport: str = "grpc_asyncio", request_type=delivery_api.UpdateTaskRequest ): client = DeliveryServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2892,44 +3530,59 @@ async def test_search_tasks_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: + with mock.patch.object(type(client.transport.update_task), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - delivery_api.SearchTasksResponse( - next_page_token="next_page_token_value", + tasks.Task( + name="name_value", + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id="tracking_id_value", + delivery_vehicle_id="delivery_vehicle_id_value", ) ) - response = await client.search_tasks(request) + response = await client.update_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = delivery_api.SearchTasksRequest() + request = delivery_api.UpdateTaskRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTasksAsyncPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, tasks.Task) + assert response.name == "name_value" + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert ( + response.task_outcome_location_source + == tasks.Task.TaskOutcomeLocationSource.PROVIDER + ) + assert response.tracking_id == "tracking_id_value" + assert response.delivery_vehicle_id == "delivery_vehicle_id_value" @pytest.mark.asyncio -async def test_search_tasks_async_from_dict(): - await test_search_tasks_async(request_type=dict) +async def test_update_task_async_from_dict(): + await test_update_task_async(request_type=dict) -def test_search_tasks_routing_parameters(): +def test_update_task_routing_parameters(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = delivery_api.SearchTasksRequest(**{"parent": "providers/sample1"}) + request = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: - call.return_value = delivery_api.SearchTasksResponse() - client.search_tasks(request) + with mock.patch.object(type(client.transport.update_task), "__call__") as call: + call.return_value = tasks.Task() + client.update_task(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2941,31 +3594,35 @@ def test_search_tasks_routing_parameters(): assert kw["metadata"] -def test_search_tasks_flattened(): +def test_update_task_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: + with mock.patch.object(type(client.transport.update_task), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = delivery_api.SearchTasksResponse() + call.return_value = tasks.Task() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.search_tasks( - parent="parent_value", + client.update_task( + task=tasks.Task(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].task + mock_val = tasks.Task(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_search_tasks_flattened_error(): +def test_update_task_flattened_error(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2973,43 +3630,46 @@ def test_search_tasks_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.search_tasks( - delivery_api.SearchTasksRequest(), - parent="parent_value", + client.update_task( + delivery_api.UpdateTaskRequest(), + task=tasks.Task(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_search_tasks_flattened_async(): +async def test_update_task_flattened_async(): client = DeliveryServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: + with mock.patch.object(type(client.transport.update_task), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = delivery_api.SearchTasksResponse() + call.return_value = tasks.Task() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - delivery_api.SearchTasksResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.search_tasks( - parent="parent_value", + response = await client.update_task( + task=tasks.Task(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" + arg = args[0].task + mock_val = tasks.Task(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_search_tasks_flattened_error_async(): +async def test_update_task_flattened_error_async(): client = DeliveryServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3017,289 +3677,139 @@ async def test_search_tasks_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.search_tasks( - delivery_api.SearchTasksRequest(), - parent="parent_value", + await client.update_task( + delivery_api.UpdateTaskRequest(), + task=tasks.Task(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_search_tasks_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + delivery_api.ListTasksRequest, + dict, + ], +) +def test_list_tasks(request_type, transport: str = "grpc"): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token="abc", - ), - delivery_api.SearchTasksResponse( - tasks=[], - next_page_token="def", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token="ghi", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = delivery_api.ListTasksResponse( + next_page_token="next_page_token_value", + total_size=1086, ) + response = client.list_tasks(request) - metadata = () - pager = client.search_tasks(request={}) - - assert pager._metadata == metadata + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = delivery_api.ListTasksRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tasks.Task) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTasksPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 -def test_search_tasks_pages(transport_name: str = "grpc"): +def test_list_tasks_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_tasks), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token="abc", - ), - delivery_api.SearchTasksResponse( - tasks=[], - next_page_token="def", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token="ghi", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - pages = list(client.search_tasks(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + client.list_tasks() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.ListTasksRequest() -@pytest.mark.asyncio -async def test_search_tasks_async_pager(): - client = DeliveryServiceAsyncClient( +def test_list_tasks_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = delivery_api.ListTasksRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_tasks), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token="abc", - ), - delivery_api.SearchTasksResponse( - tasks=[], - next_page_token="def", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token="ghi", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - async_pager = await client.search_tasks( - request={}, + client.list_tasks(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == delivery_api.ListTasksRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, tasks.Task) for i in responses) - -@pytest.mark.asyncio -async def test_search_tasks_async_pages(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_tasks), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token="abc", - ), - delivery_api.SearchTasksResponse( - tasks=[], - next_page_token="def", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token="ghi", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - RuntimeError, +def test_list_tasks_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.search_tasks(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -@pytest.mark.parametrize( - "request_type", - [ - delivery_api.UpdateTaskRequest, - dict, - ], -) -def test_update_task(request_type, transport: str = "grpc"): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + # Ensure method has been cached + assert client._transport.list_tasks in client._transport._wrapped_methods - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task( - name="name_value", - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id="tracking_id_value", - delivery_vehicle_id="delivery_vehicle_id_value", + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - response = client.update_task(request) + client._transport._wrapped_methods[client._transport.list_tasks] = mock_rpc + request = {} + client.list_tasks(request) # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateTaskRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == "name_value" - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert ( - response.task_outcome_location_source - == tasks.Task.TaskOutcomeLocationSource.PROVIDER - ) - assert response.tracking_id == "tracking_id_value" - assert response.delivery_vehicle_id == "delivery_vehicle_id_value" - - -def test_update_task_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: - client.update_task() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest() + assert mock_rpc.call_count == 1 + client.list_tasks(request) -def test_update_task_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.UpdateTaskRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: - client.update_task(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest() + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 @pytest.mark.asyncio -async def test_update_task_empty_call_async(): +async def test_list_tasks_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = DeliveryServiceAsyncClient( @@ -3308,28 +3818,67 @@ async def test_update_task_empty_call_async(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tasks.Task( - name="name_value", - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id="tracking_id_value", - delivery_vehicle_id="delivery_vehicle_id_value", + delivery_api.ListTasksResponse( + next_page_token="next_page_token_value", + total_size=1086, ) ) - response = await client.update_task() + response = await client.list_tasks() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.UpdateTaskRequest() + assert args[0] == delivery_api.ListTasksRequest() @pytest.mark.asyncio -async def test_update_task_async( - transport: str = "grpc_asyncio", request_type=delivery_api.UpdateTaskRequest +async def test_list_tasks_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_tasks + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_tasks + ] = mock_object + + request = {} + await client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_tasks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_tasks_async( + transport: str = "grpc_asyncio", request_type=delivery_api.ListTasksRequest ): client = DeliveryServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3341,59 +3890,46 @@ async def test_update_task_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - tasks.Task( - name="name_value", - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id="tracking_id_value", - delivery_vehicle_id="delivery_vehicle_id_value", + delivery_api.ListTasksResponse( + next_page_token="next_page_token_value", + total_size=1086, ) ) - response = await client.update_task(request) + response = await client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = delivery_api.UpdateTaskRequest() + request = delivery_api.ListTasksRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == "name_value" - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert ( - response.task_outcome_location_source - == tasks.Task.TaskOutcomeLocationSource.PROVIDER - ) - assert response.tracking_id == "tracking_id_value" - assert response.delivery_vehicle_id == "delivery_vehicle_id_value" + assert isinstance(response, pagers.ListTasksAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 @pytest.mark.asyncio -async def test_update_task_async_from_dict(): - await test_update_task_async(request_type=dict) +async def test_list_tasks_async_from_dict(): + await test_list_tasks_async(request_type=dict) -def test_update_task_routing_parameters(): +def test_list_tasks_routing_parameters(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = delivery_api.UpdateTaskRequest(**{"task": {"name": "providers/sample1"}}) + request = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: - call.return_value = tasks.Task() - client.update_task(request) + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: + call.return_value = delivery_api.ListTasksResponse() + client.list_tasks(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3405,293 +3941,31 @@ def test_update_task_routing_parameters(): assert kw["metadata"] -def test_update_task_flattened(): +def test_list_tasks_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: + with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = tasks.Task() + call.return_value = delivery_api.ListTasksResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_task( - task=tasks.Task(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_tasks( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].task - mock_val = tasks.Task(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_update_task_flattened_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_task_flattened_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_task), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = tasks.Task() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(tasks.Task()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_task( - task=tasks.Task(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].task - mock_val = tasks.Task(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_task_flattened_error_async(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_task( - delivery_api.UpdateTaskRequest(), - task=tasks.Task(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - delivery_api.ListTasksRequest, - dict, - ], -) -def test_list_tasks(request_type, transport: str = "grpc"): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - response = client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = delivery_api.ListTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 - - -def test_list_tasks_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - client.list_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest() - - -def test_list_tasks_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = delivery_api.ListTasksRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - client.list_tasks(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - ) - - -@pytest.mark.asyncio -async def test_list_tasks_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - delivery_api.ListTasksResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - ) - response = await client.list_tasks() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == delivery_api.ListTasksRequest() - - -@pytest.mark.asyncio -async def test_list_tasks_async( - transport: str = "grpc_asyncio", request_type=delivery_api.ListTasksRequest -): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - delivery_api.ListTasksResponse( - next_page_token="next_page_token_value", - total_size=1086, - ) - ) - response = await client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = delivery_api.ListTasksRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListTasksAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 - - -@pytest.mark.asyncio -async def test_list_tasks_async_from_dict(): - await test_list_tasks_async(request_type=dict) - - -def test_list_tasks_routing_parameters(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = delivery_api.ListTasksRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - call.return_value = delivery_api.ListTasksResponse() - client.list_tasks(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - -def test_list_tasks_flattened(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_tasks), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = delivery_api.ListTasksResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_tasks( - parent="parent_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - - -def test_list_tasks_flattened_error(): +def test_list_tasks_flattened_error(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3992,6 +4266,9 @@ def test_get_task_tracking_info_empty_call(): with mock.patch.object( type(client.transport.get_task_tracking_info), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_task_tracking_info() call.assert_called() _, args, _ = call.mock_calls[0] @@ -4017,6 +4294,9 @@ def test_get_task_tracking_info_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.get_task_tracking_info), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_task_tracking_info(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -4025,6 +4305,46 @@ def test_get_task_tracking_info_non_empty_request_with_auto_populated_field(): ) +def test_get_task_tracking_info_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_task_tracking_info + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_task_tracking_info + ] = mock_rpc + request = {} + client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task_tracking_info(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_get_task_tracking_info_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -4053,6 +4373,52 @@ async def test_get_task_tracking_info_empty_call_async(): assert args[0] == delivery_api.GetTaskTrackingInfoRequest() +@pytest.mark.asyncio +async def test_get_task_tracking_info_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_task_tracking_info + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_task_tracking_info + ] = mock_object + + request = {} + await client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_task_tracking_info(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_get_task_tracking_info_async( transport: str = "grpc_asyncio", @@ -4265,6 +4631,9 @@ def test_list_delivery_vehicles_empty_call(): with mock.patch.object( type(client.transport.list_delivery_vehicles), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_delivery_vehicles() call.assert_called() _, args, _ = call.mock_calls[0] @@ -4292,6 +4661,9 @@ def test_list_delivery_vehicles_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.list_delivery_vehicles), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_delivery_vehicles(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -4302,6 +4674,46 @@ def test_list_delivery_vehicles_non_empty_request_with_auto_populated_field(): ) +def test_list_delivery_vehicles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_delivery_vehicles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_delivery_vehicles + ] = mock_rpc + request = {} + client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_delivery_vehicles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_list_delivery_vehicles_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -4328,6 +4740,52 @@ async def test_list_delivery_vehicles_empty_call_async(): assert args[0] == delivery_api.ListDeliveryVehiclesRequest() +@pytest.mark.asyncio +async def test_list_delivery_vehicles_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_delivery_vehicles + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_delivery_vehicles + ] = mock_object + + request = {} + await client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_delivery_vehicles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_list_delivery_vehicles_async( transport: str = "grpc_asyncio", @@ -4619,531 +5077,218 @@ async def test_list_delivery_vehicles_async_pager(): RuntimeError, ) async_pager = await client.list_delivery_vehicles( - request={}, - ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) - - assert len(responses) == 6 - assert all(isinstance(i, delivery_vehicles.DeliveryVehicle) for i in responses) - - -@pytest.mark.asyncio -async def test_list_delivery_vehicles_async_pages(): - client = DeliveryServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_delivery_vehicles), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token="abc", - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[], - next_page_token="def", - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - ], - next_page_token="ghi", - ), - delivery_api.ListDeliveryVehiclesResponse( - delivery_vehicles=[ - delivery_vehicles.DeliveryVehicle(), - delivery_vehicles.DeliveryVehicle(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_delivery_vehicles(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - delivery_api.CreateDeliveryVehicleRequest, - dict, - ], -) -def test_create_delivery_vehicle_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} - request_init["delivery_vehicle"] = { - "name": "name_value", - "last_location": { - "location": {"latitude": 0.86, "longitude": 0.971}, - "horizontal_accuracy": {"value": 0.541}, - "latlng_accuracy": {}, - "heading": {"value": 541}, - "bearing_accuracy": {}, - "heading_accuracy": {}, - "altitude": {}, - "vertical_accuracy": {}, - "altitude_accuracy": {}, - "speed_kmph": {}, - "speed": {}, - "speed_accuracy": {}, - "update_time": {"seconds": 751, "nanos": 543}, - "server_time": {}, - "location_sensor": 1, - "is_road_snapped": {"value": True}, - "is_gps_sensor_enabled": {}, - "time_since_update": {}, - "num_stale_updates": {}, - "raw_location": {}, - "raw_location_time": {}, - "raw_location_sensor": 1, - "raw_location_accuracy": {}, - "supplemental_location": {}, - "supplemental_location_time": {}, - "supplemental_location_sensor": 1, - "supplemental_location_accuracy": {}, - "road_snapped": True, - }, - "navigation_status": 1, - "current_route_segment": b"current_route_segment_blob", - "current_route_segment_end_point": {}, - "remaining_distance_meters": {}, - "remaining_duration": {"seconds": 751, "nanos": 543}, - "remaining_vehicle_journey_segments": [ - { - "stop": { - "planned_location": {"point": {}}, - "tasks": [ - { - "task_id": "task_id_value", - "task_duration": {}, - "target_time_window": {"start_time": {}, "end_time": {}}, - } - ], - "state": 1, - }, - "driving_distance_meters": {}, - "driving_duration": {}, - "path": {}, - } - ], - "attributes": [ - { - "key": "key_value", - "value": "value_value", - "string_value": "string_value_value", - "bool_value": True, - "number_value": 0.1285, - } - ], - "type_": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.CreateDeliveryVehicleRequest.meta.fields[ - "delivery_vehicle" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["delivery_vehicle"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["delivery_vehicle"][field])): - del request_init["delivery_vehicle"][field][i][subfield] - else: - del request_init["delivery_vehicle"][field][subfield] - 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 = delivery_vehicles.DeliveryVehicle( - name="name_value", - navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, - current_route_segment=b"current_route_segment_blob", - type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, - ) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.create_delivery_vehicle(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_vehicles.DeliveryVehicle) - assert response.name == "name_value" - assert ( - response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE - ) - assert response.current_route_segment == b"current_route_segment_blob" - assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO - - -def test_create_delivery_vehicle_rest_required_fields( - request_type=delivery_api.CreateDeliveryVehicleRequest, -): - transport_class = transports.DeliveryServiceRestTransport - - request_init = {} - request_init["parent"] = "" - request_init["delivery_vehicle_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - assert "deliveryVehicleId" not in jsonified_request - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_delivery_vehicle._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - assert "deliveryVehicleId" in jsonified_request - assert jsonified_request["deliveryVehicleId"] == request_init["delivery_vehicle_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["deliveryVehicleId"] = "delivery_vehicle_id_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_delivery_vehicle._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "delivery_vehicle_id", - "header", - ) - ) - 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" - assert "deliveryVehicleId" in jsonified_request - assert jsonified_request["deliveryVehicleId"] == "delivery_vehicle_id_value" - - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = delivery_vehicles.DeliveryVehicle() - # 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 - - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - response = client.create_delivery_vehicle(request) - - expected_params = [ - ( - "deliveryVehicleId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert expected_params == actual_params - - -def test_create_delivery_vehicle_rest_unset_required_fields(): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.create_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "deliveryVehicleId", - "header", - ) - ) - & set( - ( - "parent", - "deliveryVehicleId", - "deliveryVehicle", - ) - ) - ) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_delivery_vehicle_rest_interceptors(null_interceptor): - transport = transports.DeliveryServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.DeliveryServiceRestInterceptor(), - ) - client = DeliveryServiceClient(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.DeliveryServiceRestInterceptor, "post_create_delivery_vehicle" - ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_create_delivery_vehicle" - ) as pre: - pre.assert_not_called() - post.assert_not_called() - pb_message = delivery_api.CreateDeliveryVehicleRequest.pb( - delivery_api.CreateDeliveryVehicleRequest() - ) - 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 = delivery_vehicles.DeliveryVehicle.to_json( - delivery_vehicles.DeliveryVehicle() - ) - - request = delivery_api.CreateDeliveryVehicleRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = delivery_vehicles.DeliveryVehicle() - - client.create_delivery_vehicle( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - - -def test_create_delivery_vehicle_rest_bad_request( - transport: str = "rest", request_type=delivery_api.CreateDeliveryVehicleRequest -): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.create_delivery_vehicle(request) - - -def test_create_delivery_vehicle_rest_flattened(): - client = DeliveryServiceClient( - 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 = delivery_vehicles.DeliveryVehicle() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "providers/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), - delivery_vehicle_id="delivery_vehicle_id_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_delivery_vehicle(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=providers/*}/deliveryVehicles" % client.transport._host, - args[1], - ) - - -def test_create_delivery_vehicle_rest_flattened_error(transport: str = "rest"): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_delivery_vehicle( - delivery_api.CreateDeliveryVehicleRequest(), - parent="parent_value", - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), - delivery_vehicle_id="delivery_vehicle_id_value", + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + assert len(responses) == 6 + assert all(isinstance(i, delivery_vehicles.DeliveryVehicle) for i in responses) -def test_create_delivery_vehicle_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + +@pytest.mark.asyncio +async def test_list_delivery_vehicles_async_pages(): + client = DeliveryServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_delivery_vehicles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token="abc", + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[], + next_page_token="def", + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + ], + next_page_token="ghi", + ), + delivery_api.ListDeliveryVehiclesResponse( + delivery_vehicles=[ + delivery_vehicles.DeliveryVehicle(), + delivery_vehicles.DeliveryVehicle(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_delivery_vehicles(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - delivery_api.GetDeliveryVehicleRequest, + delivery_api.CreateDeliveryVehicleRequest, dict, ], ) -def test_get_delivery_vehicle_rest(request_type): +def test_create_delivery_vehicle_rest(request_type): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "providers/sample1/deliveryVehicles/sample2"} + request_init = {"parent": "providers/sample1"} + request_init["delivery_vehicle"] = { + "name": "name_value", + "last_location": { + "location": {"latitude": 0.86, "longitude": 0.971}, + "horizontal_accuracy": {"value": 0.541}, + "latlng_accuracy": {}, + "heading": {"value": 541}, + "bearing_accuracy": {}, + "heading_accuracy": {}, + "altitude": {}, + "vertical_accuracy": {}, + "altitude_accuracy": {}, + "speed_kmph": {}, + "speed": {}, + "speed_accuracy": {}, + "update_time": {"seconds": 751, "nanos": 543}, + "server_time": {}, + "location_sensor": 1, + "is_road_snapped": {"value": True}, + "is_gps_sensor_enabled": {}, + "time_since_update": {}, + "num_stale_updates": {}, + "raw_location": {}, + "raw_location_time": {}, + "raw_location_sensor": 1, + "raw_location_accuracy": {}, + "supplemental_location": {}, + "supplemental_location_time": {}, + "supplemental_location_sensor": 1, + "supplemental_location_accuracy": {}, + "road_snapped": True, + }, + "navigation_status": 1, + "current_route_segment": b"current_route_segment_blob", + "current_route_segment_end_point": {}, + "remaining_distance_meters": {}, + "remaining_duration": {"seconds": 751, "nanos": 543}, + "remaining_vehicle_journey_segments": [ + { + "stop": { + "planned_location": {"point": {}}, + "tasks": [ + { + "task_id": "task_id_value", + "task_duration": {}, + "target_time_window": {"start_time": {}, "end_time": {}}, + } + ], + "state": 1, + }, + "driving_distance_meters": {}, + "driving_duration": {}, + "path": {}, + } + ], + "attributes": [ + { + "key": "key_value", + "value": "value_value", + "string_value": "string_value_value", + "bool_value": True, + "number_value": 0.1285, + } + ], + "type_": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = delivery_api.CreateDeliveryVehicleRequest.meta.fields[ + "delivery_vehicle" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["delivery_vehicle"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["delivery_vehicle"][field])): + del request_init["delivery_vehicle"][field][i][subfield] + else: + del request_init["delivery_vehicle"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -5165,7 +5310,7 @@ def test_get_delivery_vehicle_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_delivery_vehicle(request) + response = client.create_delivery_vehicle(request) # Establish that the response is the type that we expect. assert isinstance(response, delivery_vehicles.DeliveryVehicle) @@ -5177,13 +5322,55 @@ def test_get_delivery_vehicle_rest(request_type): assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO -def test_get_delivery_vehicle_rest_required_fields( - request_type=delivery_api.GetDeliveryVehicleRequest, +def test_create_delivery_vehicle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.create_delivery_vehicle + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.create_delivery_vehicle + ] = mock_rpc + + request = {} + client.create_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_delivery_vehicle_rest_required_fields( + request_type=delivery_api.CreateDeliveryVehicleRequest, ): transport_class = transports.DeliveryServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["delivery_vehicle_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5191,26 +5378,37 @@ def test_get_delivery_vehicle_rest_required_fields( ) # verify fields with default values are dropped + assert "deliveryVehicleId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_delivery_vehicle._get_unset_required_fields(jsonified_request) + ).create_delivery_vehicle._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "deliveryVehicleId" in jsonified_request + assert jsonified_request["deliveryVehicleId"] == request_init["delivery_vehicle_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["deliveryVehicleId"] = "delivery_vehicle_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_delivery_vehicle._get_unset_required_fields(jsonified_request) + ).create_delivery_vehicle._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header",)) + assert not set(unset_fields) - set( + ( + "delivery_vehicle_id", + "header", + ) + ) 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" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "deliveryVehicleId" in jsonified_request + assert jsonified_request["deliveryVehicleId"] == "delivery_vehicle_id_value" client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5231,9 +5429,10 @@ def test_get_delivery_vehicle_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -5246,24 +5445,44 @@ def test_get_delivery_vehicle_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_delivery_vehicle(request) + response = client.create_delivery_vehicle(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "deliveryVehicleId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_delivery_vehicle_rest_unset_required_fields(): +def test_create_delivery_vehicle_rest_unset_required_fields(): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header",)) & set(("name",))) + unset_fields = transport.create_delivery_vehicle._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "deliveryVehicleId", + "header", + ) + ) + & set( + ( + "parent", + "deliveryVehicleId", + "deliveryVehicle", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_delivery_vehicle_rest_interceptors(null_interceptor): +def test_create_delivery_vehicle_rest_interceptors(null_interceptor): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5276,14 +5495,14 @@ def test_get_delivery_vehicle_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "post_get_delivery_vehicle" + transports.DeliveryServiceRestInterceptor, "post_create_delivery_vehicle" ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_get_delivery_vehicle" + transports.DeliveryServiceRestInterceptor, "pre_create_delivery_vehicle" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = delivery_api.GetDeliveryVehicleRequest.pb( - delivery_api.GetDeliveryVehicleRequest() + pb_message = delivery_api.CreateDeliveryVehicleRequest.pb( + delivery_api.CreateDeliveryVehicleRequest() ) transcode.return_value = { "method": "post", @@ -5299,7 +5518,7 @@ def test_get_delivery_vehicle_rest_interceptors(null_interceptor): delivery_vehicles.DeliveryVehicle() ) - request = delivery_api.GetDeliveryVehicleRequest() + request = delivery_api.CreateDeliveryVehicleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -5307,7 +5526,7 @@ def test_get_delivery_vehicle_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = delivery_vehicles.DeliveryVehicle() - client.get_delivery_vehicle( + client.create_delivery_vehicle( request, metadata=[ ("key", "val"), @@ -5319,8 +5538,8 @@ def test_get_delivery_vehicle_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_delivery_vehicle_rest_bad_request( - transport: str = "rest", request_type=delivery_api.GetDeliveryVehicleRequest +def test_create_delivery_vehicle_rest_bad_request( + transport: str = "rest", request_type=delivery_api.CreateDeliveryVehicleRequest ): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5328,7 +5547,7 @@ def test_get_delivery_vehicle_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "providers/sample1/deliveryVehicles/sample2"} + request_init = {"parent": "providers/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5340,10 +5559,10 @@ def test_get_delivery_vehicle_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_delivery_vehicle(request) + client.create_delivery_vehicle(request) -def test_get_delivery_vehicle_rest_flattened(): +def test_create_delivery_vehicle_rest_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5355,11 +5574,13 @@ def test_get_delivery_vehicle_rest_flattened(): return_value = delivery_vehicles.DeliveryVehicle() # get arguments that satisfy an http rule for this method - sample_request = {"name": "providers/sample1/deliveryVehicles/sample2"} + sample_request = {"parent": "providers/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), + delivery_vehicle_id="delivery_vehicle_id_value", ) mock_args.update(sample_request) @@ -5372,19 +5593,19 @@ def test_get_delivery_vehicle_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_delivery_vehicle(**mock_args) + client.create_delivery_vehicle(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=providers/*/deliveryVehicles/*}" % client.transport._host, + "%s/v1/{parent=providers/*}/deliveryVehicles" % client.transport._host, args[1], ) -def test_get_delivery_vehicle_rest_flattened_error(transport: str = "rest"): +def test_create_delivery_vehicle_rest_flattened_error(transport: str = "rest"): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5393,13 +5614,15 @@ def test_get_delivery_vehicle_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_delivery_vehicle( - delivery_api.GetDeliveryVehicleRequest(), - name="name_value", + client.create_delivery_vehicle( + delivery_api.CreateDeliveryVehicleRequest(), + parent="parent_value", + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), + delivery_vehicle_id="delivery_vehicle_id_value", ) -def test_get_delivery_vehicle_rest_error(): +def test_create_delivery_vehicle_rest_error(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5408,155 +5631,18 @@ def test_get_delivery_vehicle_rest_error(): @pytest.mark.parametrize( "request_type", [ - delivery_api.UpdateDeliveryVehicleRequest, + delivery_api.GetDeliveryVehicleRequest, dict, ], ) -def test_update_delivery_vehicle_rest(request_type): +def test_get_delivery_vehicle_rest(request_type): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "delivery_vehicle": {"name": "providers/sample1/deliveryVehicles/sample2"} - } - request_init["delivery_vehicle"] = { - "name": "providers/sample1/deliveryVehicles/sample2", - "last_location": { - "location": {"latitude": 0.86, "longitude": 0.971}, - "horizontal_accuracy": {"value": 0.541}, - "latlng_accuracy": {}, - "heading": {"value": 541}, - "bearing_accuracy": {}, - "heading_accuracy": {}, - "altitude": {}, - "vertical_accuracy": {}, - "altitude_accuracy": {}, - "speed_kmph": {}, - "speed": {}, - "speed_accuracy": {}, - "update_time": {"seconds": 751, "nanos": 543}, - "server_time": {}, - "location_sensor": 1, - "is_road_snapped": {"value": True}, - "is_gps_sensor_enabled": {}, - "time_since_update": {}, - "num_stale_updates": {}, - "raw_location": {}, - "raw_location_time": {}, - "raw_location_sensor": 1, - "raw_location_accuracy": {}, - "supplemental_location": {}, - "supplemental_location_time": {}, - "supplemental_location_sensor": 1, - "supplemental_location_accuracy": {}, - "road_snapped": True, - }, - "navigation_status": 1, - "current_route_segment": b"current_route_segment_blob", - "current_route_segment_end_point": {}, - "remaining_distance_meters": {}, - "remaining_duration": {"seconds": 751, "nanos": 543}, - "remaining_vehicle_journey_segments": [ - { - "stop": { - "planned_location": {"point": {}}, - "tasks": [ - { - "task_id": "task_id_value", - "task_duration": {}, - "target_time_window": {"start_time": {}, "end_time": {}}, - } - ], - "state": 1, - }, - "driving_distance_meters": {}, - "driving_duration": {}, - "path": {}, - } - ], - "attributes": [ - { - "key": "key_value", - "value": "value_value", - "string_value": "string_value_value", - "bool_value": True, - "number_value": 0.1285, - } - ], - "type_": 1, - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.UpdateDeliveryVehicleRequest.meta.fields[ - "delivery_vehicle" - ] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["delivery_vehicle"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["delivery_vehicle"][field])): - del request_init["delivery_vehicle"][field][i][subfield] - else: - del request_init["delivery_vehicle"][field][subfield] + request_init = {"name": "providers/sample1/deliveryVehicles/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -5578,7 +5664,7 @@ def get_message_fields(field): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_delivery_vehicle(request) + response = client.get_delivery_vehicle(request) # Establish that the response is the type that we expect. assert isinstance(response, delivery_vehicles.DeliveryVehicle) @@ -5590,12 +5676,53 @@ def get_message_fields(field): assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO -def test_update_delivery_vehicle_rest_required_fields( - request_type=delivery_api.UpdateDeliveryVehicleRequest, +def test_get_delivery_vehicle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_delivery_vehicle in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_delivery_vehicle + ] = mock_rpc + + request = {} + client.get_delivery_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_delivery_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_delivery_vehicle_rest_required_fields( + request_type=delivery_api.GetDeliveryVehicleRequest, ): transport_class = transports.DeliveryServiceRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5606,24 +5733,23 @@ def test_update_delivery_vehicle_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_delivery_vehicle._get_unset_required_fields(jsonified_request) + ).get_delivery_vehicle._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_delivery_vehicle._get_unset_required_fields(jsonified_request) + ).get_delivery_vehicle._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "header", - "update_mask", - ) - ) + assert not set(unset_fields) - set(("header",)) 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 = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5644,10 +5770,9 @@ def test_update_delivery_vehicle_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -5660,37 +5785,24 @@ def test_update_delivery_vehicle_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_delivery_vehicle(request) + response = client.get_delivery_vehicle(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_delivery_vehicle_rest_unset_required_fields(): +def test_get_delivery_vehicle_rest_unset_required_fields(): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_delivery_vehicle._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "header", - "updateMask", - ) - ) - & set( - ( - "deliveryVehicle", - "updateMask", - ) - ) - ) + unset_fields = transport.get_delivery_vehicle._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_delivery_vehicle_rest_interceptors(null_interceptor): +def test_get_delivery_vehicle_rest_interceptors(null_interceptor): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5703,14 +5815,14 @@ def test_update_delivery_vehicle_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "post_update_delivery_vehicle" + transports.DeliveryServiceRestInterceptor, "post_get_delivery_vehicle" ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_update_delivery_vehicle" + transports.DeliveryServiceRestInterceptor, "pre_get_delivery_vehicle" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = delivery_api.UpdateDeliveryVehicleRequest.pb( - delivery_api.UpdateDeliveryVehicleRequest() + pb_message = delivery_api.GetDeliveryVehicleRequest.pb( + delivery_api.GetDeliveryVehicleRequest() ) transcode.return_value = { "method": "post", @@ -5726,7 +5838,7 @@ def test_update_delivery_vehicle_rest_interceptors(null_interceptor): delivery_vehicles.DeliveryVehicle() ) - request = delivery_api.UpdateDeliveryVehicleRequest() + request = delivery_api.GetDeliveryVehicleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -5734,7 +5846,7 @@ def test_update_delivery_vehicle_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = delivery_vehicles.DeliveryVehicle() - client.update_delivery_vehicle( + client.get_delivery_vehicle( request, metadata=[ ("key", "val"), @@ -5746,8 +5858,8 @@ def test_update_delivery_vehicle_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_delivery_vehicle_rest_bad_request( - transport: str = "rest", request_type=delivery_api.UpdateDeliveryVehicleRequest +def test_get_delivery_vehicle_rest_bad_request( + transport: str = "rest", request_type=delivery_api.GetDeliveryVehicleRequest ): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5755,9 +5867,7 @@ def test_update_delivery_vehicle_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "delivery_vehicle": {"name": "providers/sample1/deliveryVehicles/sample2"} - } + request_init = {"name": "providers/sample1/deliveryVehicles/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5769,10 +5879,10 @@ def test_update_delivery_vehicle_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_delivery_vehicle(request) + client.get_delivery_vehicle(request) -def test_update_delivery_vehicle_rest_flattened(): +def test_get_delivery_vehicle_rest_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5784,14 +5894,11 @@ def test_update_delivery_vehicle_rest_flattened(): return_value = delivery_vehicles.DeliveryVehicle() # get arguments that satisfy an http rule for this method - sample_request = { - "delivery_vehicle": {"name": "providers/sample1/deliveryVehicles/sample2"} - } + sample_request = {"name": "providers/sample1/deliveryVehicles/sample2"} # get truthy value for each flattened field mock_args = dict( - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -5804,20 +5911,19 @@ def test_update_delivery_vehicle_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_delivery_vehicle(**mock_args) + client.get_delivery_vehicle(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{delivery_vehicle.name=providers/*/deliveryVehicles/*}" - % client.transport._host, + "%s/v1/{name=providers/*/deliveryVehicles/*}" % client.transport._host, args[1], ) -def test_update_delivery_vehicle_rest_flattened_error(transport: str = "rest"): +def test_get_delivery_vehicle_rest_flattened_error(transport: str = "rest"): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5826,14 +5932,13 @@ def test_update_delivery_vehicle_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_delivery_vehicle( - delivery_api.UpdateDeliveryVehicleRequest(), - delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_delivery_vehicle( + delivery_api.GetDeliveryVehicleRequest(), + name="name_value", ) -def test_update_delivery_vehicle_rest_error(): +def test_get_delivery_vehicle_rest_error(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -5842,47 +5947,235 @@ def test_update_delivery_vehicle_rest_error(): @pytest.mark.parametrize( "request_type", [ - delivery_api.BatchCreateTasksRequest, + delivery_api.UpdateDeliveryVehicleRequest, dict, ], ) -def test_batch_create_tasks_rest(request_type): +def test_update_delivery_vehicle_rest(request_type): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} + request_init = { + "delivery_vehicle": {"name": "providers/sample1/deliveryVehicles/sample2"} + } + request_init["delivery_vehicle"] = { + "name": "providers/sample1/deliveryVehicles/sample2", + "last_location": { + "location": {"latitude": 0.86, "longitude": 0.971}, + "horizontal_accuracy": {"value": 0.541}, + "latlng_accuracy": {}, + "heading": {"value": 541}, + "bearing_accuracy": {}, + "heading_accuracy": {}, + "altitude": {}, + "vertical_accuracy": {}, + "altitude_accuracy": {}, + "speed_kmph": {}, + "speed": {}, + "speed_accuracy": {}, + "update_time": {"seconds": 751, "nanos": 543}, + "server_time": {}, + "location_sensor": 1, + "is_road_snapped": {"value": True}, + "is_gps_sensor_enabled": {}, + "time_since_update": {}, + "num_stale_updates": {}, + "raw_location": {}, + "raw_location_time": {}, + "raw_location_sensor": 1, + "raw_location_accuracy": {}, + "supplemental_location": {}, + "supplemental_location_time": {}, + "supplemental_location_sensor": 1, + "supplemental_location_accuracy": {}, + "road_snapped": True, + }, + "navigation_status": 1, + "current_route_segment": b"current_route_segment_blob", + "current_route_segment_end_point": {}, + "remaining_distance_meters": {}, + "remaining_duration": {"seconds": 751, "nanos": 543}, + "remaining_vehicle_journey_segments": [ + { + "stop": { + "planned_location": {"point": {}}, + "tasks": [ + { + "task_id": "task_id_value", + "task_duration": {}, + "target_time_window": {"start_time": {}, "end_time": {}}, + } + ], + "state": 1, + }, + "driving_distance_meters": {}, + "driving_duration": {}, + "path": {}, + } + ], + "attributes": [ + { + "key": "key_value", + "value": "value_value", + "string_value": "string_value_value", + "bool_value": True, + "number_value": 0.1285, + } + ], + "type_": 1, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = delivery_api.UpdateDeliveryVehicleRequest.meta.fields[ + "delivery_vehicle" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["delivery_vehicle"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["delivery_vehicle"][field])): + del request_init["delivery_vehicle"][field][i][subfield] + else: + del request_init["delivery_vehicle"][field][subfield] 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 = delivery_api.BatchCreateTasksResponse() + return_value = delivery_vehicles.DeliveryVehicle( + name="name_value", + navigation_status=common.DeliveryVehicleNavigationStatus.NO_GUIDANCE, + current_route_segment=b"current_route_segment_blob", + type_=delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) + 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_delivery_vehicle(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, delivery_vehicles.DeliveryVehicle) + assert response.name == "name_value" + assert ( + response.navigation_status == common.DeliveryVehicleNavigationStatus.NO_GUIDANCE + ) + assert response.current_route_segment == b"current_route_segment_blob" + assert response.type_ == delivery_vehicles.DeliveryVehicle.DeliveryVehicleType.AUTO + + +def test_update_delivery_vehicle_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_delivery_vehicle + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_delivery_vehicle + ] = mock_rpc + + request = {} + client.update_delivery_vehicle(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.batch_create_tasks(request) + client.update_delivery_vehicle(request) - # Establish that the response is the type that we expect. - assert isinstance(response, delivery_api.BatchCreateTasksResponse) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -def test_batch_create_tasks_rest_required_fields( - request_type=delivery_api.BatchCreateTasksRequest, +def test_update_delivery_vehicle_rest_required_fields( + request_type=delivery_api.UpdateDeliveryVehicleRequest, ): transport_class = transports.DeliveryServiceRestTransport request_init = {} - request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -5893,21 +6186,24 @@ def test_batch_create_tasks_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_tasks._get_unset_required_fields(jsonified_request) + ).update_delivery_vehicle._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() - ).batch_create_tasks._get_unset_required_fields(jsonified_request) + ).update_delivery_vehicle._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "header", + "update_mask", + ) + ) 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 = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -5916,7 +6212,7 @@ def test_batch_create_tasks_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = delivery_api.BatchCreateTasksResponse() + return_value = delivery_vehicles.DeliveryVehicle() # 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 @@ -5928,7 +6224,7 @@ def test_batch_create_tasks_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -5938,38 +6234,43 @@ def test_batch_create_tasks_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) + return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_tasks(request) + response = client.update_delivery_vehicle(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_create_tasks_rest_unset_required_fields(): +def test_update_delivery_vehicle_rest_unset_required_fields(): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_create_tasks._get_unset_required_fields({}) + unset_fields = transport.update_delivery_vehicle._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set( + ( + "header", + "updateMask", + ) + ) & set( ( - "parent", - "requests", + "deliveryVehicle", + "updateMask", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_tasks_rest_interceptors(null_interceptor): +def test_update_delivery_vehicle_rest_interceptors(null_interceptor): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5982,14 +6283,14 @@ def test_batch_create_tasks_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "post_batch_create_tasks" + transports.DeliveryServiceRestInterceptor, "post_update_delivery_vehicle" ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_batch_create_tasks" + transports.DeliveryServiceRestInterceptor, "pre_update_delivery_vehicle" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = delivery_api.BatchCreateTasksRequest.pb( - delivery_api.BatchCreateTasksRequest() + pb_message = delivery_api.UpdateDeliveryVehicleRequest.pb( + delivery_api.UpdateDeliveryVehicleRequest() ) transcode.return_value = { "method": "post", @@ -6001,19 +6302,19 @@ def test_batch_create_tasks_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = delivery_api.BatchCreateTasksResponse.to_json( - delivery_api.BatchCreateTasksResponse() + req.return_value._content = delivery_vehicles.DeliveryVehicle.to_json( + delivery_vehicles.DeliveryVehicle() ) - request = delivery_api.BatchCreateTasksRequest() + request = delivery_api.UpdateDeliveryVehicleRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = delivery_api.BatchCreateTasksResponse() + post.return_value = delivery_vehicles.DeliveryVehicle() - client.batch_create_tasks( + client.update_delivery_vehicle( request, metadata=[ ("key", "val"), @@ -6025,8 +6326,8 @@ def test_batch_create_tasks_rest_interceptors(null_interceptor): post.assert_called_once() -def test_batch_create_tasks_rest_bad_request( - transport: str = "rest", request_type=delivery_api.BatchCreateTasksRequest +def test_update_delivery_vehicle_rest_bad_request( + transport: str = "rest", request_type=delivery_api.UpdateDeliveryVehicleRequest ): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6034,7 +6335,9 @@ def test_batch_create_tasks_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} + request_init = { + "delivery_vehicle": {"name": "providers/sample1/deliveryVehicles/sample2"} + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6046,230 +6349,160 @@ def test_batch_create_tasks_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_create_tasks(request) - - -def test_batch_create_tasks_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + client.update_delivery_vehicle(request) -@pytest.mark.parametrize( - "request_type", - [ - delivery_api.CreateTaskRequest, - dict, - ], -) -def test_create_task_rest(request_type): +def test_update_delivery_vehicle_rest_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} - request_init["task"] = { - "name": "name_value", - "type_": 1, - "state": 1, - "task_outcome": 1, - "task_outcome_time": {"seconds": 751, "nanos": 543}, - "task_outcome_location": {"point": {"latitude": 0.86, "longitude": 0.971}}, - "task_outcome_location_source": 2, - "tracking_id": "tracking_id_value", - "delivery_vehicle_id": "delivery_vehicle_id_value", - "planned_location": {}, - "task_duration": {"seconds": 751, "nanos": 543}, - "target_time_window": {"start_time": {}, "end_time": {}}, - "journey_sharing_info": { - "remaining_vehicle_journey_segments": [ - { - "stop": { - "planned_location": {}, - "tasks": [ - { - "task_id": "task_id_value", - "task_duration": {}, - "target_time_window": {}, - } - ], - "state": 1, - }, - "driving_distance_meters": {"value": 541}, - "driving_duration": {}, - "path": {}, - } - ], - "last_location": { - "location": {}, - "horizontal_accuracy": {"value": 0.541}, - "latlng_accuracy": {}, - "heading": {}, - "bearing_accuracy": {}, - "heading_accuracy": {}, - "altitude": {}, - "vertical_accuracy": {}, - "altitude_accuracy": {}, - "speed_kmph": {}, - "speed": {}, - "speed_accuracy": {}, - "update_time": {}, - "server_time": {}, - "location_sensor": 1, - "is_road_snapped": {"value": True}, - "is_gps_sensor_enabled": {}, - "time_since_update": {}, - "num_stale_updates": {}, - "raw_location": {}, - "raw_location_time": {}, - "raw_location_sensor": 1, - "raw_location_accuracy": {}, - "supplemental_location": {}, - "supplemental_location_time": {}, - "supplemental_location_sensor": 1, - "supplemental_location_accuracy": {}, - "road_snapped": True, - }, - "last_location_snappable": True, - }, - "task_tracking_view_config": { - "route_polyline_points_visibility": { - "remaining_stop_count_threshold": 3219, - "duration_until_estimated_arrival_time_threshold": {}, - "remaining_driving_distance_meters_threshold": 4561, - "always": True, - "never": True, - }, - "estimated_arrival_time_visibility": {}, - "estimated_task_completion_time_visibility": {}, - "remaining_driving_distance_visibility": {}, - "remaining_stop_count_visibility": {}, - "vehicle_location_visibility": {}, - }, - "attributes": [ - { - "key": "key_value", - "string_value": "string_value_value", - "bool_value": True, - "number_value": 0.1285, - } - ], - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + # 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 = delivery_vehicles.DeliveryVehicle() - # Determine if the message type is proto-plus or protobuf - test_field = delivery_api.CreateTaskRequest.meta.fields["task"] + # get arguments that satisfy an http rule for this method + sample_request = { + "delivery_vehicle": {"name": "providers/sample1/deliveryVehicles/sample2"} + } - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # get truthy value for each flattened field + mock_args = dict( + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = delivery_vehicles.DeliveryVehicle.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + client.update_delivery_vehicle(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{delivery_vehicle.name=providers/*/deliveryVehicles/*}" + % client.transport._host, + args[1], + ) + + +def test_update_delivery_vehicle_rest_flattened_error(transport: str = "rest"): + client = DeliveryServiceClient( + 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_delivery_vehicle( + delivery_api.UpdateDeliveryVehicleRequest(), + delivery_vehicle=delivery_vehicles.DeliveryVehicle(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - subfields_not_in_runtime = [] +def test_update_delivery_vehicle_rest_error(): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["task"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) +@pytest.mark.parametrize( + "request_type", + [ + delivery_api.BatchCreateTasksRequest, + dict, + ], +) +def test_batch_create_tasks_rest(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["task"][field])): - del request_init["task"][field][i][subfield] - else: - del request_init["task"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"parent": "providers/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = tasks.Task( - name="name_value", - type_=tasks.Task.Type.PICKUP, - state=tasks.Task.State.OPEN, - task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, - task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, - tracking_id="tracking_id_value", - delivery_vehicle_id="delivery_vehicle_id_value", - ) + return_value = delivery_api.BatchCreateTasksResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) + return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_task(request) + response = client.batch_create_tasks(request) # Establish that the response is the type that we expect. - assert isinstance(response, tasks.Task) - assert response.name == "name_value" - assert response.type_ == tasks.Task.Type.PICKUP - assert response.state == tasks.Task.State.OPEN - assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED - assert ( - response.task_outcome_location_source - == tasks.Task.TaskOutcomeLocationSource.PROVIDER - ) - assert response.tracking_id == "tracking_id_value" - assert response.delivery_vehicle_id == "delivery_vehicle_id_value" + assert isinstance(response, delivery_api.BatchCreateTasksResponse) -def test_create_task_rest_required_fields(request_type=delivery_api.CreateTaskRequest): +def test_batch_create_tasks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_create_tasks in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_create_tasks + ] = mock_rpc + + request = {} + client.batch_create_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.batch_create_tasks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_create_tasks_rest_required_fields( + request_type=delivery_api.BatchCreateTasksRequest, +): transport_class = transports.DeliveryServiceRestTransport request_init = {} request_init["parent"] = "" - request_init["task_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6277,37 +6510,24 @@ def test_create_task_rest_required_fields(request_type=delivery_api.CreateTaskRe ) # verify fields with default values are dropped - assert "taskId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_task._get_unset_required_fields(jsonified_request) + ).batch_create_tasks._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "taskId" in jsonified_request - assert jsonified_request["taskId"] == request_init["task_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["taskId"] = "task_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_task._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "header", - "task_id", - ) - ) + ).batch_create_tasks._get_unset_required_fields(jsonified_request) 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" - assert "taskId" in jsonified_request - assert jsonified_request["taskId"] == "task_id_value" client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6316,7 +6536,7 @@ def test_create_task_rest_required_fields(request_type=delivery_api.CreateTaskRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = tasks.Task() + return_value = delivery_api.BatchCreateTasksResponse() # 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 @@ -6338,50 +6558,38 @@ def test_create_task_rest_required_fields(request_type=delivery_api.CreateTaskRe response_value.status_code = 200 # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) + return_value = delivery_api.BatchCreateTasksResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_task(request) + response = client.batch_create_tasks(request) - expected_params = [ - ( - "taskId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_task_rest_unset_required_fields(): +def test_batch_create_tasks_rest_unset_required_fields(): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_task._get_unset_required_fields({}) + unset_fields = transport.batch_create_tasks._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "header", - "taskId", - ) - ) + set(()) & set( ( "parent", - "taskId", - "task", + "requests", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_task_rest_interceptors(null_interceptor): +def test_batch_create_tasks_rest_interceptors(null_interceptor): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6394,13 +6602,15 @@ def test_create_task_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "post_create_task" + transports.DeliveryServiceRestInterceptor, "post_batch_create_tasks" ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_create_task" + transports.DeliveryServiceRestInterceptor, "pre_batch_create_tasks" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = delivery_api.CreateTaskRequest.pb(delivery_api.CreateTaskRequest()) + pb_message = delivery_api.BatchCreateTasksRequest.pb( + delivery_api.BatchCreateTasksRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6411,17 +6621,19 @@ def test_create_task_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = tasks.Task.to_json(tasks.Task()) + req.return_value._content = delivery_api.BatchCreateTasksResponse.to_json( + delivery_api.BatchCreateTasksResponse() + ) - request = delivery_api.CreateTaskRequest() + request = delivery_api.BatchCreateTasksRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = tasks.Task() + post.return_value = delivery_api.BatchCreateTasksResponse() - client.create_task( + client.batch_create_tasks( request, metadata=[ ("key", "val"), @@ -6433,8 +6645,8 @@ def test_create_task_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_task_rest_bad_request( - transport: str = "rest", request_type=delivery_api.CreateTaskRequest +def test_batch_create_tasks_rest_bad_request( + transport: str = "rest", request_type=delivery_api.BatchCreateTasksRequest ): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6454,89 +6666,184 @@ def test_create_task_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_task(request) + client.batch_create_tasks(request) -def test_create_task_rest_flattened(): +def test_batch_create_tasks_rest_error(): client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + 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 = tasks.Task() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "providers/sample1"} - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - task=tasks.Task(name="name_value"), - task_id="task_id_value", - ) - mock_args.update(sample_request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = tasks.Task.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value +@pytest.mark.parametrize( + "request_type", + [ + delivery_api.CreateTaskRequest, + dict, + ], +) +def test_create_task_rest(request_type): + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - client.create_task(**mock_args) + # send a request that will satisfy transcoding + request_init = {"parent": "providers/sample1"} + request_init["task"] = { + "name": "name_value", + "type_": 1, + "state": 1, + "task_outcome": 1, + "task_outcome_time": {"seconds": 751, "nanos": 543}, + "task_outcome_location": {"point": {"latitude": 0.86, "longitude": 0.971}}, + "task_outcome_location_source": 2, + "tracking_id": "tracking_id_value", + "delivery_vehicle_id": "delivery_vehicle_id_value", + "planned_location": {}, + "task_duration": {"seconds": 751, "nanos": 543}, + "target_time_window": {"start_time": {}, "end_time": {}}, + "journey_sharing_info": { + "remaining_vehicle_journey_segments": [ + { + "stop": { + "planned_location": {}, + "tasks": [ + { + "task_id": "task_id_value", + "task_duration": {}, + "target_time_window": {}, + } + ], + "state": 1, + }, + "driving_distance_meters": {"value": 541}, + "driving_duration": {}, + "path": {}, + } + ], + "last_location": { + "location": {}, + "horizontal_accuracy": {"value": 0.541}, + "latlng_accuracy": {}, + "heading": {}, + "bearing_accuracy": {}, + "heading_accuracy": {}, + "altitude": {}, + "vertical_accuracy": {}, + "altitude_accuracy": {}, + "speed_kmph": {}, + "speed": {}, + "speed_accuracy": {}, + "update_time": {}, + "server_time": {}, + "location_sensor": 1, + "is_road_snapped": {"value": True}, + "is_gps_sensor_enabled": {}, + "time_since_update": {}, + "num_stale_updates": {}, + "raw_location": {}, + "raw_location_time": {}, + "raw_location_sensor": 1, + "raw_location_accuracy": {}, + "supplemental_location": {}, + "supplemental_location_time": {}, + "supplemental_location_sensor": 1, + "supplemental_location_accuracy": {}, + "road_snapped": True, + }, + "last_location_snappable": True, + }, + "task_tracking_view_config": { + "route_polyline_points_visibility": { + "remaining_stop_count_threshold": 3219, + "duration_until_estimated_arrival_time_threshold": {}, + "remaining_driving_distance_meters_threshold": 4561, + "always": True, + "never": True, + }, + "estimated_arrival_time_visibility": {}, + "estimated_task_completion_time_visibility": {}, + "remaining_driving_distance_visibility": {}, + "remaining_stop_count_visibility": {}, + "vehicle_location_visibility": {}, + }, + "attributes": [ + { + "key": "key_value", + "string_value": "string_value_value", + "bool_value": True, + "number_value": 0.1285, + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=providers/*}/tasks" % client.transport._host, args[1] - ) + # Determine if the message type is proto-plus or protobuf + test_field = delivery_api.CreateTaskRequest.meta.fields["task"] + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] -def test_create_task_rest_flattened_error(transport: str = "rest"): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_task( - delivery_api.CreateTaskRequest(), - parent="parent_value", - task=tasks.Task(name="name_value"), - task_id="task_id_value", - ) + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] -def test_create_task_rest_error(): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["task"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - delivery_api.GetTaskRequest, - dict, - ], -) -def test_get_task_rest(request_type): - client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"name": "providers/sample1/tasks/sample2"} + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["task"][field])): + del request_init["task"][field][i][subfield] + else: + del request_init["task"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -6561,7 +6868,7 @@ def test_get_task_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_task(request) + response = client.create_task(request) # Establish that the response is the type that we expect. assert isinstance(response, tasks.Task) @@ -6577,11 +6884,48 @@ def test_get_task_rest(request_type): assert response.delivery_vehicle_id == "delivery_vehicle_id_value" -def test_get_task_rest_required_fields(request_type=delivery_api.GetTaskRequest): +def test_create_task_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_task] = mock_rpc + + request = {} + client.create_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_task_rest_required_fields(request_type=delivery_api.CreateTaskRequest): transport_class = transports.DeliveryServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["task_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6589,26 +6933,37 @@ def test_get_task_rest_required_fields(request_type=delivery_api.GetTaskRequest) ) # verify fields with default values are dropped + assert "taskId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_task._get_unset_required_fields(jsonified_request) + ).create_task._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "taskId" in jsonified_request + assert jsonified_request["taskId"] == request_init["task_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["taskId"] = "task_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_task._get_unset_required_fields(jsonified_request) + ).create_task._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("header",)) + assert not set(unset_fields) - set( + ( + "header", + "task_id", + ) + ) 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" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "taskId" in jsonified_request + assert jsonified_request["taskId"] == "task_id_value" client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6629,9 +6984,10 @@ def test_get_task_rest_required_fields(request_type=delivery_api.GetTaskRequest) pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -6644,24 +7000,44 @@ def test_get_task_rest_required_fields(request_type=delivery_api.GetTaskRequest) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_task(request) + response = client.create_task(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "taskId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_task_rest_unset_required_fields(): +def test_create_task_rest_unset_required_fields(): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_task._get_unset_required_fields({}) - assert set(unset_fields) == (set(("header",)) & set(("name",))) + unset_fields = transport.create_task._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "header", + "taskId", + ) + ) + & set( + ( + "parent", + "taskId", + "task", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_task_rest_interceptors(null_interceptor): +def test_create_task_rest_interceptors(null_interceptor): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6674,13 +7050,13 @@ def test_get_task_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "post_get_task" + transports.DeliveryServiceRestInterceptor, "post_create_task" ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_get_task" + transports.DeliveryServiceRestInterceptor, "pre_create_task" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = delivery_api.GetTaskRequest.pb(delivery_api.GetTaskRequest()) + pb_message = delivery_api.CreateTaskRequest.pb(delivery_api.CreateTaskRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6693,7 +7069,7 @@ def test_get_task_rest_interceptors(null_interceptor): req.return_value.request = PreparedRequest() req.return_value._content = tasks.Task.to_json(tasks.Task()) - request = delivery_api.GetTaskRequest() + request = delivery_api.CreateTaskRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -6701,7 +7077,7 @@ def test_get_task_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = tasks.Task() - client.get_task( + client.create_task( request, metadata=[ ("key", "val"), @@ -6713,8 +7089,8 @@ def test_get_task_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_task_rest_bad_request( - transport: str = "rest", request_type=delivery_api.GetTaskRequest +def test_create_task_rest_bad_request( + transport: str = "rest", request_type=delivery_api.CreateTaskRequest ): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6722,7 +7098,7 @@ def test_get_task_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "providers/sample1/tasks/sample2"} + request_init = {"parent": "providers/sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6734,10 +7110,10 @@ def test_get_task_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_task(request) + client.create_task(request) -def test_get_task_rest_flattened(): +def test_create_task_rest_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6749,11 +7125,13 @@ def test_get_task_rest_flattened(): return_value = tasks.Task() # get arguments that satisfy an http rule for this method - sample_request = {"name": "providers/sample1/tasks/sample2"} + sample_request = {"parent": "providers/sample1"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + task=tasks.Task(name="name_value"), + task_id="task_id_value", ) mock_args.update(sample_request) @@ -6766,18 +7144,18 @@ def test_get_task_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_task(**mock_args) + client.create_task(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=providers/*/tasks/*}" % client.transport._host, args[1] + "%s/v1/{parent=providers/*}/tasks" % client.transport._host, args[1] ) -def test_get_task_rest_flattened_error(transport: str = "rest"): +def test_create_task_rest_flattened_error(transport: str = "rest"): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6786,13 +7164,15 @@ def test_get_task_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_task( - delivery_api.GetTaskRequest(), - name="name_value", + client.create_task( + delivery_api.CreateTaskRequest(), + parent="parent_value", + task=tasks.Task(name="name_value"), + task_id="task_id_value", ) -def test_get_task_rest_error(): +def test_create_task_rest_error(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6801,51 +7181,99 @@ def test_get_task_rest_error(): @pytest.mark.parametrize( "request_type", [ - delivery_api.SearchTasksRequest, + delivery_api.GetTaskRequest, dict, ], ) -def test_search_tasks_rest(request_type): +def test_get_task_rest(request_type): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} + request_init = {"name": "providers/sample1/tasks/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 = delivery_api.SearchTasksResponse( - next_page_token="next_page_token_value", + return_value = tasks.Task( + name="name_value", + type_=tasks.Task.Type.PICKUP, + state=tasks.Task.State.OPEN, + task_outcome=tasks.Task.TaskOutcome.SUCCEEDED, + task_outcome_location_source=tasks.Task.TaskOutcomeLocationSource.PROVIDER, + tracking_id="tracking_id_value", + delivery_vehicle_id="delivery_vehicle_id_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = delivery_api.SearchTasksResponse.pb(return_value) + return_value = tasks.Task.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.search_tasks(request) + response = client.get_task(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.SearchTasksPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, tasks.Task) + assert response.name == "name_value" + assert response.type_ == tasks.Task.Type.PICKUP + assert response.state == tasks.Task.State.OPEN + assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED + assert ( + response.task_outcome_location_source + == tasks.Task.TaskOutcomeLocationSource.PROVIDER + ) + assert response.tracking_id == "tracking_id_value" + assert response.delivery_vehicle_id == "delivery_vehicle_id_value" -def test_search_tasks_rest_required_fields( - request_type=delivery_api.SearchTasksRequest, -): +def test_get_task_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_task] = mock_rpc + + request = {} + client.get_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_task_rest_required_fields(request_type=delivery_api.GetTaskRequest): transport_class = transports.DeliveryServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["tracking_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -6853,39 +7281,26 @@ def test_search_tasks_rest_required_fields( ) # verify fields with default values are dropped - assert "trackingId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search_tasks._get_unset_required_fields(jsonified_request) + ).get_task._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "trackingId" in jsonified_request - assert jsonified_request["trackingId"] == request_init["tracking_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["trackingId"] = "tracking_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).search_tasks._get_unset_required_fields(jsonified_request) + ).get_task._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "header", - "page_size", - "page_token", - "tracking_id", - ) - ) + assert not set(unset_fields) - set(("header",)) 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" - assert "trackingId" in jsonified_request - assert jsonified_request["trackingId"] == "tracking_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -6894,7 +7309,7 @@ def test_search_tasks_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = delivery_api.SearchTasksResponse() + return_value = tasks.Task() # 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 @@ -6915,51 +7330,30 @@ def test_search_tasks_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = delivery_api.SearchTasksResponse.pb(return_value) + return_value = tasks.Task.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.search_tasks(request) + response = client.get_task(request) - expected_params = [ - ( - "trackingId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_search_tasks_rest_unset_required_fields(): +def test_get_task_rest_unset_required_fields(): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.search_tasks._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "header", - "pageSize", - "pageToken", - "trackingId", - ) - ) - & set( - ( - "parent", - "trackingId", - ) - ) - ) + unset_fields = transport.get_task._get_unset_required_fields({}) + assert set(unset_fields) == (set(("header",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_search_tasks_rest_interceptors(null_interceptor): +def test_get_task_rest_interceptors(null_interceptor): transport = transports.DeliveryServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6972,15 +7366,13 @@ def test_search_tasks_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "post_search_tasks" + transports.DeliveryServiceRestInterceptor, "post_get_task" ) as post, mock.patch.object( - transports.DeliveryServiceRestInterceptor, "pre_search_tasks" + transports.DeliveryServiceRestInterceptor, "pre_get_task" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = delivery_api.SearchTasksRequest.pb( - delivery_api.SearchTasksRequest() - ) + pb_message = delivery_api.GetTaskRequest.pb(delivery_api.GetTaskRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6991,19 +7383,17 @@ def test_search_tasks_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = delivery_api.SearchTasksResponse.to_json( - delivery_api.SearchTasksResponse() - ) + req.return_value._content = tasks.Task.to_json(tasks.Task()) - request = delivery_api.SearchTasksRequest() + request = delivery_api.GetTaskRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = delivery_api.SearchTasksResponse() + post.return_value = tasks.Task() - client.search_tasks( + client.get_task( request, metadata=[ ("key", "val"), @@ -7015,8 +7405,8 @@ def test_search_tasks_rest_interceptors(null_interceptor): post.assert_called_once() -def test_search_tasks_rest_bad_request( - transport: str = "rest", request_type=delivery_api.SearchTasksRequest +def test_get_task_rest_bad_request( + transport: str = "rest", request_type=delivery_api.GetTaskRequest ): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7024,7 +7414,7 @@ def test_search_tasks_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "providers/sample1"} + request_init = {"name": "providers/sample1/tasks/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7036,10 +7426,10 @@ def test_search_tasks_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.search_tasks(request) + client.get_task(request) -def test_search_tasks_rest_flattened(): +def test_get_task_rest_flattened(): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7048,14 +7438,14 @@ def test_search_tasks_rest_flattened(): # 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 = delivery_api.SearchTasksResponse() + return_value = tasks.Task() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "providers/sample1"} + sample_request = {"name": "providers/sample1/tasks/sample2"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -7063,23 +7453,23 @@ def test_search_tasks_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = delivery_api.SearchTasksResponse.pb(return_value) + return_value = tasks.Task.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.search_tasks(**mock_args) + client.get_task(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=providers/*}/tasks:search" % client.transport._host, args[1] + "%s/v1/{name=providers/*/tasks/*}" % client.transport._host, args[1] ) -def test_search_tasks_rest_flattened_error(transport: str = "rest"): +def test_get_task_rest_flattened_error(transport: str = "rest"): client = DeliveryServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7088,72 +7478,17 @@ def test_search_tasks_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.search_tasks( - delivery_api.SearchTasksRequest(), - parent="parent_value", + client.get_task( + delivery_api.GetTaskRequest(), + name="name_value", ) -def test_search_tasks_rest_pager(transport: str = "rest"): +def test_get_task_rest_error(): client = DeliveryServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # 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 = ( - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - tasks.Task(), - ], - next_page_token="abc", - ), - delivery_api.SearchTasksResponse( - tasks=[], - next_page_token="def", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - ], - next_page_token="ghi", - ), - delivery_api.SearchTasksResponse( - tasks=[ - tasks.Task(), - tasks.Task(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(delivery_api.SearchTasksResponse.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": "providers/sample1"} - - pager = client.search_tasks(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, tasks.Task) for i in results) - - pages = list(client.search_tasks(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", @@ -7364,6 +7699,42 @@ def get_message_fields(field): assert response.delivery_vehicle_id == "delivery_vehicle_id_value" +def test_update_task_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_task in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_task] = mock_rpc + + request = {} + client.update_task(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_task(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + def test_update_task_rest_required_fields(request_type=delivery_api.UpdateTaskRequest): transport_class = transports.DeliveryServiceRestTransport @@ -7643,6 +8014,42 @@ def test_list_tasks_rest(request_type): assert response.total_size == 1086 +def test_list_tasks_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_tasks in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_tasks] = mock_rpc + + request = {} + client.list_tasks(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_tasks(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + def test_list_tasks_rest_required_fields(request_type=delivery_api.ListTasksRequest): transport_class = transports.DeliveryServiceRestTransport @@ -7984,6 +8391,47 @@ def test_get_task_tracking_info_rest(request_type): assert response.task_outcome == tasks.Task.TaskOutcome.SUCCEEDED +def test_get_task_tracking_info_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_task_tracking_info + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.get_task_tracking_info + ] = mock_rpc + + request = {} + client.get_task_tracking_info(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_task_tracking_info(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + def test_get_task_tracking_info_rest_required_fields( request_type=delivery_api.GetTaskTrackingInfoRequest, ): @@ -8254,6 +8702,47 @@ def test_list_delivery_vehicles_rest(request_type): assert response.total_size == 1086 +def test_list_delivery_vehicles_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = DeliveryServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_delivery_vehicles + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.list_delivery_vehicles + ] = mock_rpc + + request = {} + client.list_delivery_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_delivery_vehicles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + def test_list_delivery_vehicles_rest_required_fields( request_type=delivery_api.ListDeliveryVehiclesRequest, ): @@ -8703,7 +9192,6 @@ def test_delivery_service_base_transport(): "batch_create_tasks", "create_task", "get_task", - "search_tasks", "update_task", "list_tasks", "get_task_tracking_info", @@ -8984,9 +9472,6 @@ def test_delivery_service_client_transport_session_collision(transport_name): session1 = client1.transport.get_task._session session2 = client2.transport.get_task._session assert session1 != session2 - session1 = client1.transport.search_tasks._session - session2 = client2.transport.search_tasks._session - assert session1 != session2 session1 = client1.transport.update_task._session session2 = client2.transport.update_task._session assert session1 != session2 From e6969d550a7255f8ff3ed10ab77072d38edb61ff Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Wed, 8 May 2024 11:32:52 -0400 Subject: [PATCH 2/3] fix!: [google-maps-fleetengine] An existing method `UpdateVehicleLocation` is removed from service `VehicleService` (#12666) BEGIN_COMMIT_OVERRIDE fix!: An existing method `UpdateVehicleLocation` is removed from service `VehicleService` fix!: An existing method `SearchFuzzedVehicles` is removed from service `VehicleService` fix!: An existing message `UpdateVehicleLocationRequest` is removed END_COMMIT_OVERRIDE - [ ] Regenerate this pull request now. fix!: An existing method `SearchFuzzedVehicles` is removed from service `VehicleService` fix!: An existing message `UpdateVehicleLocationRequest` is removed PiperOrigin-RevId: 631557549 Source-Link: https://github.com/googleapis/googleapis/commit/3d50414a7ff3f0b8ffe8ad7858257396e4f18131 Source-Link: https://github.com/googleapis/googleapis-gen/commit/5ce63d4e636a975175bde2d16c15e70dd5a81ff4 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtZmxlZXRlbmdpbmUvLk93bEJvdC55YW1sIiwiaCI6IjVjZTYzZDRlNjM2YTk3NTE3NWJkZTJkMTZjMTVlNzBkZDVhODFmZjQifQ== --------- Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: ohmayr <omairnaveed@ymail.com> --- .../google/maps/fleetengine/__init__.py | 2 - .../google/maps/fleetengine_v1/__init__.py | 2 - .../maps/fleetengine_v1/gapic_metadata.json | 20 - .../services/trip_service/async_client.py | 112 +-- .../services/trip_service/client.py | 54 +- .../services/trip_service/transports/grpc.py | 25 +- .../trip_service/transports/grpc_asyncio.py | 92 +- .../services/vehicle_service/async_client.py | 316 +------ .../services/vehicle_service/client.py | 253 +---- .../vehicle_service/transports/base.py | 33 +- .../vehicle_service/transports/grpc.py | 84 +- .../transports/grpc_asyncio.py | 165 ++-- .../maps/fleetengine_v1/types/__init__.py | 2 - .../maps/fleetengine_v1/types/vehicle_api.py | 43 - ...le_service_search_fuzzed_vehicles_async.py | 57 -- ...cle_service_search_fuzzed_vehicles_sync.py | 57 -- ...e_service_update_vehicle_location_async.py | 52 -- ...le_service_update_vehicle_location_sync.py | 52 -- .../snippet_metadata_maps.fleetengine.v1.json | 306 ------ .../scripts/fixup_fleetengine_v1_keywords.py | 2 - .../gapic/fleetengine_v1/test_trip_service.py | 437 +++++++++ .../fleetengine_v1/test_vehicle_service.py | 879 +++++++++++------- 22 files changed, 1319 insertions(+), 1726 deletions(-) delete mode 100644 packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_async.py delete mode 100644 packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_sync.py delete mode 100644 packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_async.py delete mode 100644 packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_sync.py diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine/__init__.py b/packages/google-maps-fleetengine/google/maps/fleetengine/__init__.py index 956aaa3c46a2..1ed06619ea84 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine/__init__.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine/__init__.py @@ -69,7 +69,6 @@ SearchVehiclesResponse, UpdateVehicleAttributesRequest, UpdateVehicleAttributesResponse, - UpdateVehicleLocationRequest, UpdateVehicleRequest, VehicleAttributeList, VehicleMatch, @@ -125,7 +124,6 @@ "SearchVehiclesResponse", "UpdateVehicleAttributesRequest", "UpdateVehicleAttributesResponse", - "UpdateVehicleLocationRequest", "UpdateVehicleRequest", "VehicleAttributeList", "VehicleMatch", diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/__init__.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/__init__.py index 809f9e0ebc6c..03264cc6566e 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/__init__.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/__init__.py @@ -58,7 +58,6 @@ SearchVehiclesResponse, UpdateVehicleAttributesRequest, UpdateVehicleAttributesResponse, - UpdateVehicleLocationRequest, UpdateVehicleRequest, VehicleAttributeList, VehicleMatch, @@ -117,7 +116,6 @@ "UpdateTripRequest", "UpdateVehicleAttributesRequest", "UpdateVehicleAttributesResponse", - "UpdateVehicleLocationRequest", "UpdateVehicleRequest", "Vehicle", "VehicleAttribute", diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_metadata.json b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_metadata.json index 58371224af0a..1a6ac8f7d116 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_metadata.json +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/gapic_metadata.json @@ -89,11 +89,6 @@ "list_vehicles" ] }, - "SearchFuzzedVehicles": { - "methods": [ - "search_fuzzed_vehicles" - ] - }, "SearchVehicles": { "methods": [ "search_vehicles" @@ -108,11 +103,6 @@ "methods": [ "update_vehicle_attributes" ] - }, - "UpdateVehicleLocation": { - "methods": [ - "update_vehicle_location" - ] } } }, @@ -134,11 +124,6 @@ "list_vehicles" ] }, - "SearchFuzzedVehicles": { - "methods": [ - "search_fuzzed_vehicles" - ] - }, "SearchVehicles": { "methods": [ "search_vehicles" @@ -153,11 +138,6 @@ "methods": [ "update_vehicle_attributes" ] - }, - "UpdateVehicleLocation": { - "methods": [ - "update_vehicle_location" - ] } } } diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/async_client.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/async_client.py index 0a0faa40753b..9497389fba19 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/async_client.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/async_client.py @@ -17,6 +17,7 @@ import functools import re from typing import ( + Callable, Dict, Mapping, MutableMapping, @@ -195,7 +196,9 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, TripServiceTransport] = "grpc_asyncio", + transport: Optional[ + Union[str, TripServiceTransport, Callable[..., TripServiceTransport]] + ] = "grpc_asyncio", client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -207,9 +210,11 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.TripServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. + transport (Optional[Union[str,TripServiceTransport,Callable[..., TripServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the TripServiceTransport constructor. + If set to None, a transport is chosen automatically. client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. @@ -305,24 +310,16 @@ async def sample_create_trip(): Trip metadata. """ # Create or coerce a protobuf request object. - request = trip_api.CreateTripRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, trip_api.CreateTripRequest): + request = trip_api.CreateTripRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_trip + ] # Certain fields should be provided within the metadata header; # add these here. @@ -394,24 +391,14 @@ async def sample_get_trip(): Trip metadata. """ # Create or coerce a protobuf request object. - request = trip_api.GetTripRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, trip_api.GetTripRequest): + request = trip_api.GetTripRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[self._client._transport.get_trip] # Certain fields should be provided within the metadata header; # add these here. @@ -477,15 +464,16 @@ async def sample_report_billable_trip(): sent along with the request as metadata. """ # Create or coerce a protobuf request object. - request = trip_api.ReportBillableTripRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, trip_api.ReportBillableTripRequest): + request = trip_api.ReportBillableTripRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.report_billable_trip, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.report_billable_trip + ] # Certain fields should be provided within the metadata header; # add these here. @@ -560,24 +548,16 @@ async def sample_search_trips(): """ # Create or coerce a protobuf request object. - request = trip_api.SearchTripsRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, trip_api.SearchTripsRequest): + request = trip_api.SearchTripsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_trips, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_trips + ] # Certain fields should be provided within the metadata header; # add these here. @@ -658,24 +638,16 @@ async def sample_update_trip(): Trip metadata. """ # Create or coerce a protobuf request object. - request = trip_api.UpdateTripRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, trip_api.UpdateTripRequest): + request = trip_api.UpdateTripRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_trip, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_trip + ] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/client.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/client.py index 818f1d13d058..27ac83bb16b4 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/client.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/client.py @@ -17,6 +17,7 @@ import os import re from typing import ( + Callable, Dict, Mapping, MutableMapping, @@ -525,7 +526,9 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, TripServiceTransport]] = None, + transport: Optional[ + Union[str, TripServiceTransport, Callable[..., TripServiceTransport]] + ] = None, client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -537,9 +540,11 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, TripServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. + transport (Optional[Union[str,TripServiceTransport,Callable[..., TripServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the TripServiceTransport constructor. + If set to None, a transport is chosen automatically. client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. @@ -645,8 +650,15 @@ def __init__( api_key_value ) - Transport = type(self).get_transport_class(cast(str, transport)) - self._transport = Transport( + transport_init: Union[ + Type[TripServiceTransport], Callable[..., TripServiceTransport] + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., TripServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( credentials=credentials, credentials_file=self._client_options.credentials_file, host=self._api_endpoint, @@ -710,10 +722,8 @@ def sample_create_trip(): Trip metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a trip_api.CreateTripRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, trip_api.CreateTripRequest): request = trip_api.CreateTripRequest(request) @@ -797,10 +807,8 @@ def sample_get_trip(): Trip metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a trip_api.GetTripRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, trip_api.GetTripRequest): request = trip_api.GetTripRequest(request) @@ -878,10 +886,8 @@ def sample_report_billable_trip(): sent along with the request as metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a trip_api.ReportBillableTripRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, trip_api.ReportBillableTripRequest): request = trip_api.ReportBillableTripRequest(request) @@ -968,10 +974,8 @@ def sample_search_trips(): """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a trip_api.SearchTripsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, trip_api.SearchTripsRequest): request = trip_api.SearchTripsRequest(request) @@ -1064,10 +1068,8 @@ def sample_update_trip(): Trip metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a trip_api.UpdateTripRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, trip_api.UpdateTripRequest): request = trip_api.UpdateTripRequest(request) diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py index a78c86de97a4..e5f1d2582441 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc.py @@ -50,7 +50,7 @@ def __init__( credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, api_mtls_endpoint: Optional[str] = None, client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, @@ -70,14 +70,17 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. 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. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from @@ -87,11 +90,11 @@ def __init__( private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if a ``channel`` instance is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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): @@ -117,7 +120,7 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, grpc.Channel): # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. @@ -158,7 +161,9 @@ def __init__( ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py index 55c696afc048..025032aa9764 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/trip_service/transports/grpc_asyncio.py @@ -16,7 +16,9 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore from google.protobuf import empty_pb2 # type: ignore @@ -65,7 +67,6 @@ def create_channel( 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 optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -95,7 +96,7 @@ def __init__( credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, api_mtls_endpoint: Optional[str] = None, client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, @@ -115,15 +116,18 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. 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. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from @@ -133,11 +137,11 @@ def __init__( private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if a ``channel`` instance is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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): @@ -163,7 +167,7 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, aio.Channel): # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. @@ -203,7 +207,9 @@ def __init__( ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -363,6 +369,72 @@ def update_trip( ) return self._stubs["update_trip"] + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_trip: gapic_v1.method_async.wrap_method( + self.create_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_trip: gapic_v1.method_async.wrap_method( + self.get_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.report_billable_trip: gapic_v1.method_async.wrap_method( + self.report_billable_trip, + default_timeout=None, + client_info=client_info, + ), + self.search_trips: gapic_v1.method_async.wrap_method( + self.search_trips, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_trip: gapic_v1.method_async.wrap_method( + self.update_trip, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + } + def close(self): return self.grpc_channel.close() diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/async_client.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/async_client.py index 8c6f87525373..02f5608cb93b 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/async_client.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/async_client.py @@ -17,6 +17,7 @@ import functools import re from typing import ( + Callable, Dict, Mapping, MutableMapping, @@ -27,7 +28,6 @@ Type, Union, ) -import warnings from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 @@ -45,7 +45,6 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore from google.maps.fleetengine_v1.services.vehicle_service import pagers from google.maps.fleetengine_v1.types import fleetengine, vehicle_api, vehicles @@ -199,7 +198,9 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, VehicleServiceTransport] = "grpc_asyncio", + transport: Optional[ + Union[str, VehicleServiceTransport, Callable[..., VehicleServiceTransport]] + ] = "grpc_asyncio", client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -211,9 +212,11 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, ~.VehicleServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. + transport (Optional[Union[str,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the VehicleServiceTransport constructor. + If set to None, a transport is chosen automatically. client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. @@ -338,24 +341,16 @@ async def sample_create_vehicle(): Vehicle metadata. """ # Create or coerce a protobuf request object. - request = vehicle_api.CreateVehicleRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, vehicle_api.CreateVehicleRequest): + request = vehicle_api.CreateVehicleRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.create_vehicle + ] # Certain fields should be provided within the metadata header; # add these here. @@ -427,24 +422,16 @@ async def sample_get_vehicle(): Vehicle metadata. """ # Create or coerce a protobuf request object. - request = vehicle_api.GetVehicleRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, vehicle_api.GetVehicleRequest): + request = vehicle_api.GetVehicleRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_vehicle + ] # Certain fields should be provided within the metadata header; # add these here. @@ -533,112 +520,16 @@ async def sample_update_vehicle(): Vehicle metadata. """ # Create or coerce a protobuf request object. - request = vehicle_api.UpdateVehicleRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_vehicle, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def update_vehicle_location( - self, - request: Optional[Union[vehicle_api.UpdateVehicleLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fleetengine.VehicleLocation: - r"""Deprecated: Use the ``UpdateVehicle`` method instead. - UpdateVehicleLocation updates the location of the vehicle. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import fleetengine_v1 - - async def sample_update_vehicle_location(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleLocationRequest( - name="name_value", - ) - - # Make the request - response = await client.update_vehicle_location(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.UpdateVehicleLocationRequest, dict]]): - The request object. ``UpdateVehicleLocation`` request message. - retry (google.api_core.retry_async.AsyncRetry): 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: - google.maps.fleetengine_v1.types.VehicleLocation: - The location, speed, and heading of a - vehicle at a point in time. - - """ - warnings.warn( - "VehicleServiceAsyncClient.update_vehicle_location is deprecated", - DeprecationWarning, - ) - - # Create or coerce a protobuf request object. - request = vehicle_api.UpdateVehicleLocationRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, vehicle_api.UpdateVehicleRequest): + request = vehicle_api.UpdateVehicleRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_vehicle_location, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_vehicle + ] # Certain fields should be provided within the metadata header; # add these here. @@ -721,24 +612,16 @@ async def sample_update_vehicle_attributes(): UpdateVehicleAttributes response message. """ # Create or coerce a protobuf request object. - request = vehicle_api.UpdateVehicleAttributesRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, vehicle_api.UpdateVehicleAttributesRequest): + request = vehicle_api.UpdateVehicleAttributesRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_vehicle_attributes, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.update_vehicle_attributes + ] # Certain fields should be provided within the metadata header; # add these here. @@ -817,15 +700,16 @@ async def sample_list_vehicles(): """ # Create or coerce a protobuf request object. - request = vehicle_api.ListVehiclesRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, vehicle_api.ListVehiclesRequest): + request = vehicle_api.ListVehiclesRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_vehicles, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_vehicles + ] # Certain fields should be provided within the metadata header; # add these here. @@ -912,114 +796,16 @@ async def sample_search_vehicles(): SearchVehicles response message. """ # Create or coerce a protobuf request object. - request = vehicle_api.SearchVehiclesRequest(request) + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, vehicle_api.SearchVehiclesRequest): + request = vehicle_api.SearchVehiclesRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_vehicles, - default_retry=retries.AsyncRetry( - initial=1.0, - maximum=10.0, - multiplier=1.3, - predicate=retries.if_exception_type( - core_exceptions.ServiceUnavailable, - ), - deadline=15.0, - ), - default_timeout=15.0, - client_info=DEFAULT_CLIENT_INFO, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Validate the universe domain. - self._client._validate_universe_domain() - - # Send the request. - response = await rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - - async def search_fuzzed_vehicles( - self, - request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.SearchVehiclesResponse: - r"""Deprecated: Use ``SearchVehicles`` instead. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import fleetengine_v1 - - async def sample_search_fuzzed_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = await client.search_fuzzed_vehicles(request=request) - - # Handle the response - print(response) - - Args: - request (Optional[Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]]): - The request object. ``SearchVehicles`` request message. - retry (google.api_core.retry_async.AsyncRetry): 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: - google.maps.fleetengine_v1.types.SearchVehiclesResponse: - SearchVehicles response message. - """ - warnings.warn( - "VehicleServiceAsyncClient.search_fuzzed_vehicles is deprecated", - DeprecationWarning, - ) - - # Create or coerce a protobuf request object. - request = vehicle_api.SearchVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.search_fuzzed_vehicles, - default_timeout=None, - client_info=DEFAULT_CLIENT_INFO, - ) + rpc = self._client._transport._wrapped_methods[ + self._client._transport.search_vehicles + ] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/client.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/client.py index 84314f1108d7..24c624ee4173 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/client.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/client.py @@ -17,6 +17,7 @@ import os import re from typing import ( + Callable, Dict, Mapping, MutableMapping, @@ -49,7 +50,6 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.protobuf import wrappers_pb2 # type: ignore -from google.type import latlng_pb2 # type: ignore from google.maps.fleetengine_v1.services.vehicle_service import pagers from google.maps.fleetengine_v1.types import fleetengine, vehicle_api, vehicles @@ -526,7 +526,9 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Optional[Union[str, VehicleServiceTransport]] = None, + transport: Optional[ + Union[str, VehicleServiceTransport, Callable[..., VehicleServiceTransport]] + ] = None, client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: @@ -538,9 +540,11 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - transport (Union[str, VehicleServiceTransport]): The - transport to use. If set to None, a transport is chosen - automatically. + transport (Optional[Union[str,VehicleServiceTransport,Callable[..., VehicleServiceTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the VehicleServiceTransport constructor. + If set to None, a transport is chosen automatically. client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. @@ -649,8 +653,15 @@ def __init__( api_key_value ) - Transport = type(self).get_transport_class(cast(str, transport)) - self._transport = Transport( + transport_init: Union[ + Type[VehicleServiceTransport], Callable[..., VehicleServiceTransport] + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., VehicleServiceTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( credentials=credentials, credentials_file=self._client_options.credentials_file, host=self._api_endpoint, @@ -743,10 +754,8 @@ def sample_create_vehicle(): Vehicle metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.CreateVehicleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, vehicle_api.CreateVehicleRequest): request = vehicle_api.CreateVehicleRequest(request) @@ -830,10 +839,8 @@ def sample_get_vehicle(): Vehicle metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.GetVehicleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, vehicle_api.GetVehicleRequest): request = vehicle_api.GetVehicleRequest(request) @@ -934,10 +941,8 @@ def sample_update_vehicle(): Vehicle metadata. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.UpdateVehicleRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, vehicle_api.UpdateVehicleRequest): request = vehicle_api.UpdateVehicleRequest(request) @@ -971,101 +976,6 @@ def sample_update_vehicle(): # Done; return the response. return response - def update_vehicle_location( - self, - request: Optional[Union[vehicle_api.UpdateVehicleLocationRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> fleetengine.VehicleLocation: - r"""Deprecated: Use the ``UpdateVehicle`` method instead. - UpdateVehicleLocation updates the location of the vehicle. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import fleetengine_v1 - - def sample_update_vehicle_location(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleLocationRequest( - name="name_value", - ) - - # Make the request - response = client.update_vehicle_location(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.UpdateVehicleLocationRequest, dict]): - The request object. ``UpdateVehicleLocation`` request message. - 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: - google.maps.fleetengine_v1.types.VehicleLocation: - The location, speed, and heading of a - vehicle at a point in time. - - """ - warnings.warn( - "VehicleServiceClient.update_vehicle_location is deprecated", - DeprecationWarning, - ) - - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.UpdateVehicleLocationRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, vehicle_api.UpdateVehicleLocationRequest): - request = vehicle_api.UpdateVehicleLocationRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_vehicle_location] - - header_params = {} - - routing_param_regex = re.compile("^(?P<provider_id>providers/[^/]+)$") - regex_match = routing_param_regex.match(request.name) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - def update_vehicle_attributes( self, request: Optional[ @@ -1127,10 +1037,8 @@ def sample_update_vehicle_attributes(): UpdateVehicleAttributes response message. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.UpdateVehicleAttributesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, vehicle_api.UpdateVehicleAttributesRequest): request = vehicle_api.UpdateVehicleAttributesRequest(request) @@ -1223,10 +1131,8 @@ def sample_list_vehicles(): """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.ListVehiclesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, vehicle_api.ListVehiclesRequest): request = vehicle_api.ListVehiclesRequest(request) @@ -1325,10 +1231,8 @@ def sample_search_vehicles(): SearchVehicles response message. """ # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.SearchVehiclesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. if not isinstance(request, vehicle_api.SearchVehiclesRequest): request = vehicle_api.SearchVehiclesRequest(request) @@ -1362,103 +1266,6 @@ def sample_search_vehicles(): # Done; return the response. return response - def search_fuzzed_vehicles( - self, - request: Optional[Union[vehicle_api.SearchVehiclesRequest, dict]] = None, - *, - retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: Union[float, object] = gapic_v1.method.DEFAULT, - metadata: Sequence[Tuple[str, str]] = (), - ) -> vehicle_api.SearchVehiclesResponse: - r"""Deprecated: Use ``SearchVehicles`` instead. - - .. code-block:: python - - # This snippet has been automatically generated and should be regarded as a - # code template only. - # It will require modifications to work: - # - It may require correct/in-range values for request initialization. - # - It may require specifying regional endpoints when creating the service - # client as shown in: - # https://googleapis.dev/python/google-api-core/latest/client_options.html - from google.maps import fleetengine_v1 - - def sample_search_fuzzed_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = client.search_fuzzed_vehicles(request=request) - - # Handle the response - print(response) - - Args: - request (Union[google.maps.fleetengine_v1.types.SearchVehiclesRequest, dict]): - The request object. ``SearchVehicles`` request message. - 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: - google.maps.fleetengine_v1.types.SearchVehiclesResponse: - SearchVehicles response message. - """ - warnings.warn( - "VehicleServiceClient.search_fuzzed_vehicles is deprecated", - DeprecationWarning, - ) - - # Create or coerce a protobuf request object. - # Minor optimization to avoid making a copy if the user passes - # in a vehicle_api.SearchVehiclesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, vehicle_api.SearchVehiclesRequest): - request = vehicle_api.SearchVehiclesRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.search_fuzzed_vehicles] - - header_params = {} - - routing_param_regex = re.compile("^(?P<provider_id>providers/[^/]+)$") - regex_match = routing_param_regex.match(request.parent) - if regex_match and regex_match.group("provider_id"): - header_params["provider_id"] = regex_match.group("provider_id") - - if header_params: - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata(header_params), - ) - - # Validate the universe domain. - self._validate_universe_domain() - - # Send the request. - response = rpc( - request, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - - # Done; return the response. - return response - def __enter__(self) -> "VehicleServiceClient": return self diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py index c877f15a98ac..6cb088861824 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/base.py @@ -25,7 +25,7 @@ from google.oauth2 import service_account # type: ignore from google.maps.fleetengine_v1 import gapic_version as package_version -from google.maps.fleetengine_v1.types import fleetengine, vehicle_api, vehicles +from google.maps.fleetengine_v1.types import vehicle_api, vehicles DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ @@ -168,11 +168,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=15.0, client_info=client_info, ), - self.update_vehicle_location: gapic_v1.method.wrap_method( - self.update_vehicle_location, - default_timeout=None, - client_info=client_info, - ), self.update_vehicle_attributes: gapic_v1.method.wrap_method( self.update_vehicle_attributes, default_retry=retries.Retry( @@ -206,11 +201,6 @@ def _prep_wrapped_messages(self, client_info): default_timeout=15.0, client_info=client_info, ), - self.search_fuzzed_vehicles: gapic_v1.method.wrap_method( - self.search_fuzzed_vehicles, - default_timeout=None, - client_info=client_info, - ), } def close(self): @@ -249,15 +239,6 @@ def update_vehicle( ]: raise NotImplementedError() - @property - def update_vehicle_location( - self, - ) -> Callable[ - [vehicle_api.UpdateVehicleLocationRequest], - Union[fleetengine.VehicleLocation, Awaitable[fleetengine.VehicleLocation]], - ]: - raise NotImplementedError() - @property def update_vehicle_attributes( self, @@ -294,18 +275,6 @@ def search_vehicles( ]: raise NotImplementedError() - @property - def search_fuzzed_vehicles( - self, - ) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - Union[ - vehicle_api.SearchVehiclesResponse, - Awaitable[vehicle_api.SearchVehiclesResponse], - ], - ]: - raise NotImplementedError() - @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py index fcc2a0e9107a..88263c5ed46e 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc.py @@ -22,7 +22,7 @@ from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore -from google.maps.fleetengine_v1.types import fleetengine, vehicle_api, vehicles +from google.maps.fleetengine_v1.types import vehicle_api, vehicles from .base import DEFAULT_CLIENT_INFO, VehicleServiceTransport @@ -49,7 +49,7 @@ def __init__( credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: Optional[grpc.Channel] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, api_mtls_endpoint: Optional[str] = None, client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, @@ -69,14 +69,17 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. 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. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from @@ -86,11 +89,11 @@ def __init__( private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if a ``channel`` instance is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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): @@ -116,7 +119,7 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, grpc.Channel): # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. @@ -157,7 +160,9 @@ def __init__( ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -353,35 +358,6 @@ def update_vehicle( ) return self._stubs["update_vehicle"] - @property - def update_vehicle_location( - self, - ) -> Callable[ - [vehicle_api.UpdateVehicleLocationRequest], fleetengine.VehicleLocation - ]: - r"""Return a callable for the update vehicle location method over gRPC. - - Deprecated: Use the ``UpdateVehicle`` method instead. - UpdateVehicleLocation updates the location of the vehicle. - - Returns: - Callable[[~.UpdateVehicleLocationRequest], - ~.VehicleLocation]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_vehicle_location" not in self._stubs: - self._stubs["update_vehicle_location"] = self.grpc_channel.unary_unary( - "/maps.fleetengine.v1.VehicleService/UpdateVehicleLocation", - request_serializer=vehicle_api.UpdateVehicleLocationRequest.serialize, - response_deserializer=fleetengine.VehicleLocation.deserialize, - ) - return self._stubs["update_vehicle_location"] - @property def update_vehicle_attributes( self, @@ -472,34 +448,6 @@ def search_vehicles( ) return self._stubs["search_vehicles"] - @property - def search_fuzzed_vehicles( - self, - ) -> Callable[ - [vehicle_api.SearchVehiclesRequest], vehicle_api.SearchVehiclesResponse - ]: - r"""Return a callable for the search fuzzed vehicles method over gRPC. - - Deprecated: Use ``SearchVehicles`` instead. - - Returns: - Callable[[~.SearchVehiclesRequest], - ~.SearchVehiclesResponse]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "search_fuzzed_vehicles" not in self._stubs: - self._stubs["search_fuzzed_vehicles"] = self.grpc_channel.unary_unary( - "/maps.fleetengine.v1.VehicleService/SearchFuzzedVehicles", - request_serializer=vehicle_api.SearchVehiclesRequest.serialize, - response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, - ) - return self._stubs["search_fuzzed_vehicles"] - def close(self): self.grpc_channel.close() diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py index ac83b42fec1b..caf3c813a8df 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/services/vehicle_service/transports/grpc_asyncio.py @@ -16,13 +16,15 @@ from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union import warnings +from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1, grpc_helpers_async +from google.api_core import retry_async as retries from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore -from google.maps.fleetengine_v1.types import fleetengine, vehicle_api, vehicles +from google.maps.fleetengine_v1.types import vehicle_api, vehicles from .base import DEFAULT_CLIENT_INFO, VehicleServiceTransport from .grpc import VehicleServiceGrpcTransport @@ -64,7 +66,6 @@ def create_channel( 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 optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. @@ -94,7 +95,7 @@ def __init__( credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: Optional[aio.Channel] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, api_mtls_endpoint: Optional[str] = None, client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, @@ -114,15 +115,18 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. - This argument is ignored if ``channel`` is provided. + This argument is ignored if a ``channel`` instance is provided. 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. + This argument is ignored if a ``channel`` instance is provided. scopes (Optional[Sequence[str]]): A optional list of scopes needed for this service. These are only used when credentials are not specified and are passed to :func:`google.auth.default`. - channel (Optional[aio.Channel]): A ``Channel`` instance through - which to make calls. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from @@ -132,11 +136,11 @@ def __init__( private key bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` is None. ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials - for the grpc channel. It is ignored if ``channel`` is provided. + for the grpc channel. It is ignored if a ``channel`` instance is provided. client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback to provide client certificate bytes and private key bytes, both in PEM format. It is used to configure a mutual TLS channel. It is - ignored if ``channel`` or ``ssl_channel_credentials`` is provided. + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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): @@ -162,7 +166,7 @@ def __init__( if client_cert_source: warnings.warn("client_cert_source is deprecated", DeprecationWarning) - if channel: + if isinstance(channel, aio.Channel): # Ignore credentials if a channel was passed. credentials = False # If a channel was explicitly provided, set it. @@ -202,7 +206,9 @@ def __init__( ) if not self._grpc_channel: - self._grpc_channel = type(self).create_channel( + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( self._host, # use the credentials which are saved credentials=self._credentials, @@ -356,36 +362,6 @@ def update_vehicle( ) return self._stubs["update_vehicle"] - @property - def update_vehicle_location( - self, - ) -> Callable[ - [vehicle_api.UpdateVehicleLocationRequest], - Awaitable[fleetengine.VehicleLocation], - ]: - r"""Return a callable for the update vehicle location method over gRPC. - - Deprecated: Use the ``UpdateVehicle`` method instead. - UpdateVehicleLocation updates the location of the vehicle. - - Returns: - Callable[[~.UpdateVehicleLocationRequest], - Awaitable[~.VehicleLocation]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "update_vehicle_location" not in self._stubs: - self._stubs["update_vehicle_location"] = self.grpc_channel.unary_unary( - "/maps.fleetengine.v1.VehicleService/UpdateVehicleLocation", - request_serializer=vehicle_api.UpdateVehicleLocationRequest.serialize, - response_deserializer=fleetengine.VehicleLocation.deserialize, - ) - return self._stubs["update_vehicle_location"] - @property def update_vehicle_attributes( self, @@ -479,34 +455,85 @@ def search_vehicles( ) return self._stubs["search_vehicles"] - @property - def search_fuzzed_vehicles( - self, - ) -> Callable[ - [vehicle_api.SearchVehiclesRequest], - Awaitable[vehicle_api.SearchVehiclesResponse], - ]: - r"""Return a callable for the search fuzzed vehicles method over gRPC. - - Deprecated: Use ``SearchVehicles`` instead. - - Returns: - Callable[[~.SearchVehiclesRequest], - Awaitable[~.SearchVehiclesResponse]]: - A function that, when called, will call the underlying RPC - on the server. - """ - # Generate a "stub function" on-the-fly which will actually make - # the request. - # gRPC handles serialization and deserialization, so we just need - # to pass in the functions for each. - if "search_fuzzed_vehicles" not in self._stubs: - self._stubs["search_fuzzed_vehicles"] = self.grpc_channel.unary_unary( - "/maps.fleetengine.v1.VehicleService/SearchFuzzedVehicles", - request_serializer=vehicle_api.SearchVehiclesRequest.serialize, - response_deserializer=vehicle_api.SearchVehiclesResponse.deserialize, - ) - return self._stubs["search_fuzzed_vehicles"] + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.create_vehicle: gapic_v1.method_async.wrap_method( + self.create_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.get_vehicle: gapic_v1.method_async.wrap_method( + self.get_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle: gapic_v1.method_async.wrap_method( + self.update_vehicle, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.update_vehicle_attributes: gapic_v1.method_async.wrap_method( + self.update_vehicle_attributes, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + self.list_vehicles: gapic_v1.method_async.wrap_method( + self.list_vehicles, + default_timeout=None, + client_info=client_info, + ), + self.search_vehicles: gapic_v1.method_async.wrap_method( + self.search_vehicles, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=15.0, + ), + default_timeout=15.0, + client_info=client_info, + ), + } def close(self): return self.grpc_channel.close() diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/__init__.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/__init__.py index eeceb4d3f044..e323ef4a4937 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/__init__.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/__init__.py @@ -45,7 +45,6 @@ SearchVehiclesResponse, UpdateVehicleAttributesRequest, UpdateVehicleAttributesResponse, - UpdateVehicleLocationRequest, UpdateVehicleRequest, VehicleAttributeList, VehicleMatch, @@ -97,7 +96,6 @@ "SearchVehiclesResponse", "UpdateVehicleAttributesRequest", "UpdateVehicleAttributesResponse", - "UpdateVehicleLocationRequest", "UpdateVehicleRequest", "VehicleAttributeList", "VehicleMatch", diff --git a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py index 0b3447b8b92e..6c9de4b52788 100644 --- a/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py +++ b/packages/google-maps-fleetengine/google/maps/fleetengine_v1/types/vehicle_api.py @@ -35,7 +35,6 @@ "CreateVehicleRequest", "GetVehicleRequest", "UpdateVehicleRequest", - "UpdateVehicleLocationRequest", "UpdateVehicleAttributesRequest", "UpdateVehicleAttributesResponse", "SearchVehiclesRequest", @@ -226,48 +225,6 @@ class UpdateVehicleRequest(proto.Message): ) -class UpdateVehicleLocationRequest(proto.Message): - r"""``UpdateVehicleLocation`` request message. - - Attributes: - header (google.maps.fleetengine_v1.types.RequestHeader): - The standard Fleet Engine request header. - name (str): - Required. Must be in the format - ``providers/{provider}/vehicles/{vehicle}``. The {provider} - must be the Project ID (for example, - ``sample-cloud-project``) of the Google Cloud Project of - which the service account making this call is a member. - current_location (google.maps.fleetengine_v1.types.VehicleLocation): - Required. The vehicle's most recent location. The - ``location`` and ``update_time`` subfields are required. - current_state (google.maps.fleetengine_v1.types.VehicleState): - Set the vehicle's state to either ``ONLINE`` or ``OFFLINE``. - If set to ``UNKNOWN_VEHICLE_STATE``, the vehicle's state - will not be altered. - """ - - header: mf_header.RequestHeader = proto.Field( - proto.MESSAGE, - number=1, - message=mf_header.RequestHeader, - ) - name: str = proto.Field( - proto.STRING, - number=3, - ) - current_location: fleetengine.VehicleLocation = proto.Field( - proto.MESSAGE, - number=4, - message=fleetengine.VehicleLocation, - ) - current_state: mf_vehicles.VehicleState = proto.Field( - proto.ENUM, - number=5, - enum=mf_vehicles.VehicleState, - ) - - class UpdateVehicleAttributesRequest(proto.Message): r"""``UpdateVehicleAttributes`` request message. diff --git a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_async.py b/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_async.py deleted file mode 100644 index 2a947aab5e15..000000000000 --- a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_async.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchFuzzedVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_SearchFuzzedVehicles_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import fleetengine_v1 - - -async def sample_search_fuzzed_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = await client.search_fuzzed_vehicles(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_SearchFuzzedVehicles_async] diff --git a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_sync.py b/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_sync.py deleted file mode 100644 index 338f5415757b..000000000000 --- a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_sync.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for SearchFuzzedVehicles -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_SearchFuzzedVehicles_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import fleetengine_v1 - - -def sample_search_fuzzed_vehicles(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.SearchVehiclesRequest( - parent="parent_value", - pickup_radius_meters=2146, - count=553, - minimum_capacity=1705, - trip_types=['EXCLUSIVE'], - order_by="COST", - ) - - # Make the request - response = client.search_fuzzed_vehicles(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_SearchFuzzedVehicles_sync] diff --git a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_async.py b/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_async.py deleted file mode 100644 index 85e17ed3e7c8..000000000000 --- a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_async.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVehicleLocation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicleLocation_async] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import fleetengine_v1 - - -async def sample_update_vehicle_location(): - # Create a client - client = fleetengine_v1.VehicleServiceAsyncClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleLocationRequest( - name="name_value", - ) - - # Make the request - response = await client.update_vehicle_location(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicleLocation_async] diff --git a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_sync.py b/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_sync.py deleted file mode 100644 index 71e70571024b..000000000000 --- a/packages/google-maps-fleetengine/samples/generated_samples/fleetengine_v1_generated_vehicle_service_update_vehicle_location_sync.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright 2024 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. -# -# Generated code. DO NOT EDIT! -# -# Snippet for UpdateVehicleLocation -# NOTE: This snippet has been automatically generated for illustrative purposes only. -# It may require modifications to work in your environment. - -# To install the latest published package dependency, execute the following: -# python3 -m pip install google-maps-fleetengine - - -# [START fleetengine_v1_generated_VehicleService_UpdateVehicleLocation_sync] -# This snippet has been automatically generated and should be regarded as a -# code template only. -# It will require modifications to work: -# - It may require correct/in-range values for request initialization. -# - It may require specifying regional endpoints when creating the service -# client as shown in: -# https://googleapis.dev/python/google-api-core/latest/client_options.html -from google.maps import fleetengine_v1 - - -def sample_update_vehicle_location(): - # Create a client - client = fleetengine_v1.VehicleServiceClient() - - # Initialize request argument(s) - request = fleetengine_v1.UpdateVehicleLocationRequest( - name="name_value", - ) - - # Make the request - response = client.update_vehicle_location(request=request) - - # Handle the response - print(response) - -# [END fleetengine_v1_generated_VehicleService_UpdateVehicleLocation_sync] diff --git a/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json b/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json index f55ad57ec57a..b0139d358773 100644 --- a/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json +++ b/packages/google-maps-fleetengine/samples/generated_samples/snippet_metadata_maps.fleetengine.v1.json @@ -1229,159 +1229,6 @@ ], "title": "fleetengine_v1_generated_vehicle_service_list_vehicles_sync.py" }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.search_fuzzed_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.SearchFuzzedVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "SearchFuzzedVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", - "shortName": "search_fuzzed_vehicles" - }, - "description": "Sample for SearchFuzzedVehicles", - "file": "fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_SearchFuzzedVehicles_async", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.search_fuzzed_vehicles", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.SearchFuzzedVehicles", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "SearchFuzzedVehicles" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.SearchVehiclesRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.SearchVehiclesResponse", - "shortName": "search_fuzzed_vehicles" - }, - "description": "Sample for SearchFuzzedVehicles", - "file": "fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_SearchFuzzedVehicles_sync", - "segments": [ - { - "end": 56, - "start": 27, - "type": "FULL" - }, - { - "end": 56, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 50, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 53, - "start": 51, - "type": "REQUEST_EXECUTION" - }, - { - "end": 57, - "start": 54, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_search_fuzzed_vehicles_sync.py" - }, { "canonical": true, "clientMethod": { @@ -1688,159 +1535,6 @@ ], "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_attributes_sync.py" }, - { - "canonical": true, - "clientMethod": { - "async": true, - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient", - "shortName": "VehicleServiceAsyncClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceAsyncClient.update_vehicle_location", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleLocation", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicleLocation" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleLocationRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.VehicleLocation", - "shortName": "update_vehicle_location" - }, - "description": "Sample for UpdateVehicleLocation", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_location_async.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleLocation_async", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_location_async.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient", - "shortName": "VehicleServiceClient" - }, - "fullName": "google.maps.fleetengine_v1.VehicleServiceClient.update_vehicle_location", - "method": { - "fullName": "maps.fleetengine.v1.VehicleService.UpdateVehicleLocation", - "service": { - "fullName": "maps.fleetengine.v1.VehicleService", - "shortName": "VehicleService" - }, - "shortName": "UpdateVehicleLocation" - }, - "parameters": [ - { - "name": "request", - "type": "google.maps.fleetengine_v1.types.UpdateVehicleLocationRequest" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, str]" - } - ], - "resultType": "google.maps.fleetengine_v1.types.VehicleLocation", - "shortName": "update_vehicle_location" - }, - "description": "Sample for UpdateVehicleLocation", - "file": "fleetengine_v1_generated_vehicle_service_update_vehicle_location_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "fleetengine_v1_generated_VehicleService_UpdateVehicleLocation_sync", - "segments": [ - { - "end": 51, - "start": 27, - "type": "FULL" - }, - { - "end": 51, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 52, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "fleetengine_v1_generated_vehicle_service_update_vehicle_location_sync.py" - }, { "canonical": true, "clientMethod": { diff --git a/packages/google-maps-fleetengine/scripts/fixup_fleetengine_v1_keywords.py b/packages/google-maps-fleetengine/scripts/fixup_fleetengine_v1_keywords.py index 203629cc4770..1a4c9837d26c 100644 --- a/packages/google-maps-fleetengine/scripts/fixup_fleetengine_v1_keywords.py +++ b/packages/google-maps-fleetengine/scripts/fixup_fleetengine_v1_keywords.py @@ -45,13 +45,11 @@ class fleetengineCallTransformer(cst.CSTTransformer): 'get_vehicle': ('name', 'header', 'current_route_segment_version', 'waypoints_version', ), 'list_vehicles': ('parent', 'vehicle_type_categories', 'header', 'page_size', 'page_token', 'minimum_capacity', 'trip_types', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'vehicle_state', 'on_trip_only', 'filter', 'viewport', ), 'report_billable_trip': ('name', 'country_code', 'platform', 'related_ids', 'solution_type', ), - 'search_fuzzed_vehicles': ('parent', 'pickup_point', 'pickup_radius_meters', 'count', 'minimum_capacity', 'trip_types', 'vehicle_types', 'order_by', 'header', 'dropoff_point', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'include_back_to_back', 'trip_id', 'current_trips_present', 'filter', ), 'search_trips': ('parent', 'header', 'vehicle_id', 'active_trips_only', 'page_size', 'page_token', 'minimum_staleness', ), 'search_vehicles': ('parent', 'pickup_point', 'pickup_radius_meters', 'count', 'minimum_capacity', 'trip_types', 'vehicle_types', 'order_by', 'header', 'dropoff_point', 'maximum_staleness', 'required_attributes', 'required_one_of_attributes', 'required_one_of_attribute_sets', 'include_back_to_back', 'trip_id', 'current_trips_present', 'filter', ), 'update_trip': ('name', 'trip', 'update_mask', 'header', ), 'update_vehicle': ('name', 'vehicle', 'update_mask', 'header', ), 'update_vehicle_attributes': ('name', 'attributes', 'header', ), - 'update_vehicle_location': ('name', 'current_location', 'header', 'current_state', ), } def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: diff --git a/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_trip_service.py b/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_trip_service.py index 2cd839a3006e..f3a3680e2629 100644 --- a/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_trip_service.py +++ b/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_trip_service.py @@ -1129,6 +1129,9 @@ def test_create_trip_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_trip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_trip() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1153,6 +1156,9 @@ def test_create_trip_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_trip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_trip(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1162,6 +1168,41 @@ def test_create_trip_non_empty_request_with_auto_populated_field(): ) +def test_create_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_trip] = mock_rpc + request = {} + client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_create_trip_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1193,6 +1234,52 @@ async def test_create_trip_empty_call_async(): assert args[0] == trip_api.CreateTripRequest() +@pytest.mark.asyncio +async def test_create_trip_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_trip + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_trip + ] = mock_object + + request = {} + await client.create_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_create_trip_async( transport: str = "grpc_asyncio", request_type=trip_api.CreateTripRequest @@ -1334,6 +1421,9 @@ def test_get_trip_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_trip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_trip() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1357,6 +1447,9 @@ def test_get_trip_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_trip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_trip(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1365,6 +1458,41 @@ def test_get_trip_non_empty_request_with_auto_populated_field(): ) +def test_get_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_trip] = mock_rpc + request = {} + client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_get_trip_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1396,6 +1524,50 @@ async def test_get_trip_empty_call_async(): assert args[0] == trip_api.GetTripRequest() +@pytest.mark.asyncio +async def test_get_trip_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_trip + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_trip + ] = mock_object + + request = {} + await client.get_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_get_trip_async( transport: str = "grpc_asyncio", request_type=trip_api.GetTripRequest @@ -1522,6 +1694,9 @@ def test_report_billable_trip_empty_call(): with mock.patch.object( type(client.transport.report_billable_trip), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.report_billable_trip() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1548,6 +1723,9 @@ def test_report_billable_trip_non_empty_request_with_auto_populated_field(): with mock.patch.object( type(client.transport.report_billable_trip), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.report_billable_trip(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1557,6 +1735,45 @@ def test_report_billable_trip_non_empty_request_with_auto_populated_field(): ) +def test_report_billable_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.report_billable_trip in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.report_billable_trip + ] = mock_rpc + request = {} + client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.report_billable_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_report_billable_trip_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1578,6 +1795,52 @@ async def test_report_billable_trip_empty_call_async(): assert args[0] == trip_api.ReportBillableTripRequest() +@pytest.mark.asyncio +async def test_report_billable_trip_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.report_billable_trip + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.report_billable_trip + ] = mock_object + + request = {} + await client.report_billable_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.report_billable_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_report_billable_trip_async( transport: str = "grpc_asyncio", request_type=trip_api.ReportBillableTripRequest @@ -1686,6 +1949,9 @@ def test_search_trips_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_trips), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.search_trips() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1711,6 +1977,9 @@ def test_search_trips_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_trips), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.search_trips(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1721,6 +1990,41 @@ def test_search_trips_non_empty_request_with_auto_populated_field(): ) +def test_search_trips_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_trips in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.search_trips] = mock_rpc + request = {} + client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_trips(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_search_trips_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1744,6 +2048,52 @@ async def test_search_trips_empty_call_async(): assert args[0] == trip_api.SearchTripsRequest() +@pytest.mark.asyncio +async def test_search_trips_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.search_trips + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.search_trips + ] = mock_object + + request = {} + await client.search_trips(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.search_trips(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_search_trips_async( transport: str = "grpc_asyncio", request_type=trip_api.SearchTripsRequest @@ -2056,6 +2406,9 @@ def test_update_trip_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_trip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_trip() call.assert_called() _, args, _ = call.mock_calls[0] @@ -2079,6 +2432,9 @@ def test_update_trip_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_trip), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_trip(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -2087,6 +2443,41 @@ def test_update_trip_non_empty_request_with_auto_populated_field(): ) +def test_update_trip_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = TripServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_trip in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_trip] = mock_rpc + request = {} + client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_update_trip_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -2118,6 +2509,52 @@ async def test_update_trip_empty_call_async(): assert args[0] == trip_api.UpdateTripRequest() +@pytest.mark.asyncio +async def test_update_trip_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = TripServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_trip + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_trip + ] = mock_object + + request = {} + await client.update_trip(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_trip(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_update_trip_async( transport: str = "grpc_asyncio", request_type=trip_api.UpdateTripRequest diff --git a/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py b/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py index 1270199a5271..aa6d3c877fa6 100644 --- a/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py +++ b/packages/google-maps-fleetengine/tests/unit/gapic/fleetengine_v1/test_vehicle_service.py @@ -1165,6 +1165,9 @@ def test_create_vehicle_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_vehicle), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_vehicle() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1189,6 +1192,9 @@ def test_create_vehicle_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.create_vehicle), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.create_vehicle(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1198,6 +1204,41 @@ def test_create_vehicle_non_empty_request_with_auto_populated_field(): ) +def test_create_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_vehicle] = mock_rpc + request = {} + client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.create_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_create_vehicle_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1228,6 +1269,52 @@ async def test_create_vehicle_empty_call_async(): assert args[0] == vehicle_api.CreateVehicleRequest() +@pytest.mark.asyncio +async def test_create_vehicle_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_vehicle + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.create_vehicle + ] = mock_object + + request = {} + await client.create_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.create_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_create_vehicle_async( transport: str = "grpc_asyncio", request_type=vehicle_api.CreateVehicleRequest @@ -1365,6 +1452,9 @@ def test_get_vehicle_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_vehicle), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_vehicle() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1388,6 +1478,9 @@ def test_get_vehicle_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.get_vehicle), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.get_vehicle(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1396,6 +1489,41 @@ def test_get_vehicle_non_empty_request_with_auto_populated_field(): ) +def test_get_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_vehicle] = mock_rpc + request = {} + client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_get_vehicle_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1426,6 +1554,52 @@ async def test_get_vehicle_empty_call_async(): assert args[0] == vehicle_api.GetVehicleRequest() +@pytest.mark.asyncio +async def test_get_vehicle_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_vehicle + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.get_vehicle + ] = mock_object + + request = {} + await client.get_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.get_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_get_vehicle_async( transport: str = "grpc_asyncio", request_type=vehicle_api.GetVehicleRequest @@ -1563,6 +1737,9 @@ def test_update_vehicle_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_vehicle), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_vehicle() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1586,6 +1763,9 @@ def test_update_vehicle_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.update_vehicle), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_vehicle(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1594,6 +1774,41 @@ def test_update_vehicle_non_empty_request_with_auto_populated_field(): ) +def test_update_vehicle_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_vehicle in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_vehicle] = mock_rpc + request = {} + client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_update_vehicle_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1624,6 +1839,52 @@ async def test_update_vehicle_empty_call_async(): assert args[0] == vehicle_api.UpdateVehicleRequest() +@pytest.mark.asyncio +async def test_update_vehicle_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_vehicle + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_vehicle + ] = mock_object + + request = {} + await client.update_vehicle(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_vehicle(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_update_vehicle_async( transport: str = "grpc_asyncio", request_type=vehicle_api.UpdateVehicleRequest @@ -1701,197 +1962,6 @@ def test_update_vehicle_routing_parameters(): assert kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - vehicle_api.UpdateVehicleLocationRequest, - dict, - ], -) -def test_update_vehicle_location(request_type, transport: str = "grpc"): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_location), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = fleetengine.VehicleLocation( - location_sensor=fleetengine.LocationSensor.GPS, - raw_location_sensor=fleetengine.LocationSensor.GPS, - supplemental_location_sensor=fleetengine.LocationSensor.GPS, - road_snapped=True, - ) - response = client.update_vehicle_location(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleLocationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, fleetengine.VehicleLocation) - assert response.location_sensor == fleetengine.LocationSensor.GPS - assert response.raw_location_sensor == fleetengine.LocationSensor.GPS - assert response.supplemental_location_sensor == fleetengine.LocationSensor.GPS - assert response.road_snapped is True - - -def test_update_vehicle_location_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_location), "__call__" - ) as call: - client.update_vehicle_location() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleLocationRequest() - - -def test_update_vehicle_location_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.UpdateVehicleLocationRequest( - name="name_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_location), "__call__" - ) as call: - client.update_vehicle_location(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleLocationRequest( - name="name_value", - ) - - -@pytest.mark.asyncio -async def test_update_vehicle_location_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VehicleServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_location), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - fleetengine.VehicleLocation( - location_sensor=fleetengine.LocationSensor.GPS, - raw_location_sensor=fleetengine.LocationSensor.GPS, - supplemental_location_sensor=fleetengine.LocationSensor.GPS, - road_snapped=True, - ) - ) - response = await client.update_vehicle_location() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.UpdateVehicleLocationRequest() - - -@pytest.mark.asyncio -async def test_update_vehicle_location_async( - transport: str = "grpc_asyncio", - request_type=vehicle_api.UpdateVehicleLocationRequest, -): - client = VehicleServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_location), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - fleetengine.VehicleLocation( - location_sensor=fleetengine.LocationSensor.GPS, - raw_location_sensor=fleetengine.LocationSensor.GPS, - supplemental_location_sensor=fleetengine.LocationSensor.GPS, - road_snapped=True, - ) - ) - response = await client.update_vehicle_location(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.UpdateVehicleLocationRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, fleetengine.VehicleLocation) - assert response.location_sensor == fleetengine.LocationSensor.GPS - assert response.raw_location_sensor == fleetengine.LocationSensor.GPS - assert response.supplemental_location_sensor == fleetengine.LocationSensor.GPS - assert response.road_snapped is True - - -@pytest.mark.asyncio -async def test_update_vehicle_location_async_from_dict(): - await test_update_vehicle_location_async(request_type=dict) - - -def test_update_vehicle_location_routing_parameters(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = vehicle_api.UpdateVehicleLocationRequest(**{"name": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_vehicle_location), "__call__" - ) as call: - call.return_value = fleetengine.VehicleLocation() - client.update_vehicle_location(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] - - @pytest.mark.parametrize( "request_type", [ @@ -1939,6 +2009,9 @@ def test_update_vehicle_attributes_empty_call(): with mock.patch.object( type(client.transport.update_vehicle_attributes), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_vehicle_attributes() call.assert_called() _, args, _ = call.mock_calls[0] @@ -1964,6 +2037,9 @@ def test_update_vehicle_attributes_non_empty_request_with_auto_populated_field() with mock.patch.object( type(client.transport.update_vehicle_attributes), "__call__" ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.update_vehicle_attributes(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -1972,6 +2048,46 @@ def test_update_vehicle_attributes_non_empty_request_with_auto_populated_field() ) +def test_update_vehicle_attributes_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_vehicle_attributes + in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.update_vehicle_attributes + ] = mock_rpc + request = {} + client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.update_vehicle_attributes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_update_vehicle_attributes_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -1995,6 +2111,52 @@ async def test_update_vehicle_attributes_empty_call_async(): assert args[0] == vehicle_api.UpdateVehicleAttributesRequest() +@pytest.mark.asyncio +async def test_update_vehicle_attributes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.update_vehicle_attributes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.update_vehicle_attributes + ] = mock_object + + request = {} + await client.update_vehicle_attributes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.update_vehicle_attributes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_update_vehicle_attributes_async( transport: str = "grpc_asyncio", @@ -2110,6 +2272,9 @@ def test_list_vehicles_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_vehicles), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_vehicles() call.assert_called() _, args, _ = call.mock_calls[0] @@ -2135,6 +2300,9 @@ def test_list_vehicles_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_vehicles), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.list_vehicles(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -2145,6 +2313,41 @@ def test_list_vehicles_non_empty_request_with_auto_populated_field(): ) +def test_list_vehicles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_vehicles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list_vehicles] = mock_rpc + request = {} + client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_vehicles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_list_vehicles_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -2169,6 +2372,52 @@ async def test_list_vehicles_empty_call_async(): assert args[0] == vehicle_api.ListVehiclesRequest() +@pytest.mark.asyncio +async def test_list_vehicles_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_vehicles + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.list_vehicles + ] = mock_object + + request = {} + await client.list_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.list_vehicles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + @pytest.mark.asyncio async def test_list_vehicles_async( transport: str = "grpc_asyncio", request_type=vehicle_api.ListVehiclesRequest @@ -2464,6 +2713,9 @@ def test_search_vehicles_empty_call(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_vehicles), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.search_vehicles() call.assert_called() _, args, _ = call.mock_calls[0] @@ -2489,6 +2741,9 @@ def test_search_vehicles_non_empty_request_with_auto_populated_field(): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.search_vehicles), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) client.search_vehicles(request=request) call.assert_called() _, args, _ = call.mock_calls[0] @@ -2499,6 +2754,41 @@ def test_search_vehicles_non_empty_request_with_auto_populated_field(): ) +def test_search_vehicles_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = VehicleServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.search_vehicles in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.search_vehicles] = mock_rpc + request = {} + client.search_vehicles(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.search_vehicles(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + @pytest.mark.asyncio async def test_search_vehicles_empty_call_async(): # This test is a coverage failsafe to make sure that totally empty calls, @@ -2521,174 +2811,53 @@ async def test_search_vehicles_empty_call_async(): @pytest.mark.asyncio -async def test_search_vehicles_async( - transport: str = "grpc_asyncio", request_type=vehicle_api.SearchVehiclesRequest +async def test_search_vehicles_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - client = VehicleServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_vehicles), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - vehicle_api.SearchVehiclesResponse() + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = VehicleServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - response = await client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - request = vehicle_api.SearchVehiclesRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.SearchVehiclesResponse) - - -@pytest.mark.asyncio -async def test_search_vehicles_async_from_dict(): - await test_search_vehicles_async(request_type=dict) - -def test_search_vehicles_routing_parameters(): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.search_vehicles), "__call__") as call: - call.return_value = vehicle_api.SearchVehiclesResponse() - client.search_vehicles(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == request - - _, _, kw = call.mock_calls[0] - # This test doesn't assert anything useful. - assert kw["metadata"] + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + # Ensure method has been cached + assert ( + client._client._transport.search_vehicles + in client._client._transport._wrapped_methods + ) -@pytest.mark.parametrize( - "request_type", - [ - vehicle_api.SearchVehiclesRequest, - dict, - ], -) -def test_search_fuzzed_vehicles(request_type, transport: str = "grpc"): - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.search_vehicles + ] = mock_object - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_fuzzed_vehicles), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = vehicle_api.SearchVehiclesResponse() - response = client.search_fuzzed_vehicles(request) + request = {} + await client.search_vehicles(request) # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = vehicle_api.SearchVehiclesRequest() - assert args[0] == request + assert mock_object.call_count == 1 - # Establish that the response is the type that we expect. - assert isinstance(response, vehicle_api.SearchVehiclesResponse) + await client.search_vehicles(request) - -def test_search_fuzzed_vehicles_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_fuzzed_vehicles), "__call__" - ) as call: - client.search_fuzzed_vehicles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.SearchVehiclesRequest() - - -def test_search_fuzzed_vehicles_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = VehicleServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = vehicle_api.SearchVehiclesRequest( - parent="parent_value", - trip_id="trip_id_value", - filter="filter_value", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_fuzzed_vehicles), "__call__" - ) as call: - client.search_fuzzed_vehicles(request=request) - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.SearchVehiclesRequest( - parent="parent_value", - trip_id="trip_id_value", - filter="filter_value", - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 @pytest.mark.asyncio -async def test_search_fuzzed_vehicles_empty_call_async(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = VehicleServiceAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_fuzzed_vehicles), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - vehicle_api.SearchVehiclesResponse() - ) - response = await client.search_fuzzed_vehicles() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == vehicle_api.SearchVehiclesRequest() - - -@pytest.mark.asyncio -async def test_search_fuzzed_vehicles_async( +async def test_search_vehicles_async( transport: str = "grpc_asyncio", request_type=vehicle_api.SearchVehiclesRequest ): client = VehicleServiceAsyncClient( @@ -2701,14 +2870,12 @@ async def test_search_fuzzed_vehicles_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_fuzzed_vehicles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.search_vehicles), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( vehicle_api.SearchVehiclesResponse() ) - response = await client.search_fuzzed_vehicles(request) + response = await client.search_vehicles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2721,11 +2888,11 @@ async def test_search_fuzzed_vehicles_async( @pytest.mark.asyncio -async def test_search_fuzzed_vehicles_async_from_dict(): - await test_search_fuzzed_vehicles_async(request_type=dict) +async def test_search_vehicles_async_from_dict(): + await test_search_vehicles_async(request_type=dict) -def test_search_fuzzed_vehicles_routing_parameters(): +def test_search_vehicles_routing_parameters(): client = VehicleServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2735,11 +2902,9 @@ def test_search_fuzzed_vehicles_routing_parameters(): request = vehicle_api.SearchVehiclesRequest(**{"parent": "providers/sample1"}) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.search_fuzzed_vehicles), "__call__" - ) as call: + with mock.patch.object(type(client.transport.search_vehicles), "__call__") as call: call.return_value = vehicle_api.SearchVehiclesResponse() - client.search_fuzzed_vehicles(request) + client.search_vehicles(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2891,11 +3056,9 @@ def test_vehicle_service_base_transport(): "create_vehicle", "get_vehicle", "update_vehicle", - "update_vehicle_location", "update_vehicle_attributes", "list_vehicles", "search_vehicles", - "search_fuzzed_vehicles", ) for method in methods: with pytest.raises(NotImplementedError): From 524cd1ea815839983f803502d3b8e0dece40544a Mon Sep 17 00:00:00 2001 From: "owlbot-bootstrapper[bot]" <104649659+owlbot-bootstrapper[bot]@users.noreply.github.com> Date: Wed, 8 May 2024 12:13:32 -0400 Subject: [PATCH 3/3] feat: add initial files for google.maps.routeoptimization.v1 (#12670) Source-Link: https://github.com/googleapis/googleapis-gen/commit/cae62d4fb1b6b7d695fe5f6de6711c85ddf0abd8 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLW1hcHMtcm91dGVvcHRpbWl6YXRpb24vLk93bEJvdC55YW1sIiwiaCI6ImNhZTYyZDRmYjFiNmI3ZDY5NWZlNWY2ZGU2NzExYzg1ZGRmMGFiZDgifQ== PiperOrigin-RevId: 631097475 --------- Co-authored-by: Owlbot Bootstrapper <owlbot-bootstrapper[bot]@users.noreply.github.com> Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: ohmayr <omairnaveed@ymail.com> --- .../.OwlBot.yaml | 18 + .../google-maps-routeoptimization/.coveragerc | 13 + .../google-maps-routeoptimization/.flake8 | 33 + .../google-maps-routeoptimization/.gitignore | 63 + .../.repo-metadata.json | 17 + .../CHANGELOG.md | 1 + .../CODE_OF_CONDUCT.md | 95 + .../CONTRIBUTING.rst | 271 ++ .../google-maps-routeoptimization/LICENSE | 202 + .../google-maps-routeoptimization/MANIFEST.in | 25 + .../google-maps-routeoptimization/README.rst | 108 + .../docs/CHANGELOG.md | 1 + .../docs/README.rst | 1 + .../docs/_static/custom.css | 20 + .../docs/_templates/layout.html | 50 + .../docs/conf.py | 384 ++ .../docs/index.rst | 23 + .../docs/multiprocessing.rst | 7 + .../route_optimization.rst | 6 + .../docs/routeoptimization_v1/services_.rst | 6 + .../docs/routeoptimization_v1/types_.rst | 6 + .../google/maps/routeoptimization/__init__.py | 85 + .../maps/routeoptimization/gapic_version.py | 16 + .../google/maps/routeoptimization/py.typed | 2 + .../maps/routeoptimization_v1/__init__.py | 83 + .../routeoptimization_v1/gapic_metadata.json | 58 + .../routeoptimization_v1/gapic_version.py | 16 + .../google/maps/routeoptimization_v1/py.typed | 2 + .../routeoptimization_v1/services/__init__.py | 15 + .../services/route_optimization/__init__.py | 22 + .../route_optimization/async_client.py | 588 +++ .../services/route_optimization/client.py | 992 ++++ .../route_optimization/transports/__init__.py | 36 + .../route_optimization/transports/base.py | 200 + .../route_optimization/transports/grpc.py | 381 ++ .../transports/grpc_asyncio.py | 408 ++ .../route_optimization/transports/rest.py | 631 +++ .../routeoptimization_v1/types/__init__.py | 72 + .../types/route_optimization_service.py | 4029 +++++++++++++++++ .../google-maps-routeoptimization/mypy.ini | 3 + .../google-maps-routeoptimization/noxfile.py | 428 ++ ...optimization_batch_optimize_tours_async.py | 63 + ..._optimization_batch_optimize_tours_sync.py | 63 + ...route_optimization_optimize_tours_async.py | 52 + ..._route_optimization_optimize_tours_sync.py | 52 + ...data_google.maps.routeoptimization.v1.json | 321 ++ .../scripts/decrypt-secrets.sh | 46 + .../fixup_routeoptimization_v1_keywords.py | 177 + .../google-maps-routeoptimization/setup.py | 95 + .../testing/.gitignore | 3 + .../testing/constraints-3.10.txt | 6 + .../testing/constraints-3.11.txt | 6 + .../testing/constraints-3.12.txt | 6 + .../testing/constraints-3.7.txt | 10 + .../testing/constraints-3.8.txt | 6 + .../testing/constraints-3.9.txt | 6 + .../tests/__init__.py | 15 + .../tests/unit/__init__.py | 15 + .../tests/unit/gapic/__init__.py | 15 + .../gapic/routeoptimization_v1/__init__.py | 15 + .../test_route_optimization.py | 3276 ++++++++++++++ 61 files changed, 13665 insertions(+) create mode 100644 packages/google-maps-routeoptimization/.OwlBot.yaml create mode 100644 packages/google-maps-routeoptimization/.coveragerc create mode 100644 packages/google-maps-routeoptimization/.flake8 create mode 100644 packages/google-maps-routeoptimization/.gitignore create mode 100644 packages/google-maps-routeoptimization/.repo-metadata.json create mode 100644 packages/google-maps-routeoptimization/CHANGELOG.md create mode 100644 packages/google-maps-routeoptimization/CODE_OF_CONDUCT.md create mode 100644 packages/google-maps-routeoptimization/CONTRIBUTING.rst create mode 100644 packages/google-maps-routeoptimization/LICENSE create mode 100644 packages/google-maps-routeoptimization/MANIFEST.in create mode 100644 packages/google-maps-routeoptimization/README.rst create mode 120000 packages/google-maps-routeoptimization/docs/CHANGELOG.md create mode 120000 packages/google-maps-routeoptimization/docs/README.rst create mode 100644 packages/google-maps-routeoptimization/docs/_static/custom.css create mode 100644 packages/google-maps-routeoptimization/docs/_templates/layout.html create mode 100644 packages/google-maps-routeoptimization/docs/conf.py create mode 100644 packages/google-maps-routeoptimization/docs/index.rst create mode 100644 packages/google-maps-routeoptimization/docs/multiprocessing.rst create mode 100644 packages/google-maps-routeoptimization/docs/routeoptimization_v1/route_optimization.rst create mode 100644 packages/google-maps-routeoptimization/docs/routeoptimization_v1/services_.rst create mode 100644 packages/google-maps-routeoptimization/docs/routeoptimization_v1/types_.rst create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization/__init__.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization/py.typed create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/__init__.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_metadata.json create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/py.typed create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/__init__.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/__init__.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/__init__.py create mode 100644 packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py create mode 100644 packages/google-maps-routeoptimization/mypy.ini create mode 100644 packages/google-maps-routeoptimization/noxfile.py create mode 100644 packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py create mode 100644 packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py create mode 100644 packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py create mode 100644 packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py create mode 100644 packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json create mode 100755 packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh create mode 100644 packages/google-maps-routeoptimization/scripts/fixup_routeoptimization_v1_keywords.py create mode 100644 packages/google-maps-routeoptimization/setup.py create mode 100644 packages/google-maps-routeoptimization/testing/.gitignore create mode 100644 packages/google-maps-routeoptimization/testing/constraints-3.10.txt create mode 100644 packages/google-maps-routeoptimization/testing/constraints-3.11.txt create mode 100644 packages/google-maps-routeoptimization/testing/constraints-3.12.txt create mode 100644 packages/google-maps-routeoptimization/testing/constraints-3.7.txt create mode 100644 packages/google-maps-routeoptimization/testing/constraints-3.8.txt create mode 100644 packages/google-maps-routeoptimization/testing/constraints-3.9.txt create mode 100644 packages/google-maps-routeoptimization/tests/__init__.py create mode 100644 packages/google-maps-routeoptimization/tests/unit/__init__.py create mode 100644 packages/google-maps-routeoptimization/tests/unit/gapic/__init__.py create mode 100644 packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/__init__.py create mode 100644 packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py diff --git a/packages/google-maps-routeoptimization/.OwlBot.yaml b/packages/google-maps-routeoptimization/.OwlBot.yaml new file mode 100644 index 000000000000..767e511e21bc --- /dev/null +++ b/packages/google-maps-routeoptimization/.OwlBot.yaml @@ -0,0 +1,18 @@ +# 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. + +deep-copy-regex: + - source: /google/maps/routeoptimization/(v.*)/.*-py + dest: /owl-bot-staging/google-maps-routeoptimization/$1 +api-name: google-maps-routeoptimization diff --git a/packages/google-maps-routeoptimization/.coveragerc b/packages/google-maps-routeoptimization/.coveragerc new file mode 100644 index 000000000000..aa5ba4d9b1f4 --- /dev/null +++ b/packages/google-maps-routeoptimization/.coveragerc @@ -0,0 +1,13 @@ +[run] +branch = True + +[report] +show_missing = True +omit = + google/maps/routeoptimization/__init__.py + google/maps/routeoptimization/gapic_version.py +exclude_lines = + # Re-enable the standard pragma + pragma: NO COVER + # Ignore debug-only repr + def __repr__ diff --git a/packages/google-maps-routeoptimization/.flake8 b/packages/google-maps-routeoptimization/.flake8 new file mode 100644 index 000000000000..87f6e408c47d --- /dev/null +++ b/packages/google-maps-routeoptimization/.flake8 @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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. + +# Generated by synthtool. DO NOT EDIT! +[flake8] +ignore = E203, E231, E266, E501, W503 +exclude = + # Exclude generated code. + **/proto/** + **/gapic/** + **/services/** + **/types/** + *_pb2.py + + # Standard linting exemptions. + **/.nox/** + __pycache__, + .git, + *.pyc, + conf.py diff --git a/packages/google-maps-routeoptimization/.gitignore b/packages/google-maps-routeoptimization/.gitignore new file mode 100644 index 000000000000..b4243ced74e4 --- /dev/null +++ b/packages/google-maps-routeoptimization/.gitignore @@ -0,0 +1,63 @@ +*.py[cod] +*.sw[op] + +# C extensions +*.so + +# Packages +*.egg +*.egg-info +dist +build +eggs +.eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg +lib +lib64 +__pycache__ + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.nox +.cache +.pytest_cache + + +# Mac +.DS_Store + +# JetBrains +.idea + +# VS Code +.vscode + +# emacs +*~ + +# Built documentation +docs/_build +bigquery/docs/generated +docs.metadata + +# Virtual environment +env/ + +# Test logs +coverage.xml +*sponge_log.xml + +# System test environment variables. +system_tests/local_test_setup + +# Make sure a generated file isn't accidentally committed. +pylintrc +pylintrc.test diff --git a/packages/google-maps-routeoptimization/.repo-metadata.json b/packages/google-maps-routeoptimization/.repo-metadata.json new file mode 100644 index 000000000000..56fc3a0e87b6 --- /dev/null +++ b/packages/google-maps-routeoptimization/.repo-metadata.json @@ -0,0 +1,17 @@ +{ + "name": "google-maps-routeoptimization", + "name_pretty": "Route Optimization API", + "api_description": "he Route Optimization API assigns tasks and routes to a vehicle fleet, optimizing against the objectives and constraints that you supply for your transportation goals.", + "product_documentation": "https://developers.google.com/maps/documentation/route-optimization", + "client_documentation": "https://googleapis.dev/python/google-maps-routeoptimization/latest", + "issue_tracker": "https://issuetracker.google.com/issues/new?component=1546507", + "release_level": "preview", + "language": "python", + "library_type": "GAPIC_AUTO", + "repo": "googleapis/google-cloud-python", + "distribution_name": "google-maps-routeoptimization", + "api_id": "routeoptimization.googleapis.com", + "default_version": "v1", + "codeowner_team": "", + "api_shortname": "routeoptimization" +} diff --git a/packages/google-maps-routeoptimization/CHANGELOG.md b/packages/google-maps-routeoptimization/CHANGELOG.md new file mode 100644 index 000000000000..5ddad421e08f --- /dev/null +++ b/packages/google-maps-routeoptimization/CHANGELOG.md @@ -0,0 +1 @@ +# Changelog \ No newline at end of file diff --git a/packages/google-maps-routeoptimization/CODE_OF_CONDUCT.md b/packages/google-maps-routeoptimization/CODE_OF_CONDUCT.md new file mode 100644 index 000000000000..039f43681204 --- /dev/null +++ b/packages/google-maps-routeoptimization/CODE_OF_CONDUCT.md @@ -0,0 +1,95 @@ +<!-- # Generated by synthtool. DO NOT EDIT! !--> +# Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, or to ban temporarily or permanently any +contributor for other behaviors that they deem inappropriate, threatening, +offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +This Code of Conduct also applies outside the project spaces when the Project +Steward has a reasonable belief that an individual's behavior may have a +negative impact on the project or its community. + +## Conflict Resolution + +We do not believe that all conflict is bad; healthy debate and disagreement +often yield positive results. However, it is never okay to be disrespectful or +to engage in behavior that violates the project’s code of conduct. + +If you see someone violating the code of conduct, you are encouraged to address +the behavior directly with those involved. Many issues can be resolved quickly +and easily, and this gives people more control over the outcome of their +dispute. If you are unable to resolve the matter for any reason, or if the +behavior is threatening or harassing, report it. We are dedicated to providing +an environment where participants feel welcome and safe. + + +Reports should be directed to *googleapis-stewards@google.com*, the +Project Steward(s) for *Google Cloud Client Libraries*. It is the Project Steward’s duty to +receive and address reported violations of the code of conduct. They will then +work with a committee consisting of representatives from the Open Source +Programs Office and the Google Open Source Strategy team. If for any reason you +are uncomfortable reaching out to the Project Steward, please email +opensource@google.com. + +We will investigate every complaint, but you may not receive a direct response. +We will use our discretion in determining when and how to follow up on reported +incidents, which may range from not taking action to permanent expulsion from +the project and project-sponsored spaces. We will notify the accused of the +report and provide them an opportunity to discuss it before any action is taken. +The identity of the reporter will be omitted from the details of the report +supplied to the accused. In potentially harmful situations, such as ongoing +harassment or threats to anyone's safety, we may take action without notice. + +## Attribution + +This Code of Conduct is adapted from the Contributor Covenant, version 1.4, +available at +https://www.contributor-covenant.org/version/1/4/code-of-conduct.html \ No newline at end of file diff --git a/packages/google-maps-routeoptimization/CONTRIBUTING.rst b/packages/google-maps-routeoptimization/CONTRIBUTING.rst new file mode 100644 index 000000000000..72ac94e37ab9 --- /dev/null +++ b/packages/google-maps-routeoptimization/CONTRIBUTING.rst @@ -0,0 +1,271 @@ +.. Generated by synthtool. DO NOT EDIT! +############ +Contributing +############ + +#. **Please sign one of the contributor license agreements below.** +#. Fork the repo, develop and test your code changes, add docs. +#. Make sure that your commit messages clearly describe the changes. +#. Send a pull request. (Please Read: `Faster Pull Request Reviews`_) + +.. _Faster Pull Request Reviews: https://github.com/kubernetes/community/blob/master/contributors/guide/pull-requests.md#best-practices-for-faster-reviews + +.. contents:: Here are some guidelines for hacking on the Google Cloud Client libraries. + +*************** +Adding Features +*************** + +In order to add a feature: + +- The feature must be documented in both the API and narrative + documentation. + +- The feature must work fully on the following CPython versions: + 3.7, 3.8, 3.9, 3.10, 3.11 and 3.12 on both UNIX and Windows. + +- The feature must not add unnecessary dependencies (where + "unnecessary" is of course subjective, but new dependencies should + be discussed). + +**************************** +Using a Development Checkout +**************************** + +You'll have to create a development environment using a Git checkout: + +- While logged into your GitHub account, navigate to the + ``google-cloud-python`` `repo`_ on GitHub. + +- Fork and clone the ``google-cloud-python`` repository to your GitHub account by + clicking the "Fork" button. + +- Clone your fork of ``google-cloud-python`` from your GitHub account to your local + computer, substituting your account username and specifying the destination + as ``hack-on-google-cloud-python``. E.g.:: + + $ cd ${HOME} + $ git clone git@github.com:USERNAME/google-cloud-python.git hack-on-google-cloud-python + $ cd hack-on-google-cloud-python + # Configure remotes such that you can pull changes from the googleapis/google-cloud-python + # repository into your local repository. + $ git remote add upstream git@github.com:googleapis/google-cloud-python.git + # fetch and merge changes from upstream into main + $ git fetch upstream + $ git merge upstream/main + +Now your local repo is set up such that you will push changes to your GitHub +repo, from which you can submit a pull request. + +To work on the codebase and run the tests, we recommend using ``nox``, +but you can also use a ``virtualenv`` of your own creation. + +.. _repo: https://github.com/googleapis/google-cloud-python + +Using ``nox`` +============= + +We use `nox <https://nox.readthedocs.io/en/latest/>`__ to instrument our tests. + +- To test your changes, run unit tests with ``nox``:: + $ nox -s unit + +- To run a single unit test:: + + $ nox -s unit-3.12 -- -k <name of test> + + + .. note:: + + The unit tests and system tests are described in the + ``noxfile.py`` files in each directory. + +.. nox: https://pypi.org/project/nox/ + +***************************************** +I'm getting weird errors... Can you help? +***************************************** + +If the error mentions ``Python.h`` not being found, +install ``python-dev`` and try again. +On Debian/Ubuntu:: + + $ sudo apt-get install python-dev + +************ +Coding Style +************ +- We use the automatic code formatter ``black``. You can run it using + the nox session ``blacken``. This will eliminate many lint errors. Run via:: + + $ nox -s blacken + +- PEP8 compliance is required, with exceptions defined in the linter configuration. + If you have ``nox`` installed, you can test that you have not introduced + any non-compliant code via:: + + $ nox -s lint + +- In order to make ``nox -s lint`` run faster, you can set some environment + variables:: + + export GOOGLE_CLOUD_TESTING_REMOTE="upstream" + export GOOGLE_CLOUD_TESTING_BRANCH="main" + + By doing this, you are specifying the location of the most up-to-date + version of ``google-cloud-python``. The + remote name ``upstream`` should point to the official ``googleapis`` + checkout and the branch should be the default branch on that remote (``main``). + +- This repository contains configuration for the + `pre-commit <https://pre-commit.com/>`__ tool, which automates checking + our linters during a commit. If you have it installed on your ``$PATH``, + you can enable enforcing those checks via: + +.. code-block:: bash + + $ pre-commit install + pre-commit installed at .git/hooks/pre-commit + +Exceptions to PEP8: + +- Many unit tests use a helper method, ``_call_fut`` ("FUT" is short for + "Function-Under-Test"), which is PEP8-incompliant, but more readable. + Some also use a local variable, ``MUT`` (short for "Module-Under-Test"). + +******************** +Running System Tests +******************** + +- To run system tests, you can execute:: + + # Run all system tests + $ nox -s system + + # Run a single system test + $ nox -s system-3.12 -- -k <name of test> + + + .. note:: + + System tests are only configured to run under Python 3.8, 3.9, 3.10, 3.11 and 3.12. + For expediency, we do not run them in older versions of Python 3. + + This alone will not run the tests. You'll need to change some local + auth settings and change some configuration in your project to + run all the tests. + +- System tests will be run against an actual project. You should use local credentials from gcloud when possible. See `Best practices for application authentication <https://cloud.google.com/docs/authentication/best-practices-applications#local_development_and_testing_with_the>`__. Some tests require a service account. For those tests see `Authenticating as a service account <https://cloud.google.com/docs/authentication/production>`__. + +************* +Test Coverage +************* + +- The codebase *must* have 100% test statement coverage after each commit. + You can test coverage via ``nox -s cover``. + +****************************************************** +Documentation Coverage and Building HTML Documentation +****************************************************** + +If you fix a bug, and the bug requires an API or behavior modification, all +documentation in this package which references that API or behavior must be +changed to reflect the bug fix, ideally in the same commit that fixes the bug +or adds the feature. + +Build the docs via: + + $ nox -s docs + +************************* +Samples and code snippets +************************* + +Code samples and snippets live in the `samples/` catalogue. Feel free to +provide more examples, but make sure to write tests for those examples. +Each folder containing example code requires its own `noxfile.py` script +which automates testing. If you decide to create a new folder, you can +base it on the `samples/snippets` folder (providing `noxfile.py` and +the requirements files). + +The tests will run against a real Google Cloud Project, so you should +configure them just like the System Tests. + +- To run sample tests, you can execute:: + + # Run all tests in a folder + $ cd samples/snippets + $ nox -s py-3.8 + + # Run a single sample test + $ cd samples/snippets + $ nox -s py-3.8 -- -k <name of test> + +******************************************** +Note About ``README`` as it pertains to PyPI +******************************************** + +The `description on PyPI`_ for the project comes directly from the +``README``. Due to the reStructuredText (``rst``) parser used by +PyPI, relative links which will work on GitHub (e.g. ``CONTRIBUTING.rst`` +instead of +``https://github.com/googleapis/google-cloud-python/blob/main/CONTRIBUTING.rst``) +may cause problems creating links or rendering the description. + +.. _description on PyPI: https://pypi.org/project/google-maps-routeoptimization + + +************************* +Supported Python Versions +************************* + +We support: + +- `Python 3.7`_ +- `Python 3.8`_ +- `Python 3.9`_ +- `Python 3.10`_ +- `Python 3.11`_ +- `Python 3.12`_ + +.. _Python 3.7: https://docs.python.org/3.7/ +.. _Python 3.8: https://docs.python.org/3.8/ +.. _Python 3.9: https://docs.python.org/3.9/ +.. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ +.. _Python 3.12: https://docs.python.org/3.12/ + + +Supported versions can be found in our ``noxfile.py`` `config`_. + +.. _config: https://github.com/googleapis/google-cloud-python/blob/main/packages/google-maps-routeoptimization/noxfile.py + + +********** +Versioning +********** + +This library follows `Semantic Versioning`_. + +.. _Semantic Versioning: http://semver.org/ + +Some packages are currently in major version zero (``0.y.z``), which means that +anything may change at any time and the public API should not be considered +stable. + +****************************** +Contributor License Agreements +****************************** + +Before we can accept your pull requests you'll need to sign a Contributor +License Agreement (CLA): + +- **If you are an individual writing original source code** and **you own the + intellectual property**, then you'll need to sign an + `individual CLA <https://developers.google.com/open-source/cla/individual>`__. +- **If you work for a company that wants to allow you to contribute your work**, + then you'll need to sign a + `corporate CLA <https://developers.google.com/open-source/cla/corporate>`__. + +You can sign these electronically (just scroll to the bottom). After that, +we'll be able to accept your pull requests. diff --git a/packages/google-maps-routeoptimization/LICENSE b/packages/google-maps-routeoptimization/LICENSE new file mode 100644 index 000000000000..d64569567334 --- /dev/null +++ b/packages/google-maps-routeoptimization/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/google-maps-routeoptimization/MANIFEST.in b/packages/google-maps-routeoptimization/MANIFEST.in new file mode 100644 index 000000000000..e0a66705318e --- /dev/null +++ b/packages/google-maps-routeoptimization/MANIFEST.in @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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. + +# Generated by synthtool. DO NOT EDIT! +include README.rst LICENSE +recursive-include google *.json *.proto py.typed +recursive-include tests * +global-exclude *.py[co] +global-exclude __pycache__ + +# Exclude scripts for samples readmegen +prune scripts/readme-gen diff --git a/packages/google-maps-routeoptimization/README.rst b/packages/google-maps-routeoptimization/README.rst new file mode 100644 index 000000000000..8b1300294995 --- /dev/null +++ b/packages/google-maps-routeoptimization/README.rst @@ -0,0 +1,108 @@ +Python Client for Route Optimization API +======================================== + +|preview| |pypi| |versions| + +`Route Optimization API`_: he Route Optimization API assigns tasks and routes to a vehicle fleet, optimizing against the objectives and constraints that you supply for your transportation goals. + +- `Client Library Documentation`_ +- `Product Documentation`_ + +.. |preview| image:: https://img.shields.io/badge/support-preview-orange.svg + :target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels +.. |pypi| image:: https://img.shields.io/pypi/v/google-maps-routeoptimization.svg + :target: https://pypi.org/project/google-maps-routeoptimization/ +.. |versions| image:: https://img.shields.io/pypi/pyversions/google-maps-routeoptimization.svg + :target: https://pypi.org/project/google-maps-routeoptimization/ +.. _Route Optimization API: https://developers.google.com/maps/documentation/route-optimization +.. _Client Library Documentation: https://googleapis.dev/python/google-maps-routeoptimization/latest +.. _Product Documentation: https://developers.google.com/maps/documentation/route-optimization + +Quick Start +----------- + +In order to use this library, you first need to go through the following steps: + +1. `Select or create a Cloud Platform project.`_ +2. `Enable billing for your project.`_ +3. `Enable the Route Optimization API.`_ +4. `Setup Authentication.`_ + +.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project +.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project +.. _Enable the Route Optimization API.: https://developers.google.com/maps/documentation/route-optimization +.. _Setup Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html + +Installation +~~~~~~~~~~~~ + +Install this library in a virtual environment using `venv`_. `venv`_ is a tool that +creates isolated Python environments. These isolated environments can have separate +versions of Python packages, which allows you to isolate one project's dependencies +from the dependencies of other projects. + +With `venv`_, it's possible to install this library without needing system +install permissions, and without clashing with the installed system +dependencies. + +.. _`venv`: https://docs.python.org/3/library/venv.html + + +Code samples and snippets +~~~~~~~~~~~~~~~~~~~~~~~~~ + +Code samples and snippets live in the `samples/`_ folder. + +.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization/samples + + +Supported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^ +Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of +Python. + +Python >= 3.7 + +.. _active: https://devguide.python.org/devcycle/#in-development-main-branch +.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches + +Unsupported Python Versions +^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Python <= 3.6 + +If you are using an `end-of-life`_ +version of Python, we recommend that you update as soon as possible to an actively supported version. + +.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches + +Mac/Linux +^^^^^^^^^ + +.. code-block:: console + + python3 -m venv <your-env> + source <your-env>/bin/activate + pip install google-maps-routeoptimization + + +Windows +^^^^^^^ + +.. code-block:: console + + py -m venv <your-env> + .\<your-env>\Scripts\activate + pip install google-maps-routeoptimization + +Next Steps +~~~~~~~~~~ + +- Read the `Client Library Documentation`_ for Route Optimization API + to see other available methods on the client. +- Read the `Route Optimization API Product documentation`_ to learn + more about the product and see How-to Guides. +- View this `README`_ to see the full list of Cloud + APIs that we cover. + +.. _Route Optimization API Product documentation: https://developers.google.com/maps/documentation/route-optimization +.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst diff --git a/packages/google-maps-routeoptimization/docs/CHANGELOG.md b/packages/google-maps-routeoptimization/docs/CHANGELOG.md new file mode 120000 index 000000000000..04c99a55caae --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/CHANGELOG.md @@ -0,0 +1 @@ +../CHANGELOG.md \ No newline at end of file diff --git a/packages/google-maps-routeoptimization/docs/README.rst b/packages/google-maps-routeoptimization/docs/README.rst new file mode 120000 index 000000000000..89a0106941ff --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/README.rst @@ -0,0 +1 @@ +../README.rst \ No newline at end of file diff --git a/packages/google-maps-routeoptimization/docs/_static/custom.css b/packages/google-maps-routeoptimization/docs/_static/custom.css new file mode 100644 index 000000000000..b0a295464b23 --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/_static/custom.css @@ -0,0 +1,20 @@ +div#python2-eol { + border-color: red; + border-width: medium; +} + +/* Ensure minimum width for 'Parameters' / 'Returns' column */ +dl.field-list > dt { + min-width: 100px +} + +/* Insert space between methods for readability */ +dl.method { + padding-top: 10px; + padding-bottom: 10px +} + +/* Insert empty space between classes */ +dl.class { + padding-bottom: 50px +} diff --git a/packages/google-maps-routeoptimization/docs/_templates/layout.html b/packages/google-maps-routeoptimization/docs/_templates/layout.html new file mode 100644 index 000000000000..6316a537f72b --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/_templates/layout.html @@ -0,0 +1,50 @@ + +{% extends "!layout.html" %} +{%- block content %} +{%- if theme_fixed_sidebar|lower == 'true' %} + <div class="document"> + {{ sidebar() }} + {%- block document %} + <div class="documentwrapper"> + {%- if render_sidebar %} + <div class="bodywrapper"> + {%- endif %} + + {%- block relbar_top %} + {%- if theme_show_relbar_top|tobool %} + <div class="related top"> + + {{- rellink_markup () }} + </div> + {%- endif %} + {% endblock %} + + <div class="body" role="main"> + <div class="admonition" id="python2-eol"> + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please + visit <a href="https://cloud.google.com/python/docs/python2-sunset/">Python 2 support on Google Cloud</a>. + </div> + {% block body %} {% endblock %} + </div> + + {%- block relbar_bottom %} + {%- if theme_show_relbar_bottom|tobool %} + <div class="related bottom"> + + {{- rellink_markup () }} + </div> + {%- endif %} + {% endblock %} + + {%- if render_sidebar %} + </div> + {%- endif %} + </div> + {%- endblock %} + <div class="clearer"></div> + </div> +{%- else %} +{{ super() }} +{%- endif %} +{%- endblock %} diff --git a/packages/google-maps-routeoptimization/docs/conf.py b/packages/google-maps-routeoptimization/docs/conf.py new file mode 100644 index 000000000000..380aec7e8ec2 --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/conf.py @@ -0,0 +1,384 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 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. +# +# google-maps-routeoptimization documentation build configuration file +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import os +import shlex +import sys + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +sys.path.insert(0, os.path.abspath("..")) + +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + +__version__ = "" + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +needs_sphinx = "1.5.5" + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.autosummary", + "sphinx.ext.intersphinx", + "sphinx.ext.coverage", + "sphinx.ext.doctest", + "sphinx.ext.napoleon", + "sphinx.ext.todo", + "sphinx.ext.viewcode", + "recommonmark", +] + +# autodoc/autosummary flags +autoclass_content = "both" +autodoc_default_options = {"members": True} +autosummary_generate = True + + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# source_suffix = ['.rst', '.md'] +source_suffix = [".rst", ".md"] + +# The encoding of source files. +# source_encoding = 'utf-8-sig' + +# The root toctree document. +root_doc = "index" + +# General information about the project. +project = "google-maps-routeoptimization" +copyright = "2019, Google" +author = "Google APIs" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The full version, including alpha/beta/rc tags. +release = __version__ +# The short X.Y version. +version = ".".join(release.split(".")[0:2]) + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +# today = '' +# Else, today_fmt is used as the format for a strftime call. +# today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = [ + "_build", + "**/.nox/**/*", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +# add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +# add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +# show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# A list of ignored prefixes for module index sorting. +# modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built documents. +# keep_warnings = False + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = True + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = "alabaster" + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +html_theme_options = { + "description": "Google Cloud Client Libraries for google-maps-routeoptimization", + "github_user": "googleapis", + "github_repo": "google-cloud-python", + "github_banner": True, + "font_family": "'Roboto', Georgia, sans", + "head_font_family": "'Roboto', Georgia, serif", + "code_font_family": "'Roboto Mono', 'Consolas', monospace", +} + +# Add any paths that contain custom themes here, relative to this directory. +# html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# "<project> v<release> documentation". +# html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +# html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +# html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# Add any extra paths that contain custom files (such as robots.txt or +# .htaccess) here, relative to this directory. These files are copied +# directly to the root of the documentation. +# html_extra_path = [] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +# html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +# html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +# html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +# html_additional_pages = {} + +# If false, no module index is generated. +# html_domain_indices = True + +# If false, no index is generated. +# html_use_index = True + +# If true, the index is split into individual pages for each letter. +# html_split_index = False + +# If true, links to the reST sources are added to the pages. +# html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +# html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +# html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a <link> tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +# html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +# html_file_suffix = None + +# Language to be used for generating the HTML full-text search index. +# Sphinx supports the following languages: +# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' +# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' +# html_search_language = 'en' + +# A dictionary with options for the search language support, empty by default. +# Now only 'ja' uses this config value +# html_search_options = {'type': 'default'} + +# The name of a javascript file (relative to the configuration directory) that +# implements a search results scorer. If empty, the default will be used. +# html_search_scorer = 'scorer.js' + +# Output file base name for HTML help builder. +htmlhelp_basename = "google-maps-routeoptimization-doc" + +# -- Options for warnings ------------------------------------------------------ + + +suppress_warnings = [ + # Temporarily suppress this to avoid "more than one target found for + # cross-reference" warning, which are intractable for us to avoid while in + # a mono-repo. + # See https://github.com/sphinx-doc/sphinx/blob + # /2a65ffeef5c107c19084fabdd706cdff3f52d93c/sphinx/domains/python.py#L843 + "ref.python" +] + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + #'preamble': '', + # Latex figure (float) alignment + #'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + root_doc, + "google-maps-routeoptimization.tex", + "google-maps-routeoptimization Documentation", + author, + "manual", + ) +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +# latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +# latex_use_parts = False + +# If true, show page references after internal links. +# latex_show_pagerefs = False + +# If true, show URL addresses after external links. +# latex_show_urls = False + +# Documents to append as an appendix to all manuals. +# latex_appendices = [] + +# If false, no module index is generated. +# latex_domain_indices = True + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + root_doc, + "google-maps-routeoptimization", + "google-maps-routeoptimization Documentation", + [author], + 1, + ) +] + +# If true, show URL addresses after external links. +# man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + root_doc, + "google-maps-routeoptimization", + "google-maps-routeoptimization Documentation", + author, + "google-maps-routeoptimization", + "google-maps-routeoptimization Library", + "APIs", + ) +] + +# Documents to append as an appendix to all manuals. +# texinfo_appendices = [] + +# If false, no module index is generated. +# texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +# texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +# texinfo_no_detailmenu = False + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = { + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ( + "https://googleapis.dev/python/google-api-core/latest/", + None, + ), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), + "protobuf": ("https://googleapis.dev/python/protobuf/latest/", None), +} + + +# Napoleon settings +napoleon_google_docstring = True +napoleon_numpy_docstring = True +napoleon_include_private_with_doc = False +napoleon_include_special_with_doc = True +napoleon_use_admonition_for_examples = False +napoleon_use_admonition_for_notes = False +napoleon_use_admonition_for_references = False +napoleon_use_ivar = False +napoleon_use_param = True +napoleon_use_rtype = True diff --git a/packages/google-maps-routeoptimization/docs/index.rst b/packages/google-maps-routeoptimization/docs/index.rst new file mode 100644 index 000000000000..d6c4d4692c52 --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/index.rst @@ -0,0 +1,23 @@ +.. include:: README.rst + +.. include:: multiprocessing.rst + + +API Reference +------------- +.. toctree:: + :maxdepth: 2 + + routeoptimization_v1/services_ + routeoptimization_v1/types_ + + +Changelog +--------- + +For a list of all ``google-maps-routeoptimization`` releases: + +.. toctree:: + :maxdepth: 2 + + CHANGELOG diff --git a/packages/google-maps-routeoptimization/docs/multiprocessing.rst b/packages/google-maps-routeoptimization/docs/multiprocessing.rst new file mode 100644 index 000000000000..536d17b2ea65 --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/multiprocessing.rst @@ -0,0 +1,7 @@ +.. note:: + + Because this client uses :mod:`grpc` library, it is safe to + share instances across threads. In multiprocessing scenarios, the best + practice is to create client instances *after* the invocation of + :func:`os.fork` by :class:`multiprocessing.pool.Pool` or + :class:`multiprocessing.Process`. diff --git a/packages/google-maps-routeoptimization/docs/routeoptimization_v1/route_optimization.rst b/packages/google-maps-routeoptimization/docs/routeoptimization_v1/route_optimization.rst new file mode 100644 index 000000000000..17445dae6122 --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/routeoptimization_v1/route_optimization.rst @@ -0,0 +1,6 @@ +RouteOptimization +----------------------------------- + +.. automodule:: google.maps.routeoptimization_v1.services.route_optimization + :members: + :inherited-members: diff --git a/packages/google-maps-routeoptimization/docs/routeoptimization_v1/services_.rst b/packages/google-maps-routeoptimization/docs/routeoptimization_v1/services_.rst new file mode 100644 index 000000000000..818250f8aa4b --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/routeoptimization_v1/services_.rst @@ -0,0 +1,6 @@ +Services for Google Maps Routeoptimization v1 API +================================================= +.. toctree:: + :maxdepth: 2 + + route_optimization diff --git a/packages/google-maps-routeoptimization/docs/routeoptimization_v1/types_.rst b/packages/google-maps-routeoptimization/docs/routeoptimization_v1/types_.rst new file mode 100644 index 000000000000..44fe4e6164f4 --- /dev/null +++ b/packages/google-maps-routeoptimization/docs/routeoptimization_v1/types_.rst @@ -0,0 +1,6 @@ +Types for Google Maps Routeoptimization v1 API +============================================== + +.. automodule:: google.maps.routeoptimization_v1.types + :members: + :show-inheritance: diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization/__init__.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization/__init__.py new file mode 100644 index 000000000000..185073f9abae --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization/__init__.py @@ -0,0 +1,85 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from google.maps.routeoptimization import gapic_version as package_version + +__version__ = package_version.__version__ + + +from google.maps.routeoptimization_v1.services.route_optimization.async_client import ( + RouteOptimizationAsyncClient, +) +from google.maps.routeoptimization_v1.services.route_optimization.client import ( + RouteOptimizationClient, +) +from google.maps.routeoptimization_v1.types.route_optimization_service import ( + AggregatedMetrics, + BatchOptimizeToursMetadata, + BatchOptimizeToursRequest, + BatchOptimizeToursResponse, + BreakRule, + DataFormat, + DistanceLimit, + GcsDestination, + GcsSource, + InjectedSolutionConstraint, + InputConfig, + Location, + OptimizeToursRequest, + OptimizeToursResponse, + OptimizeToursValidationError, + OutputConfig, + Shipment, + ShipmentModel, + ShipmentRoute, + ShipmentTypeIncompatibility, + ShipmentTypeRequirement, + SkippedShipment, + TimeWindow, + TransitionAttributes, + Vehicle, + Waypoint, +) + +__all__ = ( + "RouteOptimizationClient", + "RouteOptimizationAsyncClient", + "AggregatedMetrics", + "BatchOptimizeToursMetadata", + "BatchOptimizeToursRequest", + "BatchOptimizeToursResponse", + "BreakRule", + "DistanceLimit", + "GcsDestination", + "GcsSource", + "InjectedSolutionConstraint", + "InputConfig", + "Location", + "OptimizeToursRequest", + "OptimizeToursResponse", + "OptimizeToursValidationError", + "OutputConfig", + "Shipment", + "ShipmentModel", + "ShipmentRoute", + "ShipmentTypeIncompatibility", + "ShipmentTypeRequirement", + "SkippedShipment", + "TimeWindow", + "TransitionAttributes", + "Vehicle", + "Waypoint", + "DataFormat", +) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization/py.typed b/packages/google-maps-routeoptimization/google/maps/routeoptimization/py.typed new file mode 100644 index 000000000000..9471c714bbf3 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routeoptimization package uses inline types. diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/__init__.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/__init__.py new file mode 100644 index 000000000000..053f46b064a7 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/__init__.py @@ -0,0 +1,83 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from google.maps.routeoptimization_v1 import gapic_version as package_version + +__version__ = package_version.__version__ + + +from .services.route_optimization import ( + RouteOptimizationAsyncClient, + RouteOptimizationClient, +) +from .types.route_optimization_service import ( + AggregatedMetrics, + BatchOptimizeToursMetadata, + BatchOptimizeToursRequest, + BatchOptimizeToursResponse, + BreakRule, + DataFormat, + DistanceLimit, + GcsDestination, + GcsSource, + InjectedSolutionConstraint, + InputConfig, + Location, + OptimizeToursRequest, + OptimizeToursResponse, + OptimizeToursValidationError, + OutputConfig, + Shipment, + ShipmentModel, + ShipmentRoute, + ShipmentTypeIncompatibility, + ShipmentTypeRequirement, + SkippedShipment, + TimeWindow, + TransitionAttributes, + Vehicle, + Waypoint, +) + +__all__ = ( + "RouteOptimizationAsyncClient", + "AggregatedMetrics", + "BatchOptimizeToursMetadata", + "BatchOptimizeToursRequest", + "BatchOptimizeToursResponse", + "BreakRule", + "DataFormat", + "DistanceLimit", + "GcsDestination", + "GcsSource", + "InjectedSolutionConstraint", + "InputConfig", + "Location", + "OptimizeToursRequest", + "OptimizeToursResponse", + "OptimizeToursValidationError", + "OutputConfig", + "RouteOptimizationClient", + "Shipment", + "ShipmentModel", + "ShipmentRoute", + "ShipmentTypeIncompatibility", + "ShipmentTypeRequirement", + "SkippedShipment", + "TimeWindow", + "TransitionAttributes", + "Vehicle", + "Waypoint", +) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_metadata.json b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_metadata.json new file mode 100644 index 000000000000..386551edc86c --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_metadata.json @@ -0,0 +1,58 @@ + { + "comment": "This file maps proto services/RPCs to the corresponding library clients/methods", + "language": "python", + "libraryPackage": "google.maps.routeoptimization_v1", + "protoPackage": "google.maps.routeoptimization.v1", + "schema": "1.0", + "services": { + "RouteOptimization": { + "clients": { + "grpc": { + "libraryClient": "RouteOptimizationClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + }, + "grpc-async": { + "libraryClient": "RouteOptimizationAsyncClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + }, + "rest": { + "libraryClient": "RouteOptimizationClient", + "rpcs": { + "BatchOptimizeTours": { + "methods": [ + "batch_optimize_tours" + ] + }, + "OptimizeTours": { + "methods": [ + "optimize_tours" + ] + } + } + } + } + } + } +} diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py new file mode 100644 index 000000000000..558c8aab67c5 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/py.typed b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/py.typed new file mode 100644 index 000000000000..9471c714bbf3 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-maps-routeoptimization package uses inline types. diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/__init__.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/__init__.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/__init__.py new file mode 100644 index 000000000000..1a436d7d988f --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from .async_client import RouteOptimizationAsyncClient +from .client import RouteOptimizationClient + +__all__ = ( + "RouteOptimizationClient", + "RouteOptimizationAsyncClient", +) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py new file mode 100644 index 000000000000..d04e12ddae7c --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/async_client.py @@ -0,0 +1,588 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import functools +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry_async as retries +from google.api_core.client_options import ClientOptions +from google.auth import credentials as ga_credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routeoptimization_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.maps.routeoptimization_v1.types import route_optimization_service + +from .client import RouteOptimizationClient +from .transports.base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport +from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport + + +class RouteOptimizationAsyncClient: + """A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + """ + + _client: RouteOptimizationClient + + # Copy defaults from the synchronous client for use here. + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = RouteOptimizationClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + _DEFAULT_ENDPOINT_TEMPLATE = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE + _DEFAULT_UNIVERSE = RouteOptimizationClient._DEFAULT_UNIVERSE + + common_billing_account_path = staticmethod( + RouteOptimizationClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RouteOptimizationClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod(RouteOptimizationClient.common_folder_path) + parse_common_folder_path = staticmethod( + RouteOptimizationClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + RouteOptimizationClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RouteOptimizationClient.parse_common_organization_path + ) + common_project_path = staticmethod(RouteOptimizationClient.common_project_path) + parse_common_project_path = staticmethod( + RouteOptimizationClient.parse_common_project_path + ) + common_location_path = staticmethod(RouteOptimizationClient.common_location_path) + parse_common_location_path = staticmethod( + RouteOptimizationClient.parse_common_location_path + ) + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RouteOptimizationAsyncClient: The constructed client. + """ + return RouteOptimizationClient.from_service_account_info.__func__(RouteOptimizationAsyncClient, info, *args, **kwargs) # type: ignore + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RouteOptimizationAsyncClient: The constructed client. + """ + return RouteOptimizationClient.from_service_account_file.__func__(RouteOptimizationAsyncClient, filename, *args, **kwargs) # type: ignore + + from_service_account_json = from_service_account_file + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[ClientOptions] = None + ): + """Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + return RouteOptimizationClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> RouteOptimizationTransport: + """Returns the transport used by the client instance. + + Returns: + RouteOptimizationTransport: The transport used by the client instance. + """ + return self._client.transport + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._client._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used + by the client instance. + """ + return self._client._universe_domain + + get_transport_class = functools.partial( + type(RouteOptimizationClient).get_transport_class, type(RouteOptimizationClient) + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + RouteOptimizationTransport, + Callable[..., RouteOptimizationTransport], + ] + ] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the route optimization async client. + + Args: + 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. + transport (Optional[Union[str,RouteOptimizationTransport,Callable[..., RouteOptimizationTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport to use. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RouteOptimizationTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = RouteOptimizationClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def optimize_tours( + self, + request: Optional[ + Union[route_optimization_service.OptimizeToursRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> route_optimization_service.OptimizeToursResponse: + r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + async def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = await client.optimize_tours(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routeoptimization_v1.types.OptimizeToursRequest, dict]]): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + retry (google.api_core.retry_async.AsyncRetry): 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: + google.maps.routeoptimization_v1.types.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, route_optimization_service.OptimizeToursRequest): + request = route_optimization_service.OptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.optimize_tours + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def batch_optimize_tours( + self, + request: Optional[ + Union[route_optimization_service.BatchOptimizeToursRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + async def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest, dict]]): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + retry (google.api_core.retry_async.AsyncRetry): 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: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.maps.routeoptimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in + the Long Running Operation after the operation is + complete. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, route_optimization_service.BatchOptimizeToursRequest + ): + request = route_optimization_service.BatchOptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.batch_optimize_tours + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + route_optimization_service.BatchOptimizeToursResponse, + metadata_type=route_optimization_service.BatchOptimizeToursMetadata, + ) + + # Done; return the response. + return response + + async def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry_async.AsyncRetry): 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: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self) -> "RouteOptimizationAsyncClient": + return self + + async def __aexit__(self, exc_type, exc, tb): + await self.transport.close() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("RouteOptimizationAsyncClient",) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py new file mode 100644 index 000000000000..fa1a87108b7a --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/client.py @@ -0,0 +1,992 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routeoptimization_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.longrunning import operations_pb2 # type: ignore + +from google.maps.routeoptimization_v1.types import route_optimization_service + +from .transports.base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport +from .transports.grpc import RouteOptimizationGrpcTransport +from .transports.grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport +from .transports.rest import RouteOptimizationRestTransport + + +class RouteOptimizationClientMeta(type): + """Metaclass for the RouteOptimization client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[RouteOptimizationTransport]] + _transport_registry["grpc"] = RouteOptimizationGrpcTransport + _transport_registry["grpc_asyncio"] = RouteOptimizationGrpcAsyncIOTransport + _transport_registry["rest"] = RouteOptimizationRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RouteOptimizationTransport]: + """Returns an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RouteOptimizationClient(metaclass=RouteOptimizationClientMeta): + """A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Converts api endpoint to mTLS endpoint. + + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "routeoptimization.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "routeoptimization.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RouteOptimizationClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_info(info) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + RouteOptimizationClient: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RouteOptimizationTransport: + """Returns the transport used by the client instance. + + Returns: + RouteOptimizationTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path( + folder: str, + ) -> str: + """Returns a fully-qualified folder string.""" + return "folders/{folder}".format( + folder=folder, + ) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P<folder>.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path( + organization: str, + ) -> str: + """Returns a fully-qualified organization string.""" + return "organizations/{organization}".format( + organization=organization, + ) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P<organization>.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path( + project: str, + ) -> str: + """Returns a fully-qualified project string.""" + return "projects/{project}".format( + project=project, + ) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P<project>.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path( + project: str, + location: str, + ) -> str: + """Returns a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.ClientOptions] = None + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = RouteOptimizationClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + @staticmethod + def _compare_universes( + client_universe: str, credentials: ga_credentials.Credentials + ) -> bool: + """Returns True iff the universe domains used by the client and credentials match. + + Args: + client_universe (str): The universe domain configured via the client options. + credentials (ga_credentials.Credentials): The credentials being used in the client. + + Returns: + bool: True iff client_universe matches the universe in credentials. + + Raises: + ValueError: when client_universe does not match the universe in credentials. + """ + + default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + credentials_universe = getattr(credentials, "universe_domain", default_universe) + + if client_universe != credentials_universe: + raise ValueError( + "The configured universe domain " + f"({client_universe}) does not match the universe domain " + f"found in the credentials ({credentials_universe}). " + "If you haven't configured the universe domain explicitly, " + f"`{default_universe}` is the default." + ) + return True + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + self._is_universe_domain_valid = ( + self._is_universe_domain_valid + or RouteOptimizationClient._compare_universes( + self.universe_domain, self.transport._credentials + ) + ) + return self._is_universe_domain_valid + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + RouteOptimizationTransport, + Callable[..., RouteOptimizationTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the route optimization client. + + Args: + 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. + transport (Optional[Union[str,RouteOptimizationTransport,Callable[..., RouteOptimizationTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the RouteOptimizationTransport constructor. + If set to None, a transport is chosen automatically. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + 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're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = RouteOptimizationClient._read_environment_variables() + self._client_cert_source = RouteOptimizationClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RouteOptimizationClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, RouteOptimizationTransport) + if transport_provided: + # transport is a RouteOptimizationTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(RouteOptimizationTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or RouteOptimizationClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[RouteOptimizationTransport], + Callable[..., RouteOptimizationTransport], + ] = ( + type(self).get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RouteOptimizationTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + def optimize_tours( + self, + request: Optional[ + Union[route_optimization_service.OptimizeToursRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> route_optimization_service.OptimizeToursResponse: + r"""Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = client.optimize_tours(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routeoptimization_v1.types.OptimizeToursRequest, dict]): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + 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: + google.maps.routeoptimization_v1.types.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, route_optimization_service.OptimizeToursRequest): + request = route_optimization_service.OptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.optimize_tours] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def batch_optimize_tours( + self, + request: Optional[ + Union[route_optimization_service.BatchOptimizeToursRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.maps import routeoptimization_v1 + + def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest, dict]): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + 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: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.maps.routeoptimization_v1.types.BatchOptimizeToursResponse` Response to a BatchOptimizeToursRequest. This is returned in + the Long Running Operation after the operation is + complete. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, route_optimization_service.BatchOptimizeToursRequest + ): + request = route_optimization_service.BatchOptimizeToursRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.batch_optimize_tours] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + route_optimization_service.BatchOptimizeToursResponse, + metadata_type=route_optimization_service.BatchOptimizeToursMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "RouteOptimizationClient": + return self + + def __exit__(self, type, value, traceback): + """Releases underlying transport's resources. + + .. warning:: + ONLY use as a context manager if the transport is NOT shared + with other clients! Exiting the with block will CLOSE the transport + and may cause errors in other clients! + """ + self.transport.close() + + def get_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("RouteOptimizationClient",) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py new file mode 100644 index 000000000000..f31a38591814 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import RouteOptimizationTransport +from .grpc import RouteOptimizationGrpcTransport +from .grpc_asyncio import RouteOptimizationGrpcAsyncIOTransport +from .rest import RouteOptimizationRestInterceptor, RouteOptimizationRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[RouteOptimizationTransport]] +_transport_registry["grpc"] = RouteOptimizationGrpcTransport +_transport_registry["grpc_asyncio"] = RouteOptimizationGrpcAsyncIOTransport +_transport_registry["rest"] = RouteOptimizationRestTransport + +__all__ = ( + "RouteOptimizationTransport", + "RouteOptimizationGrpcTransport", + "RouteOptimizationGrpcAsyncIOTransport", + "RouteOptimizationRestTransport", + "RouteOptimizationRestInterceptor", +) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py new file mode 100644 index 000000000000..14ce5e5ead36 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/base.py @@ -0,0 +1,200 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 abc +from typing import Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, operations_v1 +from google.api_core import retry as retries +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.maps.routeoptimization_v1 import gapic_version as package_version +from google.maps.routeoptimization_v1.types import route_optimization_service + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class RouteOptimizationTransport(abc.ABC): + """Abstract transport class for RouteOptimization.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "routeoptimization.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'routeoptimization.googleapis.com'). + 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise core_exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = google.auth.load_credentials_from_file( + credentials_file, **scopes_kwargs, quota_project_id=quota_project_id + ) + elif credentials is None: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.optimize_tours: gapic_v1.method.wrap_method( + self.optimize_tours, + default_retry=retries.Retry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.batch_optimize_tours: gapic_v1.method.wrap_method( + self.batch_optimize_tours, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def operations_client(self): + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + Union[ + route_optimization_service.OptimizeToursResponse, + Awaitable[route_optimization_service.OptimizeToursResponse], + ], + ]: + raise NotImplementedError() + + @property + def batch_optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("RouteOptimizationTransport",) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py new file mode 100644 index 000000000000..990c2022c4e5 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc.py @@ -0,0 +1,381 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from typing import Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers, operations_v1 +import google.auth # type: ignore +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore + +from google.maps.routeoptimization_v1.types import route_optimization_service + +from .base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport + + +class RouteOptimizationGrpcTransport(RouteOptimizationTransport): + """gRPC backend transport for RouteOptimization. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "routeoptimization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'routeoptimization.googleapis.com'). + 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. + This argument is ignored if a ``channel`` instance is provided. + 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 a ``channel`` instance is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if a ``channel`` instance is provided. + channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, grpc.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @classmethod + def create_channel( + cls, + host: str = "routeoptimization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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 mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service.""" + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsClient(self.grpc_channel) + + # Return the client from cache. + return self._operations_client + + @property + def optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + route_optimization_service.OptimizeToursResponse, + ]: + r"""Return a callable for the optimize tours method over gRPC. + + Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + Returns: + Callable[[~.OptimizeToursRequest], + ~.OptimizeToursResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "optimize_tours" not in self._stubs: + self._stubs["optimize_tours"] = self.grpc_channel.unary_unary( + "/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours", + request_serializer=route_optimization_service.OptimizeToursRequest.serialize, + response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, + ) + return self._stubs["optimize_tours"] + + @property + def batch_optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], operations_pb2.Operation + ]: + r"""Return a callable for the batch optimize tours method over gRPC. + + Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + Returns: + Callable[[~.BatchOptimizeToursRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_optimize_tours" not in self._stubs: + self._stubs["batch_optimize_tours"] = self.grpc_channel.unary_unary( + "/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours", + request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_optimize_tours"] + + def close(self): + self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("RouteOptimizationGrpcTransport",) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py new file mode 100644 index 000000000000..2dbabda76ff1 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/grpc_asyncio.py @@ -0,0 +1,408 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +from google.api_core import retry_async as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.longrunning import operations_pb2 # type: ignore +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.maps.routeoptimization_v1.types import route_optimization_service + +from .base import DEFAULT_CLIENT_INFO, RouteOptimizationTransport +from .grpc import RouteOptimizationGrpcTransport + + +class RouteOptimizationGrpcAsyncIOTransport(RouteOptimizationTransport): + """gRPC AsyncIO backend transport for RouteOptimization. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "routeoptimization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + host (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this 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`. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + quota_project_id=quota_project_id, + default_scopes=cls.AUTH_SCOPES, + scopes=scopes, + default_host=cls.DEFAULT_HOST, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "routeoptimization.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, + api_mtls_endpoint: Optional[str] = None, + client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + ssl_channel_credentials: Optional[grpc.ChannelCredentials] = 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, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'routeoptimization.googleapis.com'). + 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. + This argument is ignored if a ``channel`` instance is provided. + 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 a ``channel`` instance is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): + A ``Channel`` instance through which to make calls, or a Callable + that constructs and returns one. If set to None, ``self.create_channel`` + is used to create the channel. If a Callable is given, it will be called + with the same arguments as used in ``self.create_channel``. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or application default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for the grpc channel. It is ignored if a ``channel`` instance is provided. + client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): + A callback to provide client certificate bytes and private key bytes, + both in PEM format. It is used to configure a mutual TLS channel. It is + ignored if a ``channel`` instance or ``ssl_channel_credentials`` 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're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._grpc_channel = None + self._ssl_channel_credentials = ssl_channel_credentials + self._stubs: Dict[str, Callable] = {} + self._operations_client: Optional[operations_v1.OperationsAsyncClient] = None + + if api_mtls_endpoint: + warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) + if client_cert_source: + warnings.warn("client_cert_source is deprecated", DeprecationWarning) + + if isinstance(channel, aio.Channel): + # Ignore credentials if a channel was passed. + credentials = False + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + else: + if api_mtls_endpoint: + host = api_mtls_endpoint + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + self._ssl_channel_credentials = SslCredentials().ssl_credentials + + else: + if client_cert_source_for_mtls and not ssl_channel_credentials: + cert, key = client_cert_source_for_mtls() + self._ssl_channel_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + + # The base transport sets the host, credentials and scopes + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + if not self._grpc_channel: + # initialize with the provided callable or the default channel + channel_init = channel or type(self).create_channel + self._grpc_channel = channel_init( + self._host, + # use the credentials which are saved + credentials=self._credentials, + # Set ``credentials_file`` to ``None`` here as + # the credentials that we saved earlier should be used. + credentials_file=None, + scopes=self._scopes, + ssl_credentials=self._ssl_channel_credentials, + quota_project_id=quota_project_id, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Wrap messages. This must be done after self._grpc_channel exists + self._prep_wrapped_messages(client_info) + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Quick check: Only create a new client if we do not already have one. + if self._operations_client is None: + self._operations_client = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self._operations_client + + @property + def optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + Awaitable[route_optimization_service.OptimizeToursResponse], + ]: + r"""Return a callable for the optimize tours method over gRPC. + + Sends an ``OptimizeToursRequest`` containing a ``ShipmentModel`` + and returns an ``OptimizeToursResponse`` containing + ``ShipmentRoute``\ s, which are a set of routes to be performed + by vehicles minimizing the overall cost. + + A ``ShipmentModel`` model consists mainly of ``Shipment``\ s + that need to be carried out and ``Vehicle``\ s that can be used + to transport the ``Shipment``\ s. The ``ShipmentRoute``\ s + assign ``Shipment``\ s to ``Vehicle``\ s. More specifically, + they assign a series of ``Visit``\ s to each vehicle, where a + ``Visit`` corresponds to a ``VisitRequest``, which is a pickup + or delivery for a ``Shipment``. + + The goal is to provide an assignment of ``ShipmentRoute``\ s to + ``Vehicle``\ s that minimizes the total cost where cost has many + components defined in the ``ShipmentModel``. + + Returns: + Callable[[~.OptimizeToursRequest], + Awaitable[~.OptimizeToursResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "optimize_tours" not in self._stubs: + self._stubs["optimize_tours"] = self.grpc_channel.unary_unary( + "/google.maps.routeoptimization.v1.RouteOptimization/OptimizeTours", + request_serializer=route_optimization_service.OptimizeToursRequest.serialize, + response_deserializer=route_optimization_service.OptimizeToursResponse.deserialize, + ) + return self._stubs["optimize_tours"] + + @property + def batch_optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the batch optimize tours method over gRPC. + + Optimizes vehicle tours for one or more ``OptimizeToursRequest`` + messages as a batch. + + This method is a Long Running Operation (LRO). The inputs for + optimization (``OptimizeToursRequest`` messages) and outputs + (``OptimizeToursResponse`` messages) are read/written from/to + Cloud Storage in user-specified format. Like the + ``OptimizeTours`` method, each ``OptimizeToursRequest`` contains + a ``ShipmentModel`` and returns an ``OptimizeToursResponse`` + containing ``ShipmentRoute``\ s, which are a set of routes to be + performed by vehicles minimizing the overall cost. + + Returns: + Callable[[~.BatchOptimizeToursRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "batch_optimize_tours" not in self._stubs: + self._stubs["batch_optimize_tours"] = self.grpc_channel.unary_unary( + "/google.maps.routeoptimization.v1.RouteOptimization/BatchOptimizeTours", + request_serializer=route_optimization_service.BatchOptimizeToursRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["batch_optimize_tours"] + + def _prep_wrapped_messages(self, client_info): + """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" + self._wrapped_methods = { + self.optimize_tours: gapic_v1.method_async.wrap_method( + self.optimize_tours, + default_retry=retries.AsyncRetry( + initial=1.0, + maximum=10.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=3600.0, + ), + default_timeout=3600.0, + client_info=client_info, + ), + self.batch_optimize_tours: gapic_v1.method_async.wrap_method( + self.batch_optimize_tours, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + return self.grpc_channel.close() + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + +__all__ = ("RouteOptimizationGrpcAsyncIOTransport",) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py new file mode 100644 index 000000000000..b92db0e9f025 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/services/route_optimization/transports/rest.py @@ -0,0 +1,631 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 Any, 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, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + + +from google.longrunning import operations_pb2 # type: ignore + +from google.maps.routeoptimization_v1.types import route_optimization_service + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .base import RouteOptimizationTransport + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=requests_version, +) + + +class RouteOptimizationRestInterceptor: + """Interceptor for RouteOptimization. + + 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 RouteOptimizationRestTransport. + + .. code-block:: python + class MyCustomRouteOptimizationInterceptor(RouteOptimizationRestInterceptor): + def pre_batch_optimize_tours(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_batch_optimize_tours(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_optimize_tours(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_optimize_tours(self, response): + logging.log(f"Received response: {response}") + return response + + transport = RouteOptimizationRestTransport(interceptor=MyCustomRouteOptimizationInterceptor()) + client = RouteOptimizationClient(transport=transport) + + + """ + + def pre_batch_optimize_tours( + self, + request: route_optimization_service.BatchOptimizeToursRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + route_optimization_service.BatchOptimizeToursRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for batch_optimize_tours + + Override in a subclass to manipulate the request or metadata + before they are sent to the RouteOptimization server. + """ + return request, metadata + + def post_batch_optimize_tours( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for batch_optimize_tours + + Override in a subclass to manipulate the response + after it is returned by the RouteOptimization server but before + it is returned to user code. + """ + return response + + def pre_optimize_tours( + self, + request: route_optimization_service.OptimizeToursRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[ + route_optimization_service.OptimizeToursRequest, Sequence[Tuple[str, str]] + ]: + """Pre-rpc interceptor for optimize_tours + + Override in a subclass to manipulate the request or metadata + before they are sent to the RouteOptimization server. + """ + return request, metadata + + def post_optimize_tours( + self, response: route_optimization_service.OptimizeToursResponse + ) -> route_optimization_service.OptimizeToursResponse: + """Post-rpc interceptor for optimize_tours + + Override in a subclass to manipulate the response + after it is returned by the RouteOptimization server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[operations_pb2.GetOperationRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the RouteOptimization server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the RouteOptimization server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class RouteOptimizationRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RouteOptimizationRestInterceptor + + +class RouteOptimizationRestTransport(RouteOptimizationTransport): + """REST backend transport for RouteOptimization. + + A service for optimizing vehicle tours. + + Validity of certain types of fields: + + - ``google.protobuf.Timestamp`` + + - Times are in Unix time: seconds since + 1970-01-01T00:00:00+00:00. + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.protobuf.Duration`` + + - seconds must be in [0, 253402300799], i.e. in + [1970-01-01T00:00:00+00:00, 9999-12-31T23:59:59+00:00]. + - nanos must be unset or set to 0. + + - ``google.type.LatLng`` + + - latitude must be in [-90.0, 90.0]. + - longitude must be in [-180.0, 180.0]. + - at least one of latitude and longitude must be non-zero. + + 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 = "routeoptimization.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[RouteOptimizationRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'routeoptimization.googleapis.com'). + 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("^(?P<scheme>http(?:s)?://)?(?P<host>.*)$", 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 RouteOptimizationRestInterceptor() + 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]]] = { + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ], + } + + 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="v1", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _BatchOptimizeTours(RouteOptimizationRestStub): + def __hash__(self): + return hash("BatchOptimizeTours") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: route_optimization_service.BatchOptimizeToursRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the batch optimize tours method over HTTP. + + Args: + request (~.route_optimization_service.BatchOptimizeToursRequest): + The request object. Request to batch optimize tours as an asynchronous + operation. Each input file should contain one + ``OptimizeToursRequest``, and each output file will + contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. + All the input and output files should be under the same + project. + 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": "/v1/{parent=projects/*/locations/*}:batchOptimizeTours", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*}:batchOptimizeTours", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_batch_optimize_tours( + request, metadata + ) + pb_request = route_optimization_service.BatchOptimizeToursRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + 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_batch_optimize_tours(resp) + return resp + + class _OptimizeTours(RouteOptimizationRestStub): + def __hash__(self): + return hash("OptimizeTours") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @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: route_optimization_service.OptimizeToursRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> route_optimization_service.OptimizeToursResponse: + r"""Call the optimize tours method over HTTP. + + Args: + request (~.route_optimization_service.OptimizeToursRequest): + The request object. Request to be given to a tour + optimization solver which defines the + shipment model to solve as well as + optimization parameters. + 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: + ~.route_optimization_service.OptimizeToursResponse: + Response after solving a tour + optimization problem containing the + routes followed by each vehicle, the + shipments which have been skipped and + the overall cost of the solution. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*}:optimizeTours", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*}:optimizeTours", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_optimize_tours(request, metadata) + pb_request = route_optimization_service.OptimizeToursRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], 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"], + 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 = route_optimization_service.OptimizeToursResponse() + pb_resp = route_optimization_service.OptimizeToursResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_optimize_tours(resp) + return resp + + @property + def batch_optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.BatchOptimizeToursRequest], 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._BatchOptimizeTours(self._session, self._host, self._interceptor) # type: ignore + + @property + def optimize_tours( + self, + ) -> Callable[ + [route_optimization_service.OptimizeToursRequest], + route_optimization_service.OptimizeToursResponse, + ]: + # 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._OptimizeTours(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_operation(self): + return self._GetOperation(self._session, self._host, self._interceptor) # type: ignore + + class _GetOperation(RouteOptimizationRestStub): + def __call__( + self, + request: operations_pb2.GetOperationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the get operation method over HTTP. + + Args: + request (operations_pb2.GetOperationRequest): + The request object for GetOperation method. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + operations_pb2.Operation: Response from GetOperation method. + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{name=projects/*/locations/*/operations/*}", + }, + ] + + request, metadata = self._interceptor.pre_get_operation(request, metadata) + request_kwargs = json_format.MessageToDict(request) + transcoded_request = path_template.transcode(http_options, **request_kwargs) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads(json.dumps(transcoded_request["query_params"])) + + # 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), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + resp = operations_pb2.Operation() + resp = json_format.Parse(response.content.decode("utf-8"), resp) + resp = self._interceptor.post_get_operation(resp) + return resp + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("RouteOptimizationRestTransport",) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/__init__.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/__init__.py new file mode 100644 index 000000000000..88b09e715f9d --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/__init__.py @@ -0,0 +1,72 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from .route_optimization_service import ( + AggregatedMetrics, + BatchOptimizeToursMetadata, + BatchOptimizeToursRequest, + BatchOptimizeToursResponse, + BreakRule, + DataFormat, + DistanceLimit, + GcsDestination, + GcsSource, + InjectedSolutionConstraint, + InputConfig, + Location, + OptimizeToursRequest, + OptimizeToursResponse, + OptimizeToursValidationError, + OutputConfig, + Shipment, + ShipmentModel, + ShipmentRoute, + ShipmentTypeIncompatibility, + ShipmentTypeRequirement, + SkippedShipment, + TimeWindow, + TransitionAttributes, + Vehicle, + Waypoint, +) + +__all__ = ( + "AggregatedMetrics", + "BatchOptimizeToursMetadata", + "BatchOptimizeToursRequest", + "BatchOptimizeToursResponse", + "BreakRule", + "DistanceLimit", + "GcsDestination", + "GcsSource", + "InjectedSolutionConstraint", + "InputConfig", + "Location", + "OptimizeToursRequest", + "OptimizeToursResponse", + "OptimizeToursValidationError", + "OutputConfig", + "Shipment", + "ShipmentModel", + "ShipmentRoute", + "ShipmentTypeIncompatibility", + "ShipmentTypeRequirement", + "SkippedShipment", + "TimeWindow", + "TransitionAttributes", + "Vehicle", + "Waypoint", + "DataFormat", +) diff --git a/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py new file mode 100644 index 000000000000..f83a834bca15 --- /dev/null +++ b/packages/google-maps-routeoptimization/google/maps/routeoptimization_v1/types/route_optimization_service.py @@ -0,0 +1,4029 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.maps.routeoptimization.v1", + manifest={ + "DataFormat", + "BatchOptimizeToursRequest", + "BatchOptimizeToursResponse", + "BatchOptimizeToursMetadata", + "OptimizeToursRequest", + "OptimizeToursResponse", + "ShipmentModel", + "Shipment", + "ShipmentTypeIncompatibility", + "ShipmentTypeRequirement", + "Vehicle", + "TimeWindow", + "DistanceLimit", + "TransitionAttributes", + "Waypoint", + "Location", + "BreakRule", + "ShipmentRoute", + "SkippedShipment", + "AggregatedMetrics", + "InjectedSolutionConstraint", + "OptimizeToursValidationError", + "InputConfig", + "OutputConfig", + "GcsSource", + "GcsDestination", + }, +) + + +class DataFormat(proto.Enum): + r"""Data formats for input and output files. + + Values: + DATA_FORMAT_UNSPECIFIED (0): + Invalid value, format must not be + UNSPECIFIED. + JSON (1): + JavaScript Object Notation. + PROTO_TEXT (2): + Protocol Buffers text format. See + https://protobuf.dev/reference/protobuf/textformat-spec/ + """ + DATA_FORMAT_UNSPECIFIED = 0 + JSON = 1 + PROTO_TEXT = 2 + + +class BatchOptimizeToursRequest(proto.Message): + r"""Request to batch optimize tours as an asynchronous operation. Each + input file should contain one ``OptimizeToursRequest``, and each + output file will contain one ``OptimizeToursResponse``. The request + contains information to read/write and parse the files. All the + input and output files should be under the same project. + + Attributes: + parent (str): + Required. Target project and location to make a call. + + Format: + + - ``projects/{project-id}`` + - ``projects/{project-id}/locations/{location-id}`` + + If no location is specified, a region will be chosen + automatically. + model_configs (MutableSequence[google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest.AsyncModelConfig]): + Required. Input/Output information each + purchase model, such as file paths and data + formats. + """ + + class AsyncModelConfig(proto.Message): + r"""Information for solving one optimization model + asynchronously. + + Attributes: + display_name (str): + Optional. User defined model name, can be + used as alias by users to keep track of models. + input_config (google.maps.routeoptimization_v1.types.InputConfig): + Required. Information about the input model. + output_config (google.maps.routeoptimization_v1.types.OutputConfig): + Required. The desired output location + information. + """ + + display_name: str = proto.Field( + proto.STRING, + number=1, + ) + input_config: "InputConfig" = proto.Field( + proto.MESSAGE, + number=2, + message="InputConfig", + ) + output_config: "OutputConfig" = proto.Field( + proto.MESSAGE, + number=3, + message="OutputConfig", + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + model_configs: MutableSequence[AsyncModelConfig] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=AsyncModelConfig, + ) + + +class BatchOptimizeToursResponse(proto.Message): + r"""Response to a ``BatchOptimizeToursRequest``. This is returned in the + Long Running Operation after the operation is complete. + + """ + + +class BatchOptimizeToursMetadata(proto.Message): + r"""Operation metadata for ``BatchOptimizeToursRequest`` calls.""" + + +class OptimizeToursRequest(proto.Message): + r"""Request to be given to a tour optimization solver which + defines the shipment model to solve as well as optimization + parameters. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. Target project or location to make a call. + + Format: + + - ``projects/{project-id}`` + - ``projects/{project-id}/locations/{location-id}`` + + If no location is specified, a region will be chosen + automatically. + timeout (google.protobuf.duration_pb2.Duration): + If this timeout is set, the server returns a + response before the timeout period has elapsed + or the server deadline for synchronous requests + is reached, whichever is sooner. + + For asynchronous requests, the server will + generate a solution (if possible) before the + timeout has elapsed. + model (google.maps.routeoptimization_v1.types.ShipmentModel): + Shipment model to solve. + solving_mode (google.maps.routeoptimization_v1.types.OptimizeToursRequest.SolvingMode): + By default, the solving mode is ``DEFAULT_SOLVE`` (0). + search_mode (google.maps.routeoptimization_v1.types.OptimizeToursRequest.SearchMode): + Search mode used to solve the request. + injected_first_solution_routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + Guide the optimization algorithm in finding a first solution + that is similar to a previous solution. + + The model is constrained when the first solution is built. + Any shipments not performed on a route are implicitly + skipped in the first solution, but they may be performed in + successive solutions. + + The solution must satisfy some basic validity assumptions: + + - for all routes, ``vehicle_index`` must be in range and + not be duplicated. + - for all visits, ``shipment_index`` and + ``visit_request_index`` must be in range. + - a shipment may only be referenced on one route. + - the pickup of a pickup-delivery shipment must be + performed before the delivery. + - no more than one pickup alternative or delivery + alternative of a shipment may be performed. + - for all routes, times are increasing (i.e., + ``vehicle_start_time <= visits[0].start_time <= visits[1].start_time ... <= vehicle_end_time``). + - a shipment may only be performed on a vehicle that is + allowed. A vehicle is allowed if + [Shipment.allowed_vehicle_indices][google.maps.routeoptimization.v1.Shipment.allowed_vehicle_indices] + is empty or its ``vehicle_index`` is included in + [Shipment.allowed_vehicle_indices][google.maps.routeoptimization.v1.Shipment.allowed_vehicle_indices]. + + If the injected solution is not feasible, a validation error + is not necessarily returned and an error indicating + infeasibility may be returned instead. + injected_solution_constraint (google.maps.routeoptimization_v1.types.InjectedSolutionConstraint): + Constrain the optimization algorithm to find + a final solution that is similar to a previous + solution. For example, this may be used to + freeze portions of routes which have already + been completed or which are to be completed but + must not be modified. + + If the injected solution is not feasible, a + validation error is not necessarily returned and + an error indicating infeasibility may be + returned instead. + refresh_details_routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + If non-empty, the given routes will be refreshed, without + modifying their underlying sequence of visits or travel + times: only other details will be updated. This does not + solve the model. + + As of 2020/11, this only populates the polylines of + non-empty routes and requires that ``populate_polylines`` is + true. + + The ``route_polyline`` fields of the passed-in routes may be + inconsistent with route ``transitions``. + + This field must not be used together with + ``injected_first_solution_routes`` or + ``injected_solution_constraint``. + + ``Shipment.ignore`` and ``Vehicle.ignore`` have no effect on + the behavior. Polylines are still populated between all + visits in all non-empty routes regardless of whether the + related shipments or vehicles are ignored. + interpret_injected_solutions_using_labels (bool): + If true: + + - uses + [ShipmentRoute.vehicle_label][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_label] + instead of ``vehicle_index`` to match routes in an + injected solution with vehicles in the request; reuses + the mapping of original + [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index] + to new + [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index] + to update + [ConstraintRelaxation.vehicle_indices][google.maps.routeoptimization.v1.InjectedSolutionConstraint.ConstraintRelaxation.vehicle_indices] + if non-empty, but the mapping must be unambiguous (i.e., + multiple ``ShipmentRoute``\ s must not share the same + original ``vehicle_index``). + - uses + [ShipmentRoute.Visit.shipment_label][google.maps.routeoptimization.v1.ShipmentRoute.Visit.shipment_label] + instead of ``shipment_index`` to match visits in an + injected solution with shipments in the request; + - uses + [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] + instead of + [SkippedShipment.index][google.maps.routeoptimization.v1.SkippedShipment.index] + to match skipped shipments in the injected solution with + request shipments. + + This interpretation applies to the + ``injected_first_solution_routes``, + ``injected_solution_constraint``, and + ``refresh_details_routes`` fields. It can be used when + shipment or vehicle indices in the request have changed + since the solution was created, perhaps because shipments or + vehicles have been removed from or added to the request. + + If true, labels in the following categories must appear at + most once in their category: + + - [Vehicle.label][google.maps.routeoptimization.v1.Vehicle.label] + in the request; + - [Shipment.label][google.maps.routeoptimization.v1.Shipment.label] + in the request; + - [ShipmentRoute.vehicle_label][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_label] + in the injected solution; + - [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] + and + [ShipmentRoute.Visit.shipment_label][google.maps.routeoptimization.v1.ShipmentRoute.Visit.shipment_label] + in the injected solution (except pickup/delivery visit + pairs, whose ``shipment_label`` must appear twice). + + If a ``vehicle_label`` in the injected solution does not + correspond to a request vehicle, the corresponding route is + removed from the solution along with its visits. If a + ``shipment_label`` in the injected solution does not + correspond to a request shipment, the corresponding visit is + removed from the solution. If a + [SkippedShipment.label][google.maps.routeoptimization.v1.SkippedShipment.label] + in the injected solution does not correspond to a request + shipment, the ``SkippedShipment`` is removed from the + solution. + + Removing route visits or entire routes from an injected + solution may have an effect on the implied constraints, + which may lead to change in solution, validation errors, or + infeasibility. + + NOTE: The caller must ensure that each + [Vehicle.label][google.maps.routeoptimization.v1.Vehicle.label] + (resp. + [Shipment.label][google.maps.routeoptimization.v1.Shipment.label]) + uniquely identifies a vehicle (resp. shipment) entity used + across the two relevant requests: the past request that + produced the ``OptimizeToursResponse`` used in the injected + solution and the current request that includes the injected + solution. The uniqueness checks described above are not + enough to guarantee this requirement. + consider_road_traffic (bool): + Consider traffic estimation in calculating ``ShipmentRoute`` + fields + [Transition.travel_duration][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_duration], + [Visit.start_time][google.maps.routeoptimization.v1.ShipmentRoute.Visit.start_time], + and ``vehicle_end_time``; in setting the + [ShipmentRoute.has_traffic_infeasibilities][google.maps.routeoptimization.v1.ShipmentRoute.has_traffic_infeasibilities] + field, and in calculating the + [OptimizeToursResponse.total_cost][google.maps.routeoptimization.v1.OptimizeToursResponse.total_cost] + field. + populate_polylines (bool): + If true, polylines will be populated in response + ``ShipmentRoute``\ s. + populate_transition_polylines (bool): + If true, polylines will be populated in response + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions]. + allow_large_deadline_despite_interruption_risk (bool): + If this is set, then the request can have a + deadline (see https://grpc.io/blog/deadlines) of + up to 60 minutes. Otherwise, the maximum + deadline is only 30 minutes. Note that + long-lived requests have a significantly larger + (but still small) risk of interruption. + use_geodesic_distances (bool): + If true, travel distances will be computed using geodesic + distances instead of Google Maps distances, and travel times + will be computed using geodesic distances with a speed + defined by ``geodesic_meters_per_second``. + geodesic_meters_per_second (float): + When ``use_geodesic_distances`` is true, this field must be + set and defines the speed applied to compute travel times. + Its value must be at least 1.0 meters/seconds. + + This field is a member of `oneof`_ ``_geodesic_meters_per_second``. + max_validation_errors (int): + Truncates the number of validation errors returned. These + errors are typically attached to an INVALID_ARGUMENT error + payload as a BadRequest error detail + (https://cloud.google.com/apis/design/errors#error_details), + unless solving_mode=VALIDATE_ONLY: see the + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + field. This defaults to 100 and is capped at 10,000. + + This field is a member of `oneof`_ ``_max_validation_errors``. + label (str): + Label that may be used to identify this request, reported + back in the + [OptimizeToursResponse.request_label][google.maps.routeoptimization.v1.OptimizeToursResponse.request_label]. + """ + + class SolvingMode(proto.Enum): + r"""Defines how the solver should handle the request. In all modes but + ``VALIDATE_ONLY``, if the request is invalid, you will receive an + ``INVALID_REQUEST`` error. See + [max_validation_errors][google.maps.routeoptimization.v1.OptimizeToursRequest.max_validation_errors] + to cap the number of errors returned. + + Values: + DEFAULT_SOLVE (0): + Solve the model. + VALIDATE_ONLY (1): + Only validates the model without solving it: populates as + many + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + as possible. + DETECT_SOME_INFEASIBLE_SHIPMENTS (2): + Only populates + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + or + [OptimizeToursResponse.skipped_shipments][google.maps.routeoptimization.v1.OptimizeToursResponse.skipped_shipments], + and doesn't actually solve the rest of the request + (``status`` and ``routes`` are unset in the response). If + infeasibilities in ``injected_solution_constraint`` routes + are detected they are populated in the + [OptimizeToursResponse.validation_errors][google.maps.routeoptimization.v1.OptimizeToursResponse.validation_errors] + field and + [OptimizeToursResponse.skipped_shipments][google.maps.routeoptimization.v1.OptimizeToursResponse.skipped_shipments] + is left empty. + + *IMPORTANT*: not all infeasible shipments are returned here, + but only the ones that are detected as infeasible during + preprocessing. + """ + DEFAULT_SOLVE = 0 + VALIDATE_ONLY = 1 + DETECT_SOME_INFEASIBLE_SHIPMENTS = 2 + + class SearchMode(proto.Enum): + r"""Mode defining the behavior of the search, trading off latency + versus solution quality. In all modes, the global request + deadline is enforced. + + Values: + SEARCH_MODE_UNSPECIFIED (0): + Unspecified search mode, equivalent to ``RETURN_FAST``. + RETURN_FAST (1): + Stop the search after finding the first good + solution. + CONSUME_ALL_AVAILABLE_TIME (2): + Spend all the available time to search for + better solutions. + """ + SEARCH_MODE_UNSPECIFIED = 0 + RETURN_FAST = 1 + CONSUME_ALL_AVAILABLE_TIME = 2 + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + timeout: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + model: "ShipmentModel" = proto.Field( + proto.MESSAGE, + number=3, + message="ShipmentModel", + ) + solving_mode: SolvingMode = proto.Field( + proto.ENUM, + number=4, + enum=SolvingMode, + ) + search_mode: SearchMode = proto.Field( + proto.ENUM, + number=6, + enum=SearchMode, + ) + injected_first_solution_routes: MutableSequence[ + "ShipmentRoute" + ] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message="ShipmentRoute", + ) + injected_solution_constraint: "InjectedSolutionConstraint" = proto.Field( + proto.MESSAGE, + number=8, + message="InjectedSolutionConstraint", + ) + refresh_details_routes: MutableSequence["ShipmentRoute"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="ShipmentRoute", + ) + interpret_injected_solutions_using_labels: bool = proto.Field( + proto.BOOL, + number=10, + ) + consider_road_traffic: bool = proto.Field( + proto.BOOL, + number=11, + ) + populate_polylines: bool = proto.Field( + proto.BOOL, + number=12, + ) + populate_transition_polylines: bool = proto.Field( + proto.BOOL, + number=13, + ) + allow_large_deadline_despite_interruption_risk: bool = proto.Field( + proto.BOOL, + number=14, + ) + use_geodesic_distances: bool = proto.Field( + proto.BOOL, + number=15, + ) + geodesic_meters_per_second: float = proto.Field( + proto.DOUBLE, + number=16, + optional=True, + ) + max_validation_errors: int = proto.Field( + proto.INT32, + number=5, + optional=True, + ) + label: str = proto.Field( + proto.STRING, + number=17, + ) + + +class OptimizeToursResponse(proto.Message): + r"""Response after solving a tour optimization problem containing + the routes followed by each vehicle, the shipments which have + been skipped and the overall cost of the solution. + + Attributes: + routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + Routes computed for each vehicle; the i-th + route corresponds to the i-th vehicle in the + model. + request_label (str): + Copy of the + [OptimizeToursRequest.label][google.maps.routeoptimization.v1.OptimizeToursRequest.label], + if a label was specified in the request. + skipped_shipments (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment]): + The list of all shipments skipped. + validation_errors (MutableSequence[google.maps.routeoptimization_v1.types.OptimizeToursValidationError]): + List of all the validation errors that we were able to + detect independently. See the "MULTIPLE ERRORS" explanation + for the + [OptimizeToursValidationError][google.maps.routeoptimization.v1.OptimizeToursValidationError] + message. + metrics (google.maps.routeoptimization_v1.types.OptimizeToursResponse.Metrics): + Duration, distance and usage metrics for this + solution. + """ + + class Metrics(proto.Message): + r"""Overall metrics, aggregated over all routes. + + Attributes: + aggregated_route_metrics (google.maps.routeoptimization_v1.types.AggregatedMetrics): + Aggregated over the routes. Each metric is the sum (or max, + for loads) over all + [ShipmentRoute.metrics][google.maps.routeoptimization.v1.ShipmentRoute.metrics] + fields of the same name. + skipped_mandatory_shipment_count (int): + Number of mandatory shipments skipped. + used_vehicle_count (int): + Number of vehicles used. Note: if a vehicle route is empty + and + [Vehicle.used_if_route_is_empty][google.maps.routeoptimization.v1.Vehicle.used_if_route_is_empty] + is true, the vehicle is considered used. + earliest_vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): + The earliest start time for a used vehicle, computed as the + minimum over all used vehicles of + [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time]. + latest_vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): + The latest end time for a used vehicle, computed as the + maximum over all used vehicles of + [ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time]. + costs (MutableMapping[str, float]): + Cost of the solution, broken down by cost-related request + fields. The keys are proto paths, relative to the input + OptimizeToursRequest, e.g. "model.shipments.pickups.cost", + and the values are the total cost generated by the + corresponding cost field, aggregated over the whole + solution. In other words, + costs["model.shipments.pickups.cost"] is the sum of all + pickup costs over the solution. All costs defined in the + model are reported in detail here with the exception of + costs related to TransitionAttributes that are only reported + in an aggregated way as of 2022/01. + total_cost (float): + Total cost of the solution. The sum of all + values in the costs map. + """ + + aggregated_route_metrics: "AggregatedMetrics" = proto.Field( + proto.MESSAGE, + number=1, + message="AggregatedMetrics", + ) + skipped_mandatory_shipment_count: int = proto.Field( + proto.INT32, + number=2, + ) + used_vehicle_count: int = proto.Field( + proto.INT32, + number=3, + ) + earliest_vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + latest_vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=10, + ) + total_cost: float = proto.Field( + proto.DOUBLE, + number=6, + ) + + routes: MutableSequence["ShipmentRoute"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ShipmentRoute", + ) + request_label: str = proto.Field( + proto.STRING, + number=3, + ) + skipped_shipments: MutableSequence["SkippedShipment"] = proto.RepeatedField( + proto.MESSAGE, + number=4, + message="SkippedShipment", + ) + validation_errors: MutableSequence[ + "OptimizeToursValidationError" + ] = proto.RepeatedField( + proto.MESSAGE, + number=5, + message="OptimizeToursValidationError", + ) + metrics: Metrics = proto.Field( + proto.MESSAGE, + number=6, + message=Metrics, + ) + + +class ShipmentModel(proto.Message): + r"""A shipment model contains a set of shipments which must be performed + by a set of vehicles, while minimizing the overall cost, which is + the sum of: + + - the cost of routing the vehicles (sum of cost per total time, + cost per travel time, and fixed cost over all vehicles). + - the unperformed shipment penalties. + - the cost of the global duration of the shipments + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + shipments (MutableSequence[google.maps.routeoptimization_v1.types.Shipment]): + Set of shipments which must be performed in + the model. + vehicles (MutableSequence[google.maps.routeoptimization_v1.types.Vehicle]): + Set of vehicles which can be used to perform + visits. + max_active_vehicles (int): + Constrains the maximum number of active + vehicles. A vehicle is active if its route + performs at least one shipment. This can be used + to limit the number of routes in the case where + there are fewer drivers than vehicles and that + the fleet of vehicles is heterogeneous. The + optimization will then select the best subset of + vehicles to use. Must be strictly positive. + + This field is a member of `oneof`_ ``_max_active_vehicles``. + global_start_time (google.protobuf.timestamp_pb2.Timestamp): + Global start and end time of the model: no times outside of + this range can be considered valid. + + The model's time span must be less than a year, i.e. the + ``global_end_time`` and the ``global_start_time`` must be + within 31536000 seconds of each other. + + When using ``cost_per_*hour`` fields, you might want to set + this window to a smaller interval to increase performance + (eg. if you model a single day, you should set the global + time limits to that day). If unset, 00:00:00 UTC, January 1, + 1970 (i.e. seconds: 0, nanos: 0) is used as default. + global_end_time (google.protobuf.timestamp_pb2.Timestamp): + If unset, 00:00:00 UTC, January 1, 1971 (i.e. + seconds: 31536000, nanos: 0) is used as default. + global_duration_cost_per_hour (float): + The "global duration" of the overall plan is the difference + between the earliest effective start time and the latest + effective end time of all vehicles. Users can assign a cost + per hour to that quantity to try and optimize for earliest + job completion, for example. This cost must be in the same + unit as + [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. + duration_distance_matrices (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.DurationDistanceMatrix]): + Specifies duration and distance matrices used in the model. + If this field is empty, Google Maps or geodesic distances + will be used instead, depending on the value of the + ``use_geodesic_distances`` field. If it is not empty, + ``use_geodesic_distances`` cannot be true and neither + ``duration_distance_matrix_src_tags`` nor + ``duration_distance_matrix_dst_tags`` can be empty. + + Usage examples: + + - There are two locations: locA and locB. + - 1 vehicle starting its route at locA and ending it at + locA. + - 1 pickup visit request at locB. + + :: + + model { + vehicles { start_tags: "locA" end_tags: "locA" } + shipments { pickups { tags: "locB" } } + duration_distance_matrix_src_tags: "locA" + duration_distance_matrix_src_tags: "locB" + duration_distance_matrix_dst_tags: "locA" + duration_distance_matrix_dst_tags: "locB" + duration_distance_matrices { + rows { # from: locA + durations { seconds: 0 } meters: 0 # to: locA + durations { seconds: 100 } meters: 1000 # to: locB + } + rows { # from: locB + durations { seconds: 102 } meters: 990 # to: locA + durations { seconds: 0 } meters: 0 # to: locB + } + } + } + + - There are three locations: locA, locB and locC. + - 1 vehicle starting its route at locA and ending it at + locB, using matrix "fast". + - 1 vehicle starting its route at locB and ending it at + locB, using matrix "slow". + - 1 vehicle starting its route at locB and ending it at + locB, using matrix "fast". + - 1 pickup visit request at locC. + + :: + + model { + vehicles { start_tags: "locA" end_tags: "locB" start_tags: "fast" } + vehicles { start_tags: "locB" end_tags: "locB" start_tags: "slow" } + vehicles { start_tags: "locB" end_tags: "locB" start_tags: "fast" } + shipments { pickups { tags: "locC" } } + duration_distance_matrix_src_tags: "locA" + duration_distance_matrix_src_tags: "locB" + duration_distance_matrix_src_tags: "locC" + duration_distance_matrix_dst_tags: "locB" + duration_distance_matrix_dst_tags: "locC" + duration_distance_matrices { + vehicle_start_tag: "fast" + rows { # from: locA + durations { seconds: 1000 } meters: 2000 # to: locB + durations { seconds: 600 } meters: 1000 # to: locC + } + rows { # from: locB + durations { seconds: 0 } meters: 0 # to: locB + durations { seconds: 700 } meters: 1200 # to: locC + } + rows { # from: locC + durations { seconds: 702 } meters: 1190 # to: locB + durations { seconds: 0 } meters: 0 # to: locC + } + } + duration_distance_matrices { + vehicle_start_tag: "slow" + rows { # from: locA + durations { seconds: 1800 } meters: 2001 # to: locB + durations { seconds: 900 } meters: 1002 # to: locC + } + rows { # from: locB + durations { seconds: 0 } meters: 0 # to: locB + durations { seconds: 1000 } meters: 1202 # to: locC + } + rows { # from: locC + durations { seconds: 1001 } meters: 1195 # to: locB + durations { seconds: 0 } meters: 0 # to: locC + } + } + } + duration_distance_matrix_src_tags (MutableSequence[str]): + Tags defining the sources of the duration and distance + matrices; ``duration_distance_matrices(i).rows(j)`` defines + durations and distances from visits with tag + ``duration_distance_matrix_src_tags(j)`` to other visits in + matrix i. + + Tags correspond to + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags]. + A given ``VisitRequest`` or ``Vehicle`` must match exactly + one tag in this field. Note that a ``Vehicle``'s source, + destination and matrix tags may be the same; similarly a + ``VisitRequest``'s source and destination tags may be the + same. All tags must be different and cannot be empty + strings. If this field is not empty, then + ``duration_distance_matrices`` must not be empty. + duration_distance_matrix_dst_tags (MutableSequence[str]): + Tags defining the destinations of the duration and distance + matrices; + ``duration_distance_matrices(i).rows(j).durations(k)`` + (resp. ``duration_distance_matrices(i).rows(j).meters(k))`` + defines the duration (resp. the distance) of the travel from + visits with tag ``duration_distance_matrix_src_tags(j)`` to + visits with tag ``duration_distance_matrix_dst_tags(k)`` in + matrix i. + + Tags correspond to + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags]. + A given ``VisitRequest`` or ``Vehicle`` must match exactly + one tag in this field. Note that a ``Vehicle``'s source, + destination and matrix tags may be the same; similarly a + ``VisitRequest``'s source and destination tags may be the + same. All tags must be different and cannot be empty + strings. If this field is not empty, then + ``duration_distance_matrices`` must not be empty. + transition_attributes (MutableSequence[google.maps.routeoptimization_v1.types.TransitionAttributes]): + Transition attributes added to the model. + shipment_type_incompatibilities (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentTypeIncompatibility]): + Sets of incompatible shipment_types (see + ``ShipmentTypeIncompatibility``). + shipment_type_requirements (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentTypeRequirement]): + Sets of ``shipment_type`` requirements (see + ``ShipmentTypeRequirement``). + precedence_rules (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.PrecedenceRule]): + Set of precedence rules which must be + enforced in the model. + """ + + class DurationDistanceMatrix(proto.Message): + r"""Specifies a duration and distance matrix from visit and + vehicle start locations to visit and vehicle end locations. + + Attributes: + rows (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentModel.DurationDistanceMatrix.Row]): + Specifies the rows of the duration and distance matrix. It + must have as many elements as + [ShipmentModel.duration_distance_matrix_src_tags][google.maps.routeoptimization.v1.ShipmentModel.duration_distance_matrix_src_tags]. + vehicle_start_tag (str): + Tag defining to which vehicles this duration and distance + matrix applies. If empty, this applies to all vehicles, and + there can only be a single matrix. + + Each vehicle start must match exactly one matrix, i.e. + exactly one of their ``start_tags`` field must match the + ``vehicle_start_tag`` of a matrix (and of that matrix only). + + All matrices must have a different ``vehicle_start_tag``. + """ + + class Row(proto.Message): + r"""Specifies a row of the duration and distance matrix. + + Attributes: + durations (MutableSequence[google.protobuf.duration_pb2.Duration]): + Duration values for a given row. It must have as many + elements as + [ShipmentModel.duration_distance_matrix_dst_tags][google.maps.routeoptimization.v1.ShipmentModel.duration_distance_matrix_dst_tags]. + meters (MutableSequence[float]): + Distance values for a given row. If no costs or constraints + refer to distances in the model, this can be left empty; + otherwise it must have as many elements as ``durations``. + """ + + durations: MutableSequence[duration_pb2.Duration] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + meters: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=2, + ) + + rows: MutableSequence[ + "ShipmentModel.DurationDistanceMatrix.Row" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ShipmentModel.DurationDistanceMatrix.Row", + ) + vehicle_start_tag: str = proto.Field( + proto.STRING, + number=2, + ) + + class PrecedenceRule(proto.Message): + r"""A precedence rule between two events (each event is the pickup or + the delivery of a shipment): the "second" event has to start at + least ``offset_duration`` after "first" has started. + + Several precedences can refer to the same (or related) events, e.g., + "pickup of B happens after delivery of A" and "pickup of C happens + after pickup of B". + + Furthermore, precedences only apply when both shipments are + performed and are otherwise ignored. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + first_index (int): + Shipment index of the "first" event. This + field must be specified. + + This field is a member of `oneof`_ ``_first_index``. + first_is_delivery (bool): + Indicates if the "first" event is a delivery. + second_index (int): + Shipment index of the "second" event. This + field must be specified. + + This field is a member of `oneof`_ ``_second_index``. + second_is_delivery (bool): + Indicates if the "second" event is a + delivery. + offset_duration (google.protobuf.duration_pb2.Duration): + The offset between the "first" and "second" + event. It can be negative. + """ + + first_index: int = proto.Field( + proto.INT32, + number=1, + optional=True, + ) + first_is_delivery: bool = proto.Field( + proto.BOOL, + number=3, + ) + second_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + second_is_delivery: bool = proto.Field( + proto.BOOL, + number=4, + ) + offset_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + + shipments: MutableSequence["Shipment"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Shipment", + ) + vehicles: MutableSequence["Vehicle"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="Vehicle", + ) + max_active_vehicles: int = proto.Field( + proto.INT32, + number=4, + optional=True, + ) + global_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + global_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + global_duration_cost_per_hour: float = proto.Field( + proto.DOUBLE, + number=7, + ) + duration_distance_matrices: MutableSequence[ + DurationDistanceMatrix + ] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=DurationDistanceMatrix, + ) + duration_distance_matrix_src_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=9, + ) + duration_distance_matrix_dst_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + transition_attributes: MutableSequence[ + "TransitionAttributes" + ] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message="TransitionAttributes", + ) + shipment_type_incompatibilities: MutableSequence[ + "ShipmentTypeIncompatibility" + ] = proto.RepeatedField( + proto.MESSAGE, + number=12, + message="ShipmentTypeIncompatibility", + ) + shipment_type_requirements: MutableSequence[ + "ShipmentTypeRequirement" + ] = proto.RepeatedField( + proto.MESSAGE, + number=13, + message="ShipmentTypeRequirement", + ) + precedence_rules: MutableSequence[PrecedenceRule] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=PrecedenceRule, + ) + + +class Shipment(proto.Message): + r"""The shipment of a single item, from one of its pickups to one + of its deliveries. For the shipment to be considered as + performed, a unique vehicle must visit one of its pickup + locations (and decrease its spare capacities accordingly), then + visit one of its delivery locations later on (and therefore + re-increase its spare capacities accordingly). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + The user-defined display name of the + shipment. It can be up to 63 characters long and + may use UTF-8 characters. + pickups (MutableSequence[google.maps.routeoptimization_v1.types.Shipment.VisitRequest]): + Set of pickup alternatives associated to the + shipment. If not specified, the vehicle only + needs to visit a location corresponding to the + deliveries. + deliveries (MutableSequence[google.maps.routeoptimization_v1.types.Shipment.VisitRequest]): + Set of delivery alternatives associated to + the shipment. If not specified, the vehicle only + needs to visit a location corresponding to the + pickups. + load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): + Load demands of the shipment (for example weight, volume, + number of pallets etc). The keys in the map should be + identifiers describing the type of the corresponding load, + ideally also including the units. For example: "weight_kg", + "volume_gallons", "pallet_count", etc. If a given key does + not appear in the map, the corresponding load is considered + as null. + penalty_cost (float): + If the shipment is not completed, this penalty is added to + the overall cost of the routes. A shipment is considered + completed if one of its pickup and delivery alternatives is + visited. The cost may be expressed in the same unit used for + all other cost-related fields in the model and must be + positive. + + *IMPORTANT*: If this penalty is not specified, it is + considered infinite, i.e. the shipment must be completed. + + This field is a member of `oneof`_ ``_penalty_cost``. + allowed_vehicle_indices (MutableSequence[int]): + The set of vehicles that may perform this shipment. If + empty, all vehicles may perform it. Vehicles are given by + their index in the ``ShipmentModel``'s ``vehicles`` list. + costs_per_vehicle (MutableSequence[float]): + Specifies the cost that is incurred when this shipment is + delivered by each vehicle. If specified, it must have + EITHER: + + - the same number of elements as + ``costs_per_vehicle_indices``. ``costs_per_vehicle[i]`` + corresponds to vehicle ``costs_per_vehicle_indices[i]`` + of the model. + - the same number of elements as there are vehicles in the + model. The i-th element corresponds to vehicle #i of the + model. + + These costs must be in the same unit as ``penalty_cost`` and + must not be negative. Leave this field empty, if there are + no such costs. + costs_per_vehicle_indices (MutableSequence[int]): + Indices of the vehicles to which ``costs_per_vehicle`` + applies. If non-empty, it must have the same number of + elements as ``costs_per_vehicle``. A vehicle index may not + be specified more than once. If a vehicle is excluded from + ``costs_per_vehicle_indices``, its cost is zero. + pickup_to_delivery_relative_detour_limit (float): + Specifies the maximum relative detour time compared to the + shortest path from pickup to delivery. If specified, it must + be nonnegative, and the shipment must contain at least a + pickup and a delivery. + + For example, let t be the shortest time taken to go from the + selected pickup alternative directly to the selected + delivery alternative. Then setting + ``pickup_to_delivery_relative_detour_limit`` enforces: + + :: + + start_time(delivery) - start_time(pickup) <= + std::ceil(t * (1.0 + pickup_to_delivery_relative_detour_limit)) + + If both relative and absolute limits are specified on the + same shipment, the more constraining limit is used for each + possible pickup/delivery pair. As of 2017/10, detours are + only supported when travel durations do not depend on + vehicles. + + This field is a member of `oneof`_ ``_pickup_to_delivery_relative_detour_limit``. + pickup_to_delivery_absolute_detour_limit (google.protobuf.duration_pb2.Duration): + Specifies the maximum absolute detour time compared to the + shortest path from pickup to delivery. If specified, it must + be nonnegative, and the shipment must contain at least a + pickup and a delivery. + + For example, let t be the shortest time taken to go from the + selected pickup alternative directly to the selected + delivery alternative. Then setting + ``pickup_to_delivery_absolute_detour_limit`` enforces: + + :: + + start_time(delivery) - start_time(pickup) <= + t + pickup_to_delivery_absolute_detour_limit + + If both relative and absolute limits are specified on the + same shipment, the more constraining limit is used for each + possible pickup/delivery pair. As of 2017/10, detours are + only supported when travel durations do not depend on + vehicles. + pickup_to_delivery_time_limit (google.protobuf.duration_pb2.Duration): + Specifies the maximum duration from start of + pickup to start of delivery of a shipment. If + specified, it must be nonnegative, and the + shipment must contain at least a pickup and a + delivery. This does not depend on which + alternatives are selected for pickup and + delivery, nor on vehicle speed. This can be + specified alongside maximum detour constraints: + the solution will respect both specifications. + shipment_type (str): + Non-empty string specifying a "type" for this shipment. This + feature can be used to define incompatibilities or + requirements between ``shipment_types`` (see + ``shipment_type_incompatibilities`` and + ``shipment_type_requirements`` in ``ShipmentModel``). + + Differs from ``visit_types`` which is specified for a single + visit: All pickup/deliveries belonging to the same shipment + share the same ``shipment_type``. + label (str): + Specifies a label for this shipment. This label is reported + in the response in the ``shipment_label`` of the + corresponding + [ShipmentRoute.Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]. + ignore (bool): + If true, skip this shipment, but don't apply a + ``penalty_cost``. + + Ignoring a shipment results in a validation error when there + are any ``shipment_type_requirements`` in the model. + + Ignoring a shipment that is performed in + ``injected_first_solution_routes`` or + ``injected_solution_constraint`` is permitted; the solver + removes the related pickup/delivery visits from the + performing route. ``precedence_rules`` that reference + ignored shipments will also be ignored. + """ + + class VisitRequest(proto.Message): + r"""Request for a visit which can be done by a vehicle: it has a + geo-location (or two, see below), opening and closing times + represented by time windows, and a service duration time (time + spent by the vehicle once it has arrived to pickup or drop off + goods). + + Attributes: + arrival_location (google.type.latlng_pb2.LatLng): + The geo-location where the vehicle arrives when performing + this ``VisitRequest``. If the shipment model has duration + distance matrices, ``arrival_location`` must not be + specified. + arrival_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + The waypoint where the vehicle arrives when performing this + ``VisitRequest``. If the shipment model has duration + distance matrices, ``arrival_waypoint`` must not be + specified. + departure_location (google.type.latlng_pb2.LatLng): + The geo-location where the vehicle departs after completing + this ``VisitRequest``. Can be omitted if it is the same as + ``arrival_location``. If the shipment model has duration + distance matrices, ``departure_location`` must not be + specified. + departure_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + The waypoint where the vehicle departs after completing this + ``VisitRequest``. Can be omitted if it is the same as + ``arrival_waypoint``. If the shipment model has duration + distance matrices, ``departure_waypoint`` must not be + specified. + tags (MutableSequence[str]): + Specifies tags attached to the visit request. + Empty or duplicate strings are not allowed. + time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): + Time windows which constrain the arrival time at a visit. + Note that a vehicle may depart outside of the arrival time + window, i.e. arrival time + duration do not need to be + inside a time window. This can result in waiting time if the + vehicle arrives before + [TimeWindow.start_time][google.maps.routeoptimization.v1.TimeWindow.start_time]. + + The absence of ``TimeWindow`` means that the vehicle can + perform this visit at any time. + + Time windows must be disjoint, i.e. no time window must + overlap with or be adjacent to another, and they must be in + increasing order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + duration (google.protobuf.duration_pb2.Duration): + Duration of the visit, i.e. time spent by the vehicle + between arrival and departure (to be added to the possible + waiting time; see ``time_windows``). + cost (float): + Cost to service this visit request on a vehicle route. This + can be used to pay different costs for each alternative + pickup or delivery of a shipment. This cost must be in the + same unit as ``Shipment.penalty_cost`` and must not be + negative. + load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): + Load demands of this visit request. This is just like + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] + field, except that it only applies to this + [VisitRequest][google.maps.routeoptimization.v1.Shipment.VisitRequest] + instead of the whole + [Shipment][google.maps.routeoptimization.v1.Shipment]. The + demands listed here are added to the demands listed in + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands]. + visit_types (MutableSequence[str]): + Specifies the types of the visit. This may be used to + allocate additional time required for a vehicle to complete + this visit (see + [Vehicle.extra_visit_duration_for_visit_type][google.maps.routeoptimization.v1.Vehicle.extra_visit_duration_for_visit_type]). + + A type can only appear once. + label (str): + Specifies a label for this ``VisitRequest``. This label is + reported in the response as ``visit_label`` in the + corresponding + [ShipmentRoute.Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit]. + """ + + arrival_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + arrival_waypoint: "Waypoint" = proto.Field( + proto.MESSAGE, + number=2, + message="Waypoint", + ) + departure_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=3, + message=latlng_pb2.LatLng, + ) + departure_waypoint: "Waypoint" = proto.Field( + proto.MESSAGE, + number=4, + message="Waypoint", + ) + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=5, + ) + time_windows: MutableSequence["TimeWindow"] = proto.RepeatedField( + proto.MESSAGE, + number=6, + message="TimeWindow", + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + cost: float = proto.Field( + proto.DOUBLE, + number=8, + ) + load_demands: MutableMapping[str, "Shipment.Load"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=12, + message="Shipment.Load", + ) + visit_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=10, + ) + label: str = proto.Field( + proto.STRING, + number=11, + ) + + class Load(proto.Message): + r"""When performing a visit, a predefined amount may be added to the + vehicle load if it's a pickup, or subtracted if it's a delivery. + This message defines such amount. See + [load_demands][google.maps.routeoptimization.v1.Shipment.load_demands]. + + Attributes: + amount (int): + The amount by which the load of the vehicle + performing the corresponding visit will vary. + Since it is an integer, users are advised to + choose an appropriate unit to avoid loss of + precision. Must be ≥ 0. + """ + + amount: int = proto.Field( + proto.INT64, + number=2, + ) + + display_name: str = proto.Field( + proto.STRING, + number=16, + ) + pickups: MutableSequence[VisitRequest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=VisitRequest, + ) + deliveries: MutableSequence[VisitRequest] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=VisitRequest, + ) + load_demands: MutableMapping[str, Load] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=14, + message=Load, + ) + penalty_cost: float = proto.Field( + proto.DOUBLE, + number=4, + optional=True, + ) + allowed_vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=5, + ) + costs_per_vehicle: MutableSequence[float] = proto.RepeatedField( + proto.DOUBLE, + number=6, + ) + costs_per_vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=7, + ) + pickup_to_delivery_relative_detour_limit: float = proto.Field( + proto.DOUBLE, + number=8, + optional=True, + ) + pickup_to_delivery_absolute_detour_limit: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=9, + message=duration_pb2.Duration, + ) + pickup_to_delivery_time_limit: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=10, + message=duration_pb2.Duration, + ) + shipment_type: str = proto.Field( + proto.STRING, + number=11, + ) + label: str = proto.Field( + proto.STRING, + number=12, + ) + ignore: bool = proto.Field( + proto.BOOL, + number=13, + ) + + +class ShipmentTypeIncompatibility(proto.Message): + r"""Specifies incompatibilties between shipments depending on their + shipment_type. The appearance of incompatible shipments on the same + route is restricted based on the incompatibility mode. + + Attributes: + types (MutableSequence[str]): + List of incompatible types. Two shipments having different + ``shipment_types`` among those listed are "incompatible". + incompatibility_mode (google.maps.routeoptimization_v1.types.ShipmentTypeIncompatibility.IncompatibilityMode): + Mode applied to the incompatibility. + """ + + class IncompatibilityMode(proto.Enum): + r"""Modes defining how the appearance of incompatible shipments + are restricted on the same route. + + Values: + INCOMPATIBILITY_MODE_UNSPECIFIED (0): + Unspecified incompatibility mode. This value + should never be used. + NOT_PERFORMED_BY_SAME_VEHICLE (1): + In this mode, two shipments with incompatible + types can never share the same vehicle. + NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY (2): + For two shipments with incompatible types with the + ``NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY`` incompatibility mode: + + - If both are pickups only (no deliveries) or deliveries + only (no pickups), they cannot share the same vehicle at + all. + - If one of the shipments has a delivery and the other a + pickup, the two shipments can share the same vehicle iff + the former shipment is delivered before the latter is + picked up. + """ + INCOMPATIBILITY_MODE_UNSPECIFIED = 0 + NOT_PERFORMED_BY_SAME_VEHICLE = 1 + NOT_IN_SAME_VEHICLE_SIMULTANEOUSLY = 2 + + types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + incompatibility_mode: IncompatibilityMode = proto.Field( + proto.ENUM, + number=2, + enum=IncompatibilityMode, + ) + + +class ShipmentTypeRequirement(proto.Message): + r"""Specifies requirements between shipments based on their + shipment_type. The specifics of the requirement are defined by the + requirement mode. + + Attributes: + required_shipment_type_alternatives (MutableSequence[str]): + List of alternative shipment types required by the + ``dependent_shipment_types``. + dependent_shipment_types (MutableSequence[str]): + All shipments with a type in the + ``dependent_shipment_types`` field require at least one + shipment of type ``required_shipment_type_alternatives`` to + be visited on the same route. + + NOTE: Chains of requirements such that a ``shipment_type`` + depends on itself are not allowed. + requirement_mode (google.maps.routeoptimization_v1.types.ShipmentTypeRequirement.RequirementMode): + Mode applied to the requirement. + """ + + class RequirementMode(proto.Enum): + r"""Modes defining the appearance of dependent shipments on a + route. + + Values: + REQUIREMENT_MODE_UNSPECIFIED (0): + Unspecified requirement mode. This value + should never be used. + PERFORMED_BY_SAME_VEHICLE (1): + In this mode, all "dependent" shipments must + share the same vehicle as at least one of their + "required" shipments. + IN_SAME_VEHICLE_AT_PICKUP_TIME (2): + With the ``IN_SAME_VEHICLE_AT_PICKUP_TIME`` mode, all + "dependent" shipments need to have at least one "required" + shipment on their vehicle at the time of their pickup. + + A "dependent" shipment pickup must therefore have either: + + - A delivery-only "required" shipment delivered on the + route after, or + - A "required" shipment picked up on the route before it, + and if the "required" shipment has a delivery, this + delivery must be performed after the "dependent" + shipment's pickup. + IN_SAME_VEHICLE_AT_DELIVERY_TIME (3): + Same as before, except the "dependent" shipments need to + have a "required" shipment on their vehicle at the time of + their *delivery*. + """ + REQUIREMENT_MODE_UNSPECIFIED = 0 + PERFORMED_BY_SAME_VEHICLE = 1 + IN_SAME_VEHICLE_AT_PICKUP_TIME = 2 + IN_SAME_VEHICLE_AT_DELIVERY_TIME = 3 + + required_shipment_type_alternatives: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + dependent_shipment_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + requirement_mode: RequirementMode = proto.Field( + proto.ENUM, + number=3, + enum=RequirementMode, + ) + + +class Vehicle(proto.Message): + r"""Models a vehicle in a shipment problem. Solving a shipment problem + will build a route starting from ``start_location`` and ending at + ``end_location`` for this vehicle. A route is a sequence of visits + (see ``ShipmentRoute``). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + display_name (str): + The user-defined display name of the vehicle. + It can be up to 63 characters long and may use + UTF-8 characters. + travel_mode (google.maps.routeoptimization_v1.types.Vehicle.TravelMode): + The travel mode which affects the roads usable by the + vehicle and its speed. See also + ``travel_duration_multiple``. + start_location (google.type.latlng_pb2.LatLng): + Geographic location where the vehicle starts before picking + up any shipments. If not specified, the vehicle starts at + its first pickup. If the shipment model has duration and + distance matrices, ``start_location`` must not be specified. + start_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + Waypoint representing a geographic location where the + vehicle starts before picking up any shipments. If neither + ``start_waypoint`` nor ``start_location`` is specified, the + vehicle starts at its first pickup. If the shipment model + has duration and distance matrices, ``start_waypoint`` must + not be specified. + end_location (google.type.latlng_pb2.LatLng): + Geographic location where the vehicle ends after it has + completed its last ``VisitRequest``. If not specified the + vehicle's ``ShipmentRoute`` ends immediately when it + completes its last ``VisitRequest``. If the shipment model + has duration and distance matrices, ``end_location`` must + not be specified. + end_waypoint (google.maps.routeoptimization_v1.types.Waypoint): + Waypoint representing a geographic location where the + vehicle ends after it has completed its last + ``VisitRequest``. If neither ``end_waypoint`` nor + ``end_location`` is specified, the vehicle's + ``ShipmentRoute`` ends immediately when it completes its + last ``VisitRequest``. If the shipment model has duration + and distance matrices, ``end_waypoint`` must not be + specified. + start_tags (MutableSequence[str]): + Specifies tags attached to the start of the + vehicle's route. + Empty or duplicate strings are not allowed. + end_tags (MutableSequence[str]): + Specifies tags attached to the end of the + vehicle's route. + Empty or duplicate strings are not allowed. + start_time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): + Time windows during which the vehicle may depart its start + location. They must be within the global time limits (see + [ShipmentModel.global_*][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] + fields). If unspecified, there is no limitation besides + those global time limits. + + Time windows belonging to the same repeated field must be + disjoint, i.e. no time window can overlap with or be + adjacent to another, and they must be in chronological + order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + end_time_windows (MutableSequence[google.maps.routeoptimization_v1.types.TimeWindow]): + Time windows during which the vehicle may arrive at its end + location. They must be within the global time limits (see + [ShipmentModel.global_*][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] + fields). If unspecified, there is no limitation besides + those global time limits. + + Time windows belonging to the same repeated field must be + disjoint, i.e. no time window can overlap with or be + adjacent to another, and they must be in chronological + order. + + ``cost_per_hour_after_soft_end_time`` and ``soft_end_time`` + can only be set if there is a single time window. + travel_duration_multiple (float): + Specifies a multiplicative factor that can be used to + increase or decrease travel times of this vehicle. For + example, setting this to 2.0 means that this vehicle is + slower and has travel times that are twice what they are for + standard vehicles. This multiple does not affect visit + durations. It does affect cost if ``cost_per_hour`` or + ``cost_per_traveled_hour`` are specified. This must be in + the range [0.001, 1000.0]. If unset, the vehicle is + standard, and this multiple is considered 1.0. + + WARNING: Travel times will be rounded to the nearest second + after this multiple is applied but before performing any + numerical operations, thus, a small multiple may result in a + loss of precision. + + See also ``extra_visit_duration_for_visit_type`` below. + + This field is a member of `oneof`_ ``_travel_duration_multiple``. + unloading_policy (google.maps.routeoptimization_v1.types.Vehicle.UnloadingPolicy): + Unloading policy enforced on the vehicle. + load_limits (MutableMapping[str, google.maps.routeoptimization_v1.types.Vehicle.LoadLimit]): + Capacities of the vehicle (weight, volume, # of pallets for + example). The keys in the map are the identifiers of the + type of load, consistent with the keys of the + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] + field. If a given key is absent from this map, the + corresponding capacity is considered to be limitless. + cost_per_hour (float): + Vehicle costs: all costs add up and must be in the same unit + as + [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. + + Cost per hour of the vehicle route. This cost is applied to + the total time taken by the route, and includes travel time, + waiting time, and visit time. Using ``cost_per_hour`` + instead of just ``cost_per_traveled_hour`` may result in + additional latency. + cost_per_traveled_hour (float): + Cost per traveled hour of the vehicle route. This cost is + applied only to travel time taken by the route (i.e., that + reported in + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions]), + and excludes waiting time and visit time. + cost_per_kilometer (float): + Cost per kilometer of the vehicle route. This cost is + applied to the distance reported in the + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions] + and does not apply to any distance implicitly traveled from + the ``arrival_location`` to the ``departure_location`` of a + single ``VisitRequest``. + fixed_cost (float): + Fixed cost applied if this vehicle is used to + handle a shipment. + used_if_route_is_empty (bool): + This field only applies to vehicles when their route does + not serve any shipments. It indicates if the vehicle should + be considered as used or not in this case. + + If true, the vehicle goes from its start to its end location + even if it doesn't serve any shipments, and time and + distance costs resulting from its start --> end travel are + taken into account. + + Otherwise, it doesn't travel from its start to its end + location, and no ``break_rule`` or delay (from + ``TransitionAttributes``) are scheduled for this vehicle. In + this case, the vehicle's ``ShipmentRoute`` doesn't contain + any information except for the vehicle index and label. + route_duration_limit (google.maps.routeoptimization_v1.types.Vehicle.DurationLimit): + Limit applied to the total duration of the vehicle's route. + In a given ``OptimizeToursResponse``, the route duration of + a vehicle is the difference between its ``vehicle_end_time`` + and ``vehicle_start_time``. + travel_duration_limit (google.maps.routeoptimization_v1.types.Vehicle.DurationLimit): + Limit applied to the travel duration of the vehicle's route. + In a given ``OptimizeToursResponse``, the route travel + duration is the sum of all its + [transitions.travel_duration][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_duration]. + route_distance_limit (google.maps.routeoptimization_v1.types.DistanceLimit): + Limit applied to the total distance of the vehicle's route. + In a given ``OptimizeToursResponse``, the route distance is + the sum of all its + [transitions.travel_distance_meters][google.maps.routeoptimization.v1.ShipmentRoute.Transition.travel_distance_meters]. + extra_visit_duration_for_visit_type (MutableMapping[str, google.protobuf.duration_pb2.Duration]): + Specifies a map from visit_types strings to durations. The + duration is time in addition to + [VisitRequest.duration][google.maps.routeoptimization.v1.Shipment.VisitRequest.duration] + to be taken at visits with the specified ``visit_types``. + This extra visit duration adds cost if ``cost_per_hour`` is + specified. Keys (i.e. ``visit_types``) cannot be empty + strings. + + If a visit request has multiple types, a duration will be + added for each type in the map. + break_rule (google.maps.routeoptimization_v1.types.BreakRule): + Describes the break schedule to be enforced + on this vehicle. If empty, no breaks will be + scheduled for this vehicle. + label (str): + Specifies a label for this vehicle. This label is reported + in the response as the ``vehicle_label`` of the + corresponding + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]. + ignore (bool): + If true, ``used_if_route_is_empty`` must be false, and this + vehicle will remain unused. + + If a shipment is performed by an ignored vehicle in + ``injected_first_solution_routes``, it is skipped in the + first solution but is free to be performed in the response. + + If a shipment is performed by an ignored vehicle in + ``injected_solution_constraint`` and any related + pickup/delivery is constrained to remain on the vehicle + (i.e., not relaxed to level ``RELAX_ALL_AFTER_THRESHOLD``), + it is skipped in the response. If a shipment has a non-empty + ``allowed_vehicle_indices`` field and all of the allowed + vehicles are ignored, it is skipped in the response. + """ + + class TravelMode(proto.Enum): + r"""Travel modes which can be used by vehicles. + + These should be a subset of the Google Maps Platform Routes + Preferred API travel modes, see: + https://developers.google.com/maps/documentation/routes_preferred/reference/rest/Shared.Types/RouteTravelMode. + + Values: + TRAVEL_MODE_UNSPECIFIED (0): + Unspecified travel mode, equivalent to ``DRIVING``. + DRIVING (1): + Travel mode corresponding to driving + directions (car, ...). + WALKING (2): + Travel mode corresponding to walking + directions. + """ + TRAVEL_MODE_UNSPECIFIED = 0 + DRIVING = 1 + WALKING = 2 + + class UnloadingPolicy(proto.Enum): + r"""Policy on how a vehicle can be unloaded. Applies only to shipments + having both a pickup and a delivery. + + Other shipments are free to occur anywhere on the route independent + of ``unloading_policy``. + + Values: + UNLOADING_POLICY_UNSPECIFIED (0): + Unspecified unloading policy; deliveries must + just occur after their corresponding pickups. + LAST_IN_FIRST_OUT (1): + Deliveries must occur in reverse order of + pickups + FIRST_IN_FIRST_OUT (2): + Deliveries must occur in the same order as + pickups + """ + UNLOADING_POLICY_UNSPECIFIED = 0 + LAST_IN_FIRST_OUT = 1 + FIRST_IN_FIRST_OUT = 2 + + class LoadLimit(proto.Message): + r"""Defines a load limit applying to a vehicle, e.g. "this truck may + only carry up to 3500 kg". See + [load_limits][google.maps.routeoptimization.v1.Vehicle.load_limits]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_load (int): + The maximum acceptable amount of load. + + This field is a member of `oneof`_ ``_max_load``. + soft_max_load (int): + A soft limit of the load. See + [cost_per_unit_above_soft_max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. + cost_per_unit_above_soft_max (float): + If the load ever exceeds + [soft_max_load][google.maps.routeoptimization.v1.Vehicle.LoadLimit.soft_max_load] + along this vehicle's route, the following cost penalty + applies (only once per vehicle): (load - + [soft_max_load][google.maps.routeoptimization.v1.Vehicle.LoadLimit.soft_max_load]) + + - [cost_per_unit_above_soft_max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.cost_per_unit_above_soft_max]. + All costs add up and must be in the same unit as + [Shipment.penalty_cost][google.maps.routeoptimization.v1.Shipment.penalty_cost]. + start_load_interval (google.maps.routeoptimization_v1.types.Vehicle.LoadLimit.Interval): + The acceptable load interval of the vehicle + at the start of the route. + end_load_interval (google.maps.routeoptimization_v1.types.Vehicle.LoadLimit.Interval): + The acceptable load interval of the vehicle + at the end of the route. + """ + + class Interval(proto.Message): + r"""Interval of acceptable load amounts. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + min_ (int): + A minimum acceptable load. Must be ≥ 0. If they're both + specified, + [min][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.min] + must be ≤ + [max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.max]. + max_ (int): + A maximum acceptable load. Must be ≥ 0. If unspecified, the + maximum load is unrestricted by this message. If they're + both specified, + [min][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.min] + must be ≤ + [max][google.maps.routeoptimization.v1.Vehicle.LoadLimit.Interval.max]. + + This field is a member of `oneof`_ ``_max``. + """ + + min_: int = proto.Field( + proto.INT64, + number=1, + ) + max_: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + + max_load: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + soft_max_load: int = proto.Field( + proto.INT64, + number=2, + ) + cost_per_unit_above_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + ) + start_load_interval: "Vehicle.LoadLimit.Interval" = proto.Field( + proto.MESSAGE, + number=4, + message="Vehicle.LoadLimit.Interval", + ) + end_load_interval: "Vehicle.LoadLimit.Interval" = proto.Field( + proto.MESSAGE, + number=5, + message="Vehicle.LoadLimit.Interval", + ) + + class DurationLimit(proto.Message): + r"""A limit defining a maximum duration of the route of a + vehicle. It can be either hard or soft. + + When a soft limit field is defined, both the soft max threshold + and its associated cost must be defined together. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_duration (google.protobuf.duration_pb2.Duration): + A hard limit constraining the duration to be at most + max_duration. + soft_max_duration (google.protobuf.duration_pb2.Duration): + A soft limit not enforcing a maximum duration limit, but + when violated makes the route incur a cost. This cost adds + up to other costs defined in the model, with the same unit. + + If defined, ``soft_max_duration`` must be nonnegative. If + max_duration is also defined, ``soft_max_duration`` must be + less than max_duration. + cost_per_hour_after_soft_max (float): + Cost per hour incurred if the ``soft_max_duration`` + threshold is violated. The additional cost is 0 if the + duration is under the threshold, otherwise the cost depends + on the duration as follows: + + :: + + cost_per_hour_after_soft_max * (duration - soft_max_duration) + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_hour_after_soft_max``. + quadratic_soft_max_duration (google.protobuf.duration_pb2.Duration): + A soft limit not enforcing a maximum duration limit, but + when violated makes the route incur a cost, quadratic in the + duration. This cost adds up to other costs defined in the + model, with the same unit. + + If defined, ``quadratic_soft_max_duration`` must be + nonnegative. If ``max_duration`` is also defined, + ``quadratic_soft_max_duration`` must be less than + ``max_duration``, and the difference must be no larger than + one day: + + :: + + `max_duration - quadratic_soft_max_duration <= 86400 seconds` + cost_per_square_hour_after_quadratic_soft_max (float): + Cost per square hour incurred if the + ``quadratic_soft_max_duration`` threshold is violated. + + The additional cost is 0 if the duration is under the + threshold, otherwise the cost depends on the duration as + follows: + + :: + + cost_per_square_hour_after_quadratic_soft_max * + (duration - quadratic_soft_max_duration)^2 + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_square_hour_after_quadratic_soft_max``. + """ + + max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + soft_max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + cost_per_hour_after_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + quadratic_soft_max_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + cost_per_square_hour_after_quadratic_soft_max: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + + display_name: str = proto.Field( + proto.STRING, + number=32, + ) + travel_mode: TravelMode = proto.Field( + proto.ENUM, + number=1, + enum=TravelMode, + ) + start_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=3, + message=latlng_pb2.LatLng, + ) + start_waypoint: "Waypoint" = proto.Field( + proto.MESSAGE, + number=4, + message="Waypoint", + ) + end_location: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=5, + message=latlng_pb2.LatLng, + ) + end_waypoint: "Waypoint" = proto.Field( + proto.MESSAGE, + number=6, + message="Waypoint", + ) + start_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + end_tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=8, + ) + start_time_windows: MutableSequence["TimeWindow"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="TimeWindow", + ) + end_time_windows: MutableSequence["TimeWindow"] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message="TimeWindow", + ) + travel_duration_multiple: float = proto.Field( + proto.DOUBLE, + number=11, + optional=True, + ) + unloading_policy: UnloadingPolicy = proto.Field( + proto.ENUM, + number=12, + enum=UnloadingPolicy, + ) + load_limits: MutableMapping[str, LoadLimit] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=30, + message=LoadLimit, + ) + cost_per_hour: float = proto.Field( + proto.DOUBLE, + number=16, + ) + cost_per_traveled_hour: float = proto.Field( + proto.DOUBLE, + number=17, + ) + cost_per_kilometer: float = proto.Field( + proto.DOUBLE, + number=18, + ) + fixed_cost: float = proto.Field( + proto.DOUBLE, + number=19, + ) + used_if_route_is_empty: bool = proto.Field( + proto.BOOL, + number=20, + ) + route_duration_limit: DurationLimit = proto.Field( + proto.MESSAGE, + number=21, + message=DurationLimit, + ) + travel_duration_limit: DurationLimit = proto.Field( + proto.MESSAGE, + number=22, + message=DurationLimit, + ) + route_distance_limit: "DistanceLimit" = proto.Field( + proto.MESSAGE, + number=23, + message="DistanceLimit", + ) + extra_visit_duration_for_visit_type: MutableMapping[ + str, duration_pb2.Duration + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=24, + message=duration_pb2.Duration, + ) + break_rule: "BreakRule" = proto.Field( + proto.MESSAGE, + number=25, + message="BreakRule", + ) + label: str = proto.Field( + proto.STRING, + number=27, + ) + ignore: bool = proto.Field( + proto.BOOL, + number=28, + ) + + +class TimeWindow(proto.Message): + r"""Time windows constrain the time of an event, such as the arrival + time at a visit, or the start and end time of a vehicle. + + Hard time window bounds, ``start_time`` and ``end_time``, enforce + the earliest and latest time of the event, such that + ``start_time <= event_time <= end_time``. The soft time window lower + bound, ``soft_start_time``, expresses a preference for the event to + happen at or after ``soft_start_time`` by incurring a cost + proportional to how long before soft_start_time the event occurs. + The soft time window upper bound, ``soft_end_time``, expresses a + preference for the event to happen at or before ``soft_end_time`` by + incurring a cost proportional to how long after ``soft_end_time`` + the event occurs. ``start_time``, ``end_time``, ``soft_start_time`` + and ``soft_end_time`` should be within the global time limits (see + [ShipmentModel.global_start_time][google.maps.routeoptimization.v1.ShipmentModel.global_start_time] + and + [ShipmentModel.global_end_time][google.maps.routeoptimization.v1.ShipmentModel.global_end_time]) + and should respect: + + :: + + 0 <= `start_time` <= `soft_start_time` <= `end_time` and + 0 <= `start_time` <= `soft_end_time` <= `end_time`. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + The hard time window start time. If unspecified it will be + set to ``ShipmentModel.global_start_time``. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The hard time window end time. If unspecified it will be set + to ``ShipmentModel.global_end_time``. + soft_start_time (google.protobuf.timestamp_pb2.Timestamp): + The soft start time of the time window. + soft_end_time (google.protobuf.timestamp_pb2.Timestamp): + The soft end time of the time window. + cost_per_hour_before_soft_start_time (float): + A cost per hour added to other costs in the model if the + event occurs before soft_start_time, computed as: + + :: + + max(0, soft_start_time - t.seconds) + * cost_per_hour_before_soft_start_time / 3600, + t being the time of the event. + + This cost must be positive, and the field can only be set if + soft_start_time has been set. + + This field is a member of `oneof`_ ``_cost_per_hour_before_soft_start_time``. + cost_per_hour_after_soft_end_time (float): + A cost per hour added to other costs in the model if the + event occurs after ``soft_end_time``, computed as: + + :: + + max(0, t.seconds - soft_end_time.seconds) + * cost_per_hour_after_soft_end_time / 3600, + t being the time of the event. + + This cost must be positive, and the field can only be set if + ``soft_end_time`` has been set. + + This field is a member of `oneof`_ ``_cost_per_hour_after_soft_end_time``. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + soft_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + soft_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + cost_per_hour_before_soft_start_time: float = proto.Field( + proto.DOUBLE, + number=5, + optional=True, + ) + cost_per_hour_after_soft_end_time: float = proto.Field( + proto.DOUBLE, + number=6, + optional=True, + ) + + +class DistanceLimit(proto.Message): + r"""A limit defining a maximum distance which can be traveled. It can be + either hard or soft. + + If a soft limit is defined, both ``soft_max_meters`` and + ``cost_per_kilometer_above_soft_max`` must be defined and be + nonnegative. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_meters (int): + A hard limit constraining the distance to be at most + max_meters. The limit must be nonnegative. + + This field is a member of `oneof`_ ``_max_meters``. + soft_max_meters (int): + A soft limit not enforcing a maximum distance limit, but + when violated results in a cost which adds up to other costs + defined in the model, with the same unit. + + If defined soft_max_meters must be less than max_meters and + must be nonnegative. + + This field is a member of `oneof`_ ``_soft_max_meters``. + cost_per_kilometer_above_soft_max (float): + Cost per kilometer incurred if distance is above + ``soft_max_meters`` limit. The additional cost is 0 if the + distance is under the limit, otherwise the formula used to + compute the cost is the following: + + :: + + (distance_meters - soft_max_meters) / 1000.0 * + cost_per_kilometer_above_soft_max. + + The cost must be nonnegative. + + This field is a member of `oneof`_ ``_cost_per_kilometer_above_soft_max``. + """ + + max_meters: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + soft_max_meters: int = proto.Field( + proto.INT64, + number=2, + optional=True, + ) + cost_per_kilometer_above_soft_max: float = proto.Field( + proto.DOUBLE, + number=3, + optional=True, + ) + + +class TransitionAttributes(proto.Message): + r"""Specifies attributes of transitions between two consecutive visits + on a route. Several ``TransitionAttributes`` may apply to the same + transition: in that case, all extra costs add up and the strictest + constraint or limit applies (following natural "AND" semantics). + + Attributes: + src_tag (str): + Tags defining the set of (src->dst) transitions these + attributes apply to. + + A source visit or vehicle start matches iff its + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.start_tags][google.maps.routeoptimization.v1.Vehicle.start_tags] + either contains ``src_tag`` or does not contain + ``excluded_src_tag`` (depending on which of these two fields + is non-empty). + excluded_src_tag (str): + See ``src_tag``. Exactly one of ``src_tag`` and + ``excluded_src_tag`` must be non-empty. + dst_tag (str): + A destination visit or vehicle end matches iff its + [VisitRequest.tags][google.maps.routeoptimization.v1.Shipment.VisitRequest.tags] + or + [Vehicle.end_tags][google.maps.routeoptimization.v1.Vehicle.end_tags] + either contains ``dst_tag`` or does not contain + ``excluded_dst_tag`` (depending on which of these two fields + is non-empty). + excluded_dst_tag (str): + See ``dst_tag``. Exactly one of ``dst_tag`` and + ``excluded_dst_tag`` must be non-empty. + cost (float): + Specifies a cost for performing this + transition. This is in the same unit as all + other costs in the model and must not be + negative. It is applied on top of all other + existing costs. + cost_per_kilometer (float): + Specifies a cost per kilometer applied to the distance + traveled while performing this transition. It adds up to any + [Vehicle.cost_per_kilometer][google.maps.routeoptimization.v1.Vehicle.cost_per_kilometer] + specified on vehicles. + distance_limit (google.maps.routeoptimization_v1.types.DistanceLimit): + Specifies a limit on the distance traveled + while performing this transition. + + As of 2021/06, only soft limits are supported. + delay (google.protobuf.duration_pb2.Duration): + Specifies a delay incurred when performing this transition. + + This delay always occurs *after* finishing the source visit + and *before* starting the destination visit. + """ + + src_tag: str = proto.Field( + proto.STRING, + number=1, + ) + excluded_src_tag: str = proto.Field( + proto.STRING, + number=2, + ) + dst_tag: str = proto.Field( + proto.STRING, + number=3, + ) + excluded_dst_tag: str = proto.Field( + proto.STRING, + number=4, + ) + cost: float = proto.Field( + proto.DOUBLE, + number=5, + ) + cost_per_kilometer: float = proto.Field( + proto.DOUBLE, + number=6, + ) + distance_limit: "DistanceLimit" = proto.Field( + proto.MESSAGE, + number=7, + message="DistanceLimit", + ) + delay: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=8, + message=duration_pb2.Duration, + ) + + +class Waypoint(proto.Message): + r"""Encapsulates a waypoint. Waypoints mark arrival and departure + locations of VisitRequests, and start and end locations of + Vehicles. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + location (google.maps.routeoptimization_v1.types.Location): + A point specified using geographic + coordinates, including an optional heading. + + This field is a member of `oneof`_ ``location_type``. + place_id (str): + The POI Place ID associated with the + waypoint. + + This field is a member of `oneof`_ ``location_type``. + side_of_road (bool): + Optional. Indicates that the location of this + waypoint is meant to have a preference for the + vehicle to stop at a particular side of road. + When you set this value, the route will pass + through the location so that the vehicle can + stop at the side of road that the location is + biased towards from the center of the road. This + option doesn't work for the 'WALKING' travel + mode. + """ + + location: "Location" = proto.Field( + proto.MESSAGE, + number=1, + oneof="location_type", + message="Location", + ) + place_id: str = proto.Field( + proto.STRING, + number=2, + oneof="location_type", + ) + side_of_road: bool = proto.Field( + proto.BOOL, + number=3, + ) + + +class Location(proto.Message): + r"""Encapsulates a location (a geographic point, and an optional + heading). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + lat_lng (google.type.latlng_pb2.LatLng): + The waypoint's geographic coordinates. + heading (int): + The compass heading associated with the + direction of the flow of traffic. This value is + used to specify the side of the road to use for + pickup and drop-off. Heading values can be from + 0 to 360, where 0 specifies a heading of due + North, 90 specifies a heading of due East, etc. + + This field is a member of `oneof`_ ``_heading``. + """ + + lat_lng: latlng_pb2.LatLng = proto.Field( + proto.MESSAGE, + number=1, + message=latlng_pb2.LatLng, + ) + heading: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + + +class BreakRule(proto.Message): + r"""Rules to generate time breaks for a vehicle (e.g. lunch breaks). A + break is a contiguous period of time during which the vehicle + remains idle at its current position and cannot perform any visit. A + break may occur: + + - during the travel between two visits (which includes the time + right before or right after a visit, but not in the middle of a + visit), in which case it extends the corresponding transit time + between the visits, + - or before the vehicle start (the vehicle may not start in the + middle of a break), in which case it does not affect the vehicle + start time. + - or after the vehicle end (ditto, with the vehicle end time). + + Attributes: + break_requests (MutableSequence[google.maps.routeoptimization_v1.types.BreakRule.BreakRequest]): + Sequence of breaks. See the ``BreakRequest`` message. + frequency_constraints (MutableSequence[google.maps.routeoptimization_v1.types.BreakRule.FrequencyConstraint]): + Several ``FrequencyConstraint`` may apply. They must all be + satisfied by the ``BreakRequest``\ s of this ``BreakRule``. + See ``FrequencyConstraint``. + """ + + class BreakRequest(proto.Message): + r"""The sequence of breaks (i.e. their number and order) that apply to + each vehicle must be known beforehand. The repeated + ``BreakRequest``\ s define that sequence, in the order in which they + must occur. Their time windows (``earliest_start_time`` / + ``latest_start_time``) may overlap, but they must be compatible with + the order (this is checked). + + Attributes: + earliest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Lower bound (inclusive) on the + start of the break. + latest_start_time (google.protobuf.timestamp_pb2.Timestamp): + Required. Upper bound (inclusive) on the + start of the break. + min_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum duration of the break. Must + be positive. + """ + + earliest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + latest_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + min_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + + class FrequencyConstraint(proto.Message): + r"""One may further constrain the frequency and duration of the breaks + specified above, by enforcing a minimum break frequency, such as + "There must be a break of at least 1 hour every 12 hours". Assuming + that this can be interpreted as "Within any sliding time window of + 12h, there must be at least one break of at least one hour", that + example would translate to the following ``FrequencyConstraint``: + + :: + + { + min_break_duration { seconds: 3600 } # 1 hour. + max_inter_break_duration { seconds: 39600 } # 11 hours (12 - 1 = 11). + } + + The timing and duration of the breaks in the solution will respect + all such constraints, in addition to the time windows and minimum + durations already specified in the ``BreakRequest``. + + A ``FrequencyConstraint`` may in practice apply to non-consecutive + breaks. For example, the following schedule honors the "1h every + 12h" example: + + :: + + 04:00 vehicle start + .. performing travel and visits .. + 09:00 1 hour break + 10:00 end of the break + .. performing travel and visits .. + 12:00 20-min lunch break + 12:20 end of the break + .. performing travel and visits .. + 21:00 1 hour break + 22:00 end of the break + .. performing travel and visits .. + 23:59 vehicle end + + Attributes: + min_break_duration (google.protobuf.duration_pb2.Duration): + Required. Minimum break duration for this constraint. + Nonnegative. See description of ``FrequencyConstraint``. + max_inter_break_duration (google.protobuf.duration_pb2.Duration): + Required. Maximum allowed span of any interval of time in + the route that does not include at least partially a break + of ``duration >= min_break_duration``. Must be positive. + """ + + min_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + max_inter_break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + break_requests: MutableSequence[BreakRequest] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=BreakRequest, + ) + frequency_constraints: MutableSequence[FrequencyConstraint] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=FrequencyConstraint, + ) + + +class ShipmentRoute(proto.Message): + r"""A vehicle's route can be decomposed, along the time axis, like this + (we assume there are n visits): + + :: + + | | | | | T[2], | | | + | Transition | Visit #0 | | | V[2], | | | + | #0 | aka | T[1] | V[1] | ... | V[n-1] | T[n] | + | aka T[0] | V[0] | | | V[n-2],| | | + | | | | | T[n-1] | | | + ^ ^ ^ ^ ^ ^ ^ ^ + vehicle V[0].start V[0].end V[1]. V[1]. V[n]. V[n]. vehicle + start (arrival) (departure) start end start end end + + Note that we make a difference between: + + - "punctual events", such as the vehicle start and end and each + visit's start and end (aka arrival and departure). They happen at + a given second. + - "time intervals", such as the visits themselves, and the + transition between visits. Though time intervals can sometimes + have zero duration, i.e. start and end at the same second, they + often have a positive duration. + + Invariants: + + - If there are n visits, there are n+1 transitions. + - A visit is always surrounded by a transition before it (same + index) and a transition after it (index + 1). + - The vehicle start is always followed by transition #0. + - The vehicle end is always preceded by transition #n. + + Zooming in, here is what happens during a ``Transition`` and a + ``Visit``: + + :: + + ---+-------------------------------------+-----------------------------+--> + | TRANSITION[i] | VISIT[i] | + | | | + | * TRAVEL: the vehicle moves from | PERFORM the visit: | + | VISIT[i-1].departure_location to | | + | VISIT[i].arrival_location, which | * Spend some time: | + | takes a given travel duration | the "visit duration". | + | and distance | | + | | * Load or unload | + | * BREAKS: the driver may have | some quantities from the | + | breaks (e.g. lunch break). | vehicle: the "demand". | + | | | + | * WAIT: the driver/vehicle does | | + | nothing. This can happen for | | + | many reasons, for example when | | + | the vehicle reaches the next | | + | event's destination before the | | + | start of its time window | | + | | | + | * DELAY: *right before* the next | | + | arrival. E.g. the vehicle and/or | | + | driver spends time unloading. | | + | | | + ---+-------------------------------------+-----------------------------+--> + ^ ^ ^ + V[i-1].end V[i].start V[i].end + + Lastly, here is how the TRAVEL, BREAKS, DELAY and WAIT can be + arranged during a transition. + + - They don't overlap. + - The DELAY is unique and *must* be a contiguous period of time + right before the next visit (or vehicle end). Thus, it suffice to + know the delay duration to know its start and end time. + - The BREAKS are contiguous, non-overlapping periods of time. The + response specifies the start time and duration of each break. + - TRAVEL and WAIT are "preemptable": they can be interrupted + several times during this transition. Clients can assume that + travel happens "as soon as possible" and that "wait" fills the + remaining time. + + A (complex) example: + + :: + + TRANSITION[i] + --++-----+-----------------------------------------------------------++--> + || | | | | | | || + || T | B | T | | B | | D || + || r | r | r | W | r | W | e || + || a | e | a | a | e | a | l || + || v | a | v | i | a | i | a || + || e | k | e | t | k | t | y || + || l | | l | | | | || + || | | | | | | || + --++-----------------------------------------------------------------++--> + + Attributes: + vehicle_index (int): + Vehicle performing the route, identified by its index in the + source ``ShipmentModel``. + vehicle_label (str): + Label of the vehicle performing this route, equal to + ``ShipmentModel.vehicles(vehicle_index).label``, if + specified. + vehicle_start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the vehicle starts its route. + vehicle_end_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the vehicle finishes its route. + visits (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Visit]): + Ordered sequence of visits representing a route. visits[i] + is the i-th visit in the route. If this field is empty, the + vehicle is considered as unused. + transitions (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Transition]): + Ordered list of transitions for the route. + has_traffic_infeasibilities (bool): + When + [OptimizeToursRequest.consider_road_traffic][google.maps.routeoptimization.v1.OptimizeToursRequest.consider_road_traffic], + is set to true, this field indicates that inconsistencies in + route timings are predicted using traffic-based travel + duration estimates. There may be insufficient time to + complete traffic-adjusted travel, delays, and breaks between + visits, before the first visit, or after the last visit, + while still satisfying the visit and vehicle time windows. + For example, + + :: + + start_time(previous_visit) + duration(previous_visit) + + travel_duration(previous_visit, next_visit) > start_time(next_visit) + + Arrival at next_visit will likely happen later than its + current time window due the increased estimate of travel + time ``travel_duration(previous_visit, next_visit)`` due to + traffic. Also, a break may be forced to overlap with a visit + due to an increase in travel time estimates and visit or + break time window restrictions. + route_polyline (google.maps.routeoptimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route. This field + is only populated if + [OptimizeToursRequest.populate_polylines][google.maps.routeoptimization.v1.OptimizeToursRequest.populate_polylines] + is set to true. + breaks (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute.Break]): + Breaks scheduled for the vehicle performing this route. The + ``breaks`` sequence represents time intervals, each starting + at the corresponding ``start_time`` and lasting ``duration`` + seconds. + metrics (google.maps.routeoptimization_v1.types.AggregatedMetrics): + Duration, distance and load metrics for this route. The + fields of + [AggregatedMetrics][google.maps.routeoptimization.v1.AggregatedMetrics] + are summed over all + [ShipmentRoute.transitions][google.maps.routeoptimization.v1.ShipmentRoute.transitions] + or + [ShipmentRoute.visits][google.maps.routeoptimization.v1.ShipmentRoute.visits], + depending on the context. + route_costs (MutableMapping[str, float]): + Cost of the route, broken down by cost-related request + fields. The keys are proto paths, relative to the input + OptimizeToursRequest, e.g. "model.shipments.pickups.cost", + and the values are the total cost generated by the + corresponding cost field, aggregated over the whole route. + In other words, costs["model.shipments.pickups.cost"] is the + sum of all pickup costs over the route. All costs defined in + the model are reported in detail here with the exception of + costs related to TransitionAttributes that are only reported + in an aggregated way as of 2022/01. + route_total_cost (float): + Total cost of the route. The sum of all costs + in the cost map. + """ + + class Visit(proto.Message): + r"""A visit performed during a route. This visit corresponds to a pickup + or a delivery of a ``Shipment``. + + Attributes: + shipment_index (int): + Index of the ``shipments`` field in the source + [ShipmentModel][google.maps.routeoptimization.v1.ShipmentModel]. + is_pickup (bool): + If true the visit corresponds to a pickup of a ``Shipment``. + Otherwise, it corresponds to a delivery. + visit_request_index (int): + Index of ``VisitRequest`` in either the pickup or delivery + field of the ``Shipment`` (see ``is_pickup``). + start_time (google.protobuf.timestamp_pb2.Timestamp): + Time at which the visit starts. Note that the vehicle may + arrive earlier than this at the visit location. Times are + consistent with the ``ShipmentModel``. + load_demands (MutableMapping[str, google.maps.routeoptimization_v1.types.Shipment.Load]): + Total visit load demand as the sum of the shipment and the + visit request ``load_demands``. The values are negative if + the visit is a delivery. Demands are reported for the same + types as the + [Transition.loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition] + (see this field). + detour (google.protobuf.duration_pb2.Duration): + Extra detour time due to the shipments visited on the route + before the visit and to the potential waiting time induced + by time windows. If the visit is a delivery, the detour is + computed from the corresponding pickup visit and is equal + to: + + :: + + start_time(delivery) - start_time(pickup) + - (duration(pickup) + travel duration from the pickup location + to the delivery location). + + Otherwise, it is computed from the vehicle + ``start_location`` and is equal to: + + :: + + start_time - vehicle_start_time - travel duration from + the vehicle's `start_location` to the visit. + shipment_label (str): + Copy of the corresponding ``Shipment.label``, if specified + in the ``Shipment``. + visit_label (str): + Copy of the corresponding + [VisitRequest.label][google.maps.routeoptimization.v1.Shipment.VisitRequest.label], + if specified in the ``VisitRequest``. + """ + + shipment_index: int = proto.Field( + proto.INT32, + number=1, + ) + is_pickup: bool = proto.Field( + proto.BOOL, + number=2, + ) + visit_request_index: int = proto.Field( + proto.INT32, + number=3, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + load_demands: MutableMapping[str, "Shipment.Load"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message="Shipment.Load", + ) + detour: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + shipment_label: str = proto.Field( + proto.STRING, + number=7, + ) + visit_label: str = proto.Field( + proto.STRING, + number=8, + ) + + class Transition(proto.Message): + r"""Transition between two events on the route. See the description of + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]. + + If the vehicle does not have a ``start_location`` and/or + ``end_location``, the corresponding travel metrics are 0. + + Attributes: + travel_duration (google.protobuf.duration_pb2.Duration): + Travel duration during this transition. + travel_distance_meters (float): + Distance traveled during the transition. + traffic_info_unavailable (bool): + When traffic is requested via + [OptimizeToursRequest.consider_road_traffic] + [google.maps.routeoptimization.v1.OptimizeToursRequest.consider_road_traffic], + and the traffic info couldn't be retrieved for a + ``Transition``, this boolean is set to true. This may be + temporary (rare hiccup in the realtime traffic servers) or + permanent (no data for this location). + delay_duration (google.protobuf.duration_pb2.Duration): + Sum of the delay durations applied to this transition. If + any, the delay starts exactly ``delay_duration`` seconds + before the next event (visit or vehicle end). See + [TransitionAttributes.delay][google.maps.routeoptimization.v1.TransitionAttributes.delay]. + break_duration (google.protobuf.duration_pb2.Duration): + Sum of the duration of the breaks occurring during this + transition, if any. Details about each break's start time + and duration are stored in + [ShipmentRoute.breaks][google.maps.routeoptimization.v1.ShipmentRoute.breaks]. + wait_duration (google.protobuf.duration_pb2.Duration): + Time spent waiting during this transition. + Wait duration corresponds to idle time and does + not include break time. Also note that this wait + time may be split into several non-contiguous + intervals. + total_duration (google.protobuf.duration_pb2.Duration): + Total duration of the transition, provided for convenience. + It is equal to: + + - next visit ``start_time`` (or ``vehicle_end_time`` if + this is the last transition) - this transition's + ``start_time``; + - if ``ShipmentRoute.has_traffic_infeasibilities`` is + false, the following additionally holds: \`total_duration + = travel_duration + delay_duration + + - break_duration + wait_duration`. + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of this transition. + route_polyline (google.maps.routeoptimization_v1.types.ShipmentRoute.EncodedPolyline): + The encoded polyline representation of the route followed + during the transition. This field is only populated if + [populate_transition_polylines] + [google.maps.routeoptimization.v1.OptimizeToursRequest.populate_transition_polylines] + is set to true. + vehicle_loads (MutableMapping[str, google.maps.routeoptimization_v1.types.ShipmentRoute.VehicleLoad]): + Vehicle loads during this transition, for each type that + either appears in this vehicle's + [Vehicle.load_limits][google.maps.routeoptimization.v1.Vehicle.load_limits], + or that have non-zero + [Shipment.load_demands][google.maps.routeoptimization.v1.Shipment.load_demands] + on some shipment performed on this route. + + The loads during the first transition are the starting loads + of the vehicle route. Then, after each visit, the visit's + ``load_demands`` are either added or subtracted to get the + next transition's loads, depending on whether the visit was + a pickup or a delivery. + """ + + travel_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + travel_distance_meters: float = proto.Field( + proto.DOUBLE, + number=2, + ) + traffic_info_unavailable: bool = proto.Field( + proto.BOOL, + number=3, + ) + delay_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + wait_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + total_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=8, + message=timestamp_pb2.Timestamp, + ) + route_polyline: "ShipmentRoute.EncodedPolyline" = proto.Field( + proto.MESSAGE, + number=9, + message="ShipmentRoute.EncodedPolyline", + ) + vehicle_loads: MutableMapping[ + str, "ShipmentRoute.VehicleLoad" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=11, + message="ShipmentRoute.VehicleLoad", + ) + + class VehicleLoad(proto.Message): + r"""Reports the actual load of the vehicle at some point along the + route, for a given type (see + [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads]). + + Attributes: + amount (int): + The amount of load on the vehicle, for the given type. The + unit of load is usually indicated by the type. See + [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads]. + """ + + amount: int = proto.Field( + proto.INT64, + number=1, + ) + + class EncodedPolyline(proto.Message): + r"""The encoded representation of a polyline. More information on + polyline encoding can be found here: + + https://developers.google.com/maps/documentation/utilities/polylinealgorithm + https://developers.google.com/maps/documentation/javascript/reference/geometry#encoding. + + Attributes: + points (str): + String representing encoded points of the + polyline. + """ + + points: str = proto.Field( + proto.STRING, + number=1, + ) + + class Break(proto.Message): + r"""Data representing the execution of a break. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Start time of a break. + duration (google.protobuf.duration_pb2.Duration): + Duration of a break. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + + vehicle_index: int = proto.Field( + proto.INT32, + number=1, + ) + vehicle_label: str = proto.Field( + proto.STRING, + number=2, + ) + vehicle_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + vehicle_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + visits: MutableSequence[Visit] = proto.RepeatedField( + proto.MESSAGE, + number=7, + message=Visit, + ) + transitions: MutableSequence[Transition] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message=Transition, + ) + has_traffic_infeasibilities: bool = proto.Field( + proto.BOOL, + number=9, + ) + route_polyline: EncodedPolyline = proto.Field( + proto.MESSAGE, + number=10, + message=EncodedPolyline, + ) + breaks: MutableSequence[Break] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=Break, + ) + metrics: "AggregatedMetrics" = proto.Field( + proto.MESSAGE, + number=12, + message="AggregatedMetrics", + ) + route_costs: MutableMapping[str, float] = proto.MapField( + proto.STRING, + proto.DOUBLE, + number=17, + ) + route_total_cost: float = proto.Field( + proto.DOUBLE, + number=18, + ) + + +class SkippedShipment(proto.Message): + r"""Specifies details of unperformed shipments in a solution. For + trivial cases and/or if we are able to identify the cause for + skipping, we report the reason here. + + Attributes: + index (int): + The index corresponds to the index of the shipment in the + source ``ShipmentModel``. + label (str): + Copy of the corresponding + [Shipment.label][google.maps.routeoptimization.v1.Shipment.label], + if specified in the ``Shipment``. + reasons (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment.Reason]): + A list of reasons that explain why the shipment was skipped. + See comment above ``Reason``. + """ + + class Reason(proto.Message): + r"""If we can explain why the shipment was skipped, reasons will be + listed here. If the reason is not the same for all vehicles, + ``reason`` will have more than 1 element. A skipped shipment cannot + have duplicate reasons, i.e. where all fields are the same except + for ``example_vehicle_index``. Example: + + :: + + reasons { + code: DEMAND_EXCEEDS_VEHICLE_CAPACITY + example_vehicle_index: 1 + example_exceeded_capacity_type: "Apples" + } + reasons { + code: DEMAND_EXCEEDS_VEHICLE_CAPACITY + example_vehicle_index: 3 + example_exceeded_capacity_type: "Pears" + } + reasons { + code: CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT + example_vehicle_index: 1 + } + + The skipped shipment is incompatible with all vehicles. The reasons + may be different for all vehicles but at least one vehicle's + "Apples" capacity would be exceeded (including vehicle 1), at least + one vehicle's "Pears" capacity would be exceeded (including vehicle + 3) and at least one vehicle's distance limit would be exceeded + (including vehicle 1). + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + code (google.maps.routeoptimization_v1.types.SkippedShipment.Reason.Code): + Refer to the comments of Code. + example_vehicle_index (int): + If the reason is related to a + shipment-vehicle incompatibility, this field + provides the index of one relevant vehicle. + + This field is a member of `oneof`_ ``_example_vehicle_index``. + example_exceeded_capacity_type (str): + If the reason code is ``DEMAND_EXCEEDS_VEHICLE_CAPACITY``, + documents one capacity type that is exceeded. + """ + + class Code(proto.Enum): + r"""Code identifying the reason type. The order here is + meaningless. In particular, it gives no indication of whether a + given reason will appear before another in the solution, if both + apply. + + Values: + CODE_UNSPECIFIED (0): + This should never be used. If we are unable + to understand why a shipment was skipped, we + simply return an empty set of reasons. + NO_VEHICLE (1): + There is no vehicle in the model making all + shipments infeasible. + DEMAND_EXCEEDS_VEHICLE_CAPACITY (2): + The demand of the shipment exceeds a vehicle's capacity for + some capacity types, one of which is + ``example_exceeded_capacity_type``. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT (3): + The minimum distance necessary to perform this shipment, + i.e. from the vehicle's ``start_location`` to the shipment's + pickup and/or delivery locations and to the vehicle's end + location exceeds the vehicle's ``route_distance_limit``. + + Note that for this computation we use the geodesic + distances. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT (4): + The minimum time necessary to perform this shipment, + including travel time, wait time and service time exceeds + the vehicle's ``route_duration_limit``. + + Note: travel time is computed in the best-case scenario, + namely as geodesic distance x 36 m/s (roughly 130 km/hour). + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT (5): + Same as above but we only compare minimum travel time and + the vehicle's ``travel_duration_limit``. + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS (6): + The vehicle cannot perform this shipment in the best-case + scenario (see + ``CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT`` for + time computation) if it starts at its earliest start time: + the total time would make the vehicle end after its latest + end time. + VEHICLE_NOT_ALLOWED (7): + The ``allowed_vehicle_indices`` field of the shipment is not + empty and this vehicle does not belong to it. + """ + CODE_UNSPECIFIED = 0 + NO_VEHICLE = 1 + DEMAND_EXCEEDS_VEHICLE_CAPACITY = 2 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DISTANCE_LIMIT = 3 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_DURATION_LIMIT = 4 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TRAVEL_DURATION_LIMIT = 5 + CANNOT_BE_PERFORMED_WITHIN_VEHICLE_TIME_WINDOWS = 6 + VEHICLE_NOT_ALLOWED = 7 + + code: "SkippedShipment.Reason.Code" = proto.Field( + proto.ENUM, + number=1, + enum="SkippedShipment.Reason.Code", + ) + example_vehicle_index: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + example_exceeded_capacity_type: str = proto.Field( + proto.STRING, + number=3, + ) + + index: int = proto.Field( + proto.INT32, + number=1, + ) + label: str = proto.Field( + proto.STRING, + number=2, + ) + reasons: MutableSequence[Reason] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=Reason, + ) + + +class AggregatedMetrics(proto.Message): + r"""Aggregated metrics for + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute] + (resp. for + [OptimizeToursResponse][google.maps.routeoptimization.v1.OptimizeToursResponse] + over all + [Transition][google.maps.routeoptimization.v1.ShipmentRoute.Transition] + and/or [Visit][google.maps.routeoptimization.v1.ShipmentRoute.Visit] + (resp. over all + [ShipmentRoute][google.maps.routeoptimization.v1.ShipmentRoute]) + elements. + + Attributes: + performed_shipment_count (int): + Number of shipments performed. Note that a + pickup and delivery pair only counts once. + travel_duration (google.protobuf.duration_pb2.Duration): + Total travel duration for a route or a + solution. + wait_duration (google.protobuf.duration_pb2.Duration): + Total wait duration for a route or a + solution. + delay_duration (google.protobuf.duration_pb2.Duration): + Total delay duration for a route or a + solution. + break_duration (google.protobuf.duration_pb2.Duration): + Total break duration for a route or a + solution. + visit_duration (google.protobuf.duration_pb2.Duration): + Total visit duration for a route or a + solution. + total_duration (google.protobuf.duration_pb2.Duration): + The total duration should be equal to the sum of all + durations above. For routes, it also corresponds to: + + :: + + [ShipmentRoute.vehicle_end_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_end_time] + - + [ShipmentRoute.vehicle_start_time][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_start_time] + travel_distance_meters (float): + Total travel distance for a route or a + solution. + max_loads (MutableMapping[str, google.maps.routeoptimization_v1.types.ShipmentRoute.VehicleLoad]): + Maximum load achieved over the entire route (resp. + solution), for each of the quantities on this route (resp. + solution), computed as the maximum over all + [Transition.vehicle_loads][google.maps.routeoptimization.v1.ShipmentRoute.Transition.vehicle_loads] + (resp. + [ShipmentRoute.metrics.max_loads][google.maps.routeoptimization.v1.AggregatedMetrics.max_loads]. + """ + + performed_shipment_count: int = proto.Field( + proto.INT32, + number=1, + ) + travel_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + wait_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + delay_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + break_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=5, + message=duration_pb2.Duration, + ) + visit_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=6, + message=duration_pb2.Duration, + ) + total_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) + travel_distance_meters: float = proto.Field( + proto.DOUBLE, + number=8, + ) + max_loads: MutableMapping[str, "ShipmentRoute.VehicleLoad"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=9, + message="ShipmentRoute.VehicleLoad", + ) + + +class InjectedSolutionConstraint(proto.Message): + r"""Solution injected in the request including information about + which visits must be constrained and how they must be + constrained. + + Attributes: + routes (MutableSequence[google.maps.routeoptimization_v1.types.ShipmentRoute]): + Routes of the solution to inject. Some routes may be omitted + from the original solution. The routes and skipped shipments + must satisfy the basic validity assumptions listed for + ``injected_first_solution_routes``. + skipped_shipments (MutableSequence[google.maps.routeoptimization_v1.types.SkippedShipment]): + Skipped shipments of the solution to inject. Some may be + omitted from the original solution. See the ``routes`` + field. + constraint_relaxations (MutableSequence[google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation]): + For zero or more groups of vehicles, + specifies when and how much to relax + constraints. If this field is empty, all + non-empty vehicle routes are fully constrained. + """ + + class ConstraintRelaxation(proto.Message): + r"""For a group of vehicles, specifies at what threshold(s) constraints + on visits will be relaxed and to which level. Shipments listed in + the ``skipped_shipment`` field are constrained to be skipped; i.e., + they cannot be performed. + + Attributes: + relaxations (MutableSequence[google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation]): + All the visit constraint relaxations that will apply to + visits on routes with vehicles in ``vehicle_indices``. + vehicle_indices (MutableSequence[int]): + Specifies the vehicle indices to which the visit constraint + ``relaxations`` apply. If empty, this is considered the + default and the ``relaxations`` apply to all vehicles that + are not specified in other ``constraint_relaxations``. There + can be at most one default, i.e., at most one constraint + relaxation field is allowed empty ``vehicle_indices``. A + vehicle index can only be listed once, even within several + ``constraint_relaxations``. + + A vehicle index is mapped the same as + [ShipmentRoute.vehicle_index][google.maps.routeoptimization.v1.ShipmentRoute.vehicle_index], + if ``interpret_injected_solutions_using_labels`` is true + (see ``fields`` comment). + """ + + class Relaxation(proto.Message): + r"""If ``relaxations`` is empty, the start time and sequence of all + visits on ``routes`` are fully constrained and no new visits may be + inserted or added to those routes. Also, a vehicle's start and end + time in ``routes`` is fully constrained, unless the vehicle is empty + (i.e., has no visits and has ``used_if_route_is_empty`` set to false + in the model). + + ``relaxations(i).level`` specifies the constraint relaxation level + applied to a visit #j that satisfies: + + - ``route.visits(j).start_time >= relaxations(i).threshold_time`` + AND + - ``j + 1 >= relaxations(i).threshold_visit_count`` + + Similarly, the vehicle start is relaxed to ``relaxations(i).level`` + if it satisfies: + + - ``vehicle_start_time >= relaxations(i).threshold_time`` AND + - ``relaxations(i).threshold_visit_count == 0`` and the vehicle end + is relaxed to ``relaxations(i).level`` if it satisfies: + - ``vehicle_end_time >= relaxations(i).threshold_time`` AND + - ``route.visits_size() + 1 >= relaxations(i).threshold_visit_count`` + + To apply a relaxation level if a visit meets the + ``threshold_visit_count`` OR the ``threshold_time`` add two + ``relaxations`` with the same ``level``: one with only + ``threshold_visit_count`` set and the other with only + ``threshold_time`` set. If a visit satisfies the conditions of + multiple ``relaxations``, the most relaxed level applies. As a + result, from the vehicle start through the route visits in order to + the vehicle end, the relaxation level becomes more relaxed: i.e., + the relaxation level is non-decreasing as the route progresses. + + The timing and sequence of route visits that do not satisfy the + threshold conditions of any ``relaxations`` are fully constrained + and no visits may be inserted into these sequences. Also, if a + vehicle start or end does not satisfy the conditions of any + relaxation the time is fixed, unless the vehicle is empty. + + Attributes: + level (google.maps.routeoptimization_v1.types.InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level): + The constraint relaxation level that applies when the + conditions at or after ``threshold_time`` AND at least + ``threshold_visit_count`` are satisfied. + threshold_time (google.protobuf.timestamp_pb2.Timestamp): + The time at or after which the relaxation ``level`` may be + applied. + threshold_visit_count (int): + The number of visits at or after which the relaxation + ``level`` may be applied. If ``threshold_visit_count`` is 0 + (or unset), the ``level`` may be applied directly at the + vehicle start. + + If it is ``route.visits_size() + 1``, the ``level`` may only + be applied to the vehicle end. If it is more than + ``route.visits_size() + 1``, ``level`` is not applied at all + for that route. + """ + + class Level(proto.Enum): + r"""Expresses the different constraint relaxation levels, which + are applied for a visit and those that follow when it satisfies + the threshold conditions. + + The enumeration below is in order of increasing relaxation. + + Values: + LEVEL_UNSPECIFIED (0): + Implicit default relaxation level: no constraints are + relaxed, i.e., all visits are fully constrained. + + This value must not be explicitly used in ``level``. + RELAX_VISIT_TIMES_AFTER_THRESHOLD (1): + Visit start times and vehicle start/end times + will be relaxed, but each visit remains bound to + the same vehicle and the visit sequence must be + observed: no visit can be inserted between them + or before them. + RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD (2): + Same as ``RELAX_VISIT_TIMES_AFTER_THRESHOLD``, but the visit + sequence is also relaxed: visits remain simply bound to + their vehicle. + RELAX_ALL_AFTER_THRESHOLD (3): + Same as ``RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD``, + but the vehicle is also relaxed: visits are completely free + at or after the threshold time and can potentially become + unperformed. + """ + LEVEL_UNSPECIFIED = 0 + RELAX_VISIT_TIMES_AFTER_THRESHOLD = 1 + RELAX_VISIT_TIMES_AND_SEQUENCE_AFTER_THRESHOLD = 2 + RELAX_ALL_AFTER_THRESHOLD = 3 + + level: "InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level" = proto.Field( + proto.ENUM, + number=1, + enum="InjectedSolutionConstraint.ConstraintRelaxation.Relaxation.Level", + ) + threshold_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + threshold_visit_count: int = proto.Field( + proto.INT32, + number=3, + ) + + relaxations: MutableSequence[ + "InjectedSolutionConstraint.ConstraintRelaxation.Relaxation" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="InjectedSolutionConstraint.ConstraintRelaxation.Relaxation", + ) + vehicle_indices: MutableSequence[int] = proto.RepeatedField( + proto.INT32, + number=2, + ) + + routes: MutableSequence["ShipmentRoute"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ShipmentRoute", + ) + skipped_shipments: MutableSequence["SkippedShipment"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SkippedShipment", + ) + constraint_relaxations: MutableSequence[ConstraintRelaxation] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=ConstraintRelaxation, + ) + + +class OptimizeToursValidationError(proto.Message): + r"""Describes an error encountered when validating an + ``OptimizeToursRequest``. + + Attributes: + code (int): + A validation error is defined by the pair (``code``, + ``display_name``) which are always present. + + Other fields (below) provide more context about the error. + + *MULTIPLE ERRORS*: When there are multiple errors, the + validation process tries to output several of them. Much + like a compiler, this is an imperfect process. Some + validation errors will be "fatal", meaning that they stop + the entire validation process. This is the case for + ``display_name="UNSPECIFIED"`` errors, among others. Some + may cause the validation process to skip other errors. + + *STABILITY*: ``code`` and ``display_name`` should be very + stable. But new codes and display names may appear over + time, which may cause a given (invalid) request to yield a + different (``code``, ``display_name``) pair because the new + error hid the old one (see "MULTIPLE ERRORS"). + + *REFERENCE*: A list of all (code, name) pairs: + + - UNSPECIFIED = 0; + + - VALIDATION_TIMEOUT_ERROR = 10; Validation couldn't be + completed within the deadline. + + - REQUEST_OPTIONS_ERROR = 12; + + - REQUEST_OPTIONS_INVALID_SOLVING_MODE = 1201; + - REQUEST_OPTIONS_INVALID_MAX_VALIDATION_ERRORS = 1203; + - REQUEST_OPTIONS_INVALID_GEODESIC_METERS_PER_SECOND = + 1204; + - REQUEST_OPTIONS_GEODESIC_METERS_PER_SECOND_TOO_SMALL = + 1205; + - REQUEST_OPTIONS_MISSING_GEODESIC_METERS_PER_SECOND = + 1206; + - REQUEST_OPTIONS_POPULATE_PATHFINDER_TRIPS_AND_GEODESIC_DISTANCE + = 1207; + - REQUEST_OPTIONS_COST_MODEL_OPTIONS_AND_GEODESIC_DISTANCE + = 1208; + - REQUEST_OPTIONS_TRAVEL_MODE_INCOMPATIBLE_WITH_TRAFFIC + = 1211; + - REQUEST_OPTIONS_MULTIPLE_TRAFFIC_FLAVORS = 1212; + - REQUEST_OPTIONS_INVALID_TRAFFIC_FLAVOR = 1213; + - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITHOUT_GLOBAL_START_TIME + = 1214; + - REQUEST_OPTIONS_TRAFFIC_ENABLED_WITH_PRECEDENCES = + 1215; + - REQUEST_OPTIONS_TRAFFIC_PREFILL_MODE_INVALID = 1216; + - REQUEST_OPTIONS_TRAFFIC_PREFILL_ENABLED_WITHOUT_TRAFFIC + = 1217; + + - INJECTED_SOLUTION_ERROR = 20; + + - INJECTED_SOLUTION_MISSING_LABEL = 2000; + - INJECTED_SOLUTION_DUPLICATE_LABEL = 2001; + - INJECTED_SOLUTION_AMBIGUOUS_INDEX = 2002; + - INJECTED_SOLUTION_INFEASIBLE_AFTER_GETTING_TRAVEL_TIMES + = 2003; + - INJECTED_SOLUTION_TRANSITION_INCONSISTENT_WITH_ACTUAL_TRAVEL + = 2004; + - INJECTED_SOLUTION_CONCURRENT_SOLUTION_TYPES = 2005; + - INJECTED_SOLUTION_MORE_THAN_ONE_PER_TYPE = 2006; + - INJECTED_SOLUTION_REFRESH_WITHOUT_POPULATE = 2008; + - INJECTED_SOLUTION_CONSTRAINED_ROUTE_PORTION_INFEASIBLE + = 2010; + + - SHIPMENT_MODEL_ERROR = 22; + + - SHIPMENT_MODEL_TOO_LARGE = 2200; + - SHIPMENT_MODEL_TOO_MANY_CAPACITY_TYPES = 2201; + - SHIPMENT_MODEL_GLOBAL_START_TIME_NEGATIVE_OR_NAN = + 2202; + - SHIPMENT_MODEL_GLOBAL_END_TIME_TOO_LARGE_OR_NAN = + 2203; + - SHIPMENT_MODEL_GLOBAL_START_TIME_AFTER_GLOBAL_END_TIME + = 2204; + - SHIPMENT_MODEL_GLOBAL_DURATION_TOO_LONG = 2205; + - SHIPMENT_MODEL_MAX_ACTIVE_VEHICLES_NOT_POSITIVE = + 2206; + - SHIPMENT_MODEL_DURATION_MATRIX_TOO_LARGE = 2207; + + - INDEX_ERROR = 24; + + - TAG_ERROR = 26; + + - TIME_WINDOW_ERROR = 28; + + - TIME_WINDOW_INVALID_START_TIME = 2800; + - TIME_WINDOW_INVALID_END_TIME = 2801; + - TIME_WINDOW_INVALID_SOFT_START_TIME = 2802; + - TIME_WINDOW_INVALID_SOFT_END_TIME = 2803; + - TIME_WINDOW_OUTSIDE_GLOBAL_TIME_WINDOW = 2804; + - TIME_WINDOW_START_TIME_AFTER_END_TIME = 2805; + - TIME_WINDOW_INVALID_COST_PER_HOUR_BEFORE_SOFT_START_TIME + = 2806; + - TIME_WINDOW_INVALID_COST_PER_HOUR_AFTER_SOFT_END_TIME + = 2807; + - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_WITHOUT_SOFT_START_TIME + = 2808; + - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_WITHOUT_SOFT_END_TIME + = 2809; + - TIME_WINDOW_SOFT_START_TIME_WITHOUT_COST_BEFORE_SOFT_START_TIME + = 2810; + - TIME_WINDOW_SOFT_END_TIME_WITHOUT_COST_AFTER_SOFT_END_TIME + = 2811; + - TIME_WINDOW_OVERLAPPING_ADJACENT_OR_EARLIER_THAN_PREVIOUS + = 2812; + - TIME_WINDOW_START_TIME_AFTER_SOFT_START_TIME = 2813; + - TIME_WINDOW_SOFT_START_TIME_AFTER_END_TIME = 2814; + - TIME_WINDOW_START_TIME_AFTER_SOFT_END_TIME = 2815; + - TIME_WINDOW_SOFT_END_TIME_AFTER_END_TIME = 2816; + - TIME_WINDOW_COST_BEFORE_SOFT_START_TIME_SET_AND_MULTIPLE_WINDOWS + = 2817; + - TIME_WINDOW_COST_AFTER_SOFT_END_TIME_SET_AND_MULTIPLE_WINDOWS + = 2818; + - TRANSITION_ATTRIBUTES_ERROR = 30; + - TRANSITION_ATTRIBUTES_INVALID_COST = 3000; + - TRANSITION_ATTRIBUTES_INVALID_COST_PER_KILOMETER = + 3001; + - TRANSITION_ATTRIBUTES_DUPLICATE_TAG_PAIR = 3002; + - TRANSITION_ATTRIBUTES_DISTANCE_LIMIT_MAX_METERS_UNSUPPORTED + = 3003; + - TRANSITION_ATTRIBUTES_UNSPECIFIED_SOURCE_TAGS = 3004; + - TRANSITION_ATTRIBUTES_CONFLICTING_SOURCE_TAGS_FIELDS = + 3005; + - TRANSITION_ATTRIBUTES_UNSPECIFIED_DESTINATION_TAGS = + 3006; + - TRANSITION_ATTRIBUTES_CONFLICTING_DESTINATION_TAGS_FIELDS + = 3007; + - TRANSITION_ATTRIBUTES_DELAY_DURATION_NEGATIVE_OR_NAN = + 3008; + - TRANSITION_ATTRIBUTES_DELAY_DURATION_EXCEEDS_GLOBAL_DURATION + = 3009; + + - AMOUNT_ERROR = 31; + + - AMOUNT_NEGATIVE_VALUE = 3100; + + - LOAD_LIMIT_ERROR = 33; + + - LOAD_LIMIT_INVALID_COST_ABOVE_SOFT_MAX = 3303; + - LOAD_LIMIT_SOFT_MAX_WITHOUT_COST_ABOVE_SOFT_MAX = + 3304; + - LOAD_LIMIT_COST_ABOVE_SOFT_MAX_WITHOUT_SOFT_MAX = + 3305; + - LOAD_LIMIT_NEGATIVE_SOFT_MAX = 3306; + - LOAD_LIMIT_MIXED_DEMAND_TYPE = 3307; + - LOAD_LIMIT_MAX_LOAD_NEGATIVE_VALUE = 3308; + - LOAD_LIMIT_SOFT_MAX_ABOVE_MAX = 3309; + + - INTERVAL_ERROR = 34; + + - INTERVAL_MIN_EXCEEDS_MAX = 3401; + - INTERVAL_NEGATIVE_MIN = 3402; + - INTERVAL_NEGATIVE_MAX = 3403; + - INTERVAL_MIN_EXCEEDS_CAPACITY = 3404; + - INTERVAL_MAX_EXCEEDS_CAPACITY = 3405; + + - DISTANCE_LIMIT_ERROR = 36; + + - DISTANCE_LIMIT_INVALID_COST_AFTER_SOFT_MAX = 3601; + - DISTANCE_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = + 3602; + - DISTANCE_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = + 3603; + - DISTANCE_LIMIT_NEGATIVE_MAX = 3604; + - DISTANCE_LIMIT_NEGATIVE_SOFT_MAX = 3605; + - DISTANCE_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3606; + + - DURATION_LIMIT_ERROR = 38; + + - DURATION_LIMIT_MAX_DURATION_NEGATIVE_OR_NAN = 3800; + - DURATION_LIMIT_SOFT_MAX_DURATION_NEGATIVE_OR_NAN = + 3801; + - DURATION_LIMIT_INVALID_COST_PER_HOUR_AFTER_SOFT_MAX = + 3802; + - DURATION_LIMIT_SOFT_MAX_WITHOUT_COST_AFTER_SOFT_MAX = + 3803; + - DURATION_LIMIT_COST_AFTER_SOFT_MAX_WITHOUT_SOFT_MAX = + 3804; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_NEGATIVE_OR_NAN + = 3805; + - DURATION_LIMIT_INVALID_COST_AFTER_QUADRATIC_SOFT_MAX = + 3806; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_COST_PER_SQUARE_HOUR + = 3807; + - DURATION_LIMIT_COST_PER_SQUARE_HOUR_WITHOUT_QUADRATIC_SOFT_MAX + = 3808; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_WITHOUT_MAX = 3809; + - DURATION_LIMIT_SOFT_MAX_LARGER_THAN_MAX = 3810; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_LARGER_THAN_MAX = + 3811; + - DURATION_LIMIT_DIFF_BETWEEN_MAX_AND_QUADRATIC_SOFT_MAX_TOO_LARGE + = 3812; + - DURATION_LIMIT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION = + 3813; + - DURATION_LIMIT_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION + = 3814; + - DURATION_LIMIT_QUADRATIC_SOFT_MAX_DURATION_EXCEEDS_GLOBAL_DURATION + = 3815; + + - SHIPMENT_ERROR = 40; + + - SHIPMENT_PD_LIMIT_WITHOUT_PICKUP_AND_DELIVERY = 4014; + - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_NEGATIVE_OR_NAN + = 4000; + - SHIPMENT_PD_ABSOLUTE_DETOUR_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION + = 4001; + - SHIPMENT_PD_RELATIVE_DETOUR_LIMIT_INVALID = 4015; + - SHIPMENT_PD_DETOUR_LIMIT_AND_EXTRA_VISIT_DURATION = + 4016; + - SHIPMENT_PD_TIME_LIMIT_DURATION_NEGATIVE_OR_NAN = + 4002; + - SHIPMENT_PD_TIME_LIMIT_DURATION_EXCEEDS_GLOBAL_DURATION + = 4003; + - SHIPMENT_EMPTY_SHIPMENT_TYPE = 4004; + - SHIPMENT_NO_PICKUP_NO_DELIVERY = 4005; + - SHIPMENT_INVALID_PENALTY_COST = 4006; + - SHIPMENT_ALLOWED_VEHICLE_INDEX_OUT_OF_BOUNDS = 4007; + - SHIPMENT_DUPLICATE_ALLOWED_VEHICLE_INDEX = 4008; + - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITHOUT_INDEX + = 4009; + - SHIPMENT_INCONSISTENT_COST_FOR_VEHICLE_SIZE_WITH_INDEX + = 4010; + - SHIPMENT_INVALID_COST_FOR_VEHICLE = 4011; + - SHIPMENT_COST_FOR_VEHICLE_INDEX_OUT_OF_BOUNDS = 4012; + - SHIPMENT_DUPLICATE_COST_FOR_VEHICLE_INDEX = 4013; + + - VEHICLE_ERROR = 42; + + - VEHICLE_EMPTY_REQUIRED_OPERATOR_TYPE = 4200; + - VEHICLE_DUPLICATE_REQUIRED_OPERATOR_TYPE = 4201; + - VEHICLE_NO_OPERATOR_WITH_REQUIRED_OPERATOR_TYPE = + 4202; + - VEHICLE_EMPTY_START_TAG = 4203; + - VEHICLE_DUPLICATE_START_TAG = 4204; + - VEHICLE_EMPTY_END_TAG = 4205; + - VEHICLE_DUPLICATE_END_TAG = 4206; + - VEHICLE_EXTRA_VISIT_DURATION_NEGATIVE_OR_NAN = 4207; + - VEHICLE_EXTRA_VISIT_DURATION_EXCEEDS_GLOBAL_DURATION = + 4208; + - VEHICLE_EXTRA_VISIT_DURATION_EMPTY_KEY = 4209; + - VEHICLE_FIRST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4210; + - VEHICLE_FIRST_SHIPMENT_IGNORED = 4211; + - VEHICLE_FIRST_SHIPMENT_NOT_BOUND = 4212; + - VEHICLE_LAST_SHIPMENT_INDEX_OUT_OF_BOUNDS = 4213; + - VEHICLE_LAST_SHIPMENT_IGNORED = 4214; + - VEHICLE_LAST_SHIPMENT_NOT_BOUND = 4215; + - VEHICLE_IGNORED_WITH_USED_IF_ROUTE_IS_EMPTY = 4216; + - VEHICLE_INVALID_COST_PER_KILOMETER = 4217; + - VEHICLE_INVALID_COST_PER_HOUR = 4218; + - VEHICLE_INVALID_COST_PER_TRAVELED_HOUR = 4219; + - VEHICLE_INVALID_FIXED_COST = 4220; + - VEHICLE_INVALID_TRAVEL_DURATION_MULTIPLE = 4221; + - VEHICLE_TRAVEL_DURATION_MULTIPLE_WITH_SHIPMENT_PD_DETOUR_LIMITS + = 4223; + - VEHICLE_MATRIX_INDEX_WITH_SHIPMENT_PD_DETOUR_LIMITS = + 4224; + - VEHICLE_MINIMUM_DURATION_LONGER_THAN_DURATION_LIMIT = + 4222; + + - VISIT_REQUEST_ERROR = 44; + + - VISIT_REQUEST_EMPTY_TAG = 4400; + - VISIT_REQUEST_DUPLICATE_TAG = 4401; + - VISIT_REQUEST_DURATION_NEGATIVE_OR_NAN = 4404; + - VISIT_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4405; + + - PRECEDENCE_ERROR = 46; + + - BREAK_ERROR = 48; + + - BREAK_RULE_EMPTY = 4800; + - BREAK_REQUEST_UNSPECIFIED_DURATION = 4801; + - BREAK_REQUEST_UNSPECIFIED_EARLIEST_START_TIME = 4802; + - BREAK_REQUEST_UNSPECIFIED_LATEST_START_TIME = 4803; + - BREAK_REQUEST_DURATION_NEGATIVE_OR_NAN = 4804; = 4804; + - BREAK_REQUEST_LATEST_START_TIME_BEFORE_EARLIEST_START_TIME + = 4805; + - BREAK_REQUEST_EARLIEST_START_TIME_BEFORE_GLOBAL_START_TIME + = 4806; + - BREAK_REQUEST_LATEST_END_TIME_AFTER_GLOBAL_END_TIME = + 4807; + - BREAK_REQUEST_NON_SCHEDULABLE = 4808; + - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_NEGATIVE_OR_NAN + = 4809; + - BREAK_FREQUENCY_MIN_BREAK_DURATION_NEGATIVE_OR_NAN = + 4810; + - BREAK_FREQUENCY_MIN_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION + = 4811; + - BREAK_FREQUENCY_MAX_INTER_BREAK_DURATION_EXCEEDS_GLOBAL_DURATION + = 4812; + - BREAK_REQUEST_DURATION_EXCEEDS_GLOBAL_DURATION = 4813; + - BREAK_FREQUENCY_MISSING_MAX_INTER_BREAK_DURATION = + 4814; + - BREAK_FREQUENCY_MISSING_MIN_BREAK_DURATION = 4815; + + - SHIPMENT_TYPE_INCOMPATIBILITY_ERROR = 50; + + - SHIPMENT_TYPE_INCOMPATIBILITY_EMPTY_TYPE = 5001; + - SHIPMENT_TYPE_INCOMPATIBILITY_LESS_THAN_TWO_TYPES = + 5002; + - SHIPMENT_TYPE_INCOMPATIBILITY_DUPLICATE_TYPE = 5003; + - SHIPMENT_TYPE_INCOMPATIBILITY_INVALID_INCOMPATIBILITY_MODE + = 5004; + - SHIPMENT_TYPE_INCOMPATIBILITY_TOO_MANY_INCOMPATIBILITIES + = 5005; + + - SHIPMENT_TYPE_REQUIREMENT_ERROR = 52; + + - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE = 52001; + - SHIPMENT_TYPE_REQUIREMENT_NO_DEPENDENT_TYPE = 52002; + - SHIPMENT_TYPE_REQUIREMENT_INVALID_REQUIREMENT_MODE = + 52003; + - SHIPMENT_TYPE_REQUIREMENT_TOO_MANY_REQUIREMENTS = + 52004; + - SHIPMENT_TYPE_REQUIREMENT_EMPTY_REQUIRED_TYPE = 52005; + - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_REQUIRED_TYPE = + 52006; + - SHIPMENT_TYPE_REQUIREMENT_NO_REQUIRED_TYPE_FOUND = + 52007; + - SHIPMENT_TYPE_REQUIREMENT_EMPTY_DEPENDENT_TYPE = + 52008; + - SHIPMENT_TYPE_REQUIREMENT_DUPLICATE_DEPENDENT_TYPE = + 52009; + - SHIPMENT_TYPE_REQUIREMENT_SELF_DEPENDENT_TYPE = 52010; + - SHIPMENT_TYPE_REQUIREMENT_GRAPH_HAS_CYCLES = 52011; + + - VEHICLE_OPERATOR_ERROR = 54; + + - VEHICLE_OPERATOR_EMPTY_TYPE = 5400; + - VEHICLE_OPERATOR_MULTIPLE_START_TIME_WINDOWS = 5401; + - VEHICLE_OPERATOR_SOFT_START_TIME_WINDOW = 5402; + - VEHICLE_OPERATOR_MULTIPLE_END_TIME_WINDOWS = 5403; + - VEHICLE_OPERATOR_SOFT_END_TIME_WINDOW = 5404; + + - DURATION_SECONDS_MATRIX_ERROR = 56; + + - DURATION_SECONDS_MATRIX_DURATION_NEGATIVE_OR_NAN = + 5600; + - DURATION_SECONDS_MATRIX_DURATION_EXCEEDS_GLOBAL_DURATION + = 5601; + display_name (str): + The error display name. + fields (MutableSequence[google.maps.routeoptimization_v1.types.OptimizeToursValidationError.FieldReference]): + An error context may involve 0, 1 (most of the time) or more + fields. For example, referring to vehicle #4 and shipment + #2's first pickup can be done as follows: + + :: + + fields { name: "vehicles" index: 4} + fields { name: "shipments" index: 2 sub_field {name: "pickups" index: 0} } + + Note, however, that the cardinality of ``fields`` should not + change for a given error code. + error_message (str): + Human-readable string describing the error. There is a 1:1 + mapping between ``code`` and ``error_message`` (when code != + "UNSPECIFIED"). + + *STABILITY*: Not stable: the error message associated to a + given ``code`` may change (hopefully to clarify it) over + time. Please rely on the ``display_name`` and ``code`` + instead. + offending_values (str): + May contain the value(s) of the field(s). + This is not always available. You should + absolutely not rely on it and use it only for + manual model debugging. + """ + + class FieldReference(proto.Message): + r"""Specifies a context for the validation error. A ``FieldReference`` + always refers to a given field in this file and follows the same + hierarchical structure. For example, we may specify element #2 of + ``start_time_windows`` of vehicle #5 using: + + :: + + name: "vehicles" index: 5 sub_field { name: "end_time_windows" index: 2 } + + We however omit top-level entities such as ``OptimizeToursRequest`` + or ``ShipmentModel`` to avoid crowding the message. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Name of the field, e.g., "vehicles". + index (int): + Index of the field if repeated. + + This field is a member of `oneof`_ ``index_or_key``. + key (str): + Key if the field is a map. + + This field is a member of `oneof`_ ``index_or_key``. + sub_field (google.maps.routeoptimization_v1.types.OptimizeToursValidationError.FieldReference): + Recursively nested sub-field, if needed. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + index: int = proto.Field( + proto.INT32, + number=2, + oneof="index_or_key", + ) + key: str = proto.Field( + proto.STRING, + number=4, + oneof="index_or_key", + ) + sub_field: "OptimizeToursValidationError.FieldReference" = proto.Field( + proto.MESSAGE, + number=3, + message="OptimizeToursValidationError.FieldReference", + ) + + code: int = proto.Field( + proto.INT32, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + fields: MutableSequence[FieldReference] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=FieldReference, + ) + error_message: str = proto.Field( + proto.STRING, + number=4, + ) + offending_values: str = proto.Field( + proto.STRING, + number=5, + ) + + +class InputConfig(proto.Message): + r"""Specify an input for + [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_source (google.maps.routeoptimization_v1.types.GcsSource): + A Google Cloud Storage location. This must be + a single object (file). + + This field is a member of `oneof`_ ``source``. + data_format (google.maps.routeoptimization_v1.types.DataFormat): + Required. The input data format. + """ + + gcs_source: "GcsSource" = proto.Field( + proto.MESSAGE, + number=1, + oneof="source", + message="GcsSource", + ) + data_format: "DataFormat" = proto.Field( + proto.ENUM, + number=2, + enum="DataFormat", + ) + + +class OutputConfig(proto.Message): + r"""Specify a destination for + [BatchOptimizeTours][google.maps.routeoptimization.v1.RouteOptimizationService.BatchOptimizeTours] + results. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_destination (google.maps.routeoptimization_v1.types.GcsDestination): + The Google Cloud Storage location to write + the output to. + + This field is a member of `oneof`_ ``destination``. + data_format (google.maps.routeoptimization_v1.types.DataFormat): + Required. The output data format. + """ + + gcs_destination: "GcsDestination" = proto.Field( + proto.MESSAGE, + number=1, + oneof="destination", + message="GcsDestination", + ) + data_format: "DataFormat" = proto.Field( + proto.ENUM, + number=2, + enum="DataFormat", + ) + + +class GcsSource(proto.Message): + r"""The Google Cloud Storage location where the input file will + be read from. + + Attributes: + uri (str): + Required. URI of a Google Cloud Storage object with the + format ``gs://bucket/path/to/object``. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GcsDestination(proto.Message): + r"""The Google Cloud Storage location where the output file(s) + will be written to. + + Attributes: + uri (str): + Required. Google Cloud Storage URI. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-maps-routeoptimization/mypy.ini b/packages/google-maps-routeoptimization/mypy.ini new file mode 100644 index 000000000000..574c5aed394b --- /dev/null +++ b/packages/google-maps-routeoptimization/mypy.ini @@ -0,0 +1,3 @@ +[mypy] +python_version = 3.7 +namespace_packages = True diff --git a/packages/google-maps-routeoptimization/noxfile.py b/packages/google-maps-routeoptimization/noxfile.py new file mode 100644 index 000000000000..1e6cd48d0529 --- /dev/null +++ b/packages/google-maps-routeoptimization/noxfile.py @@ -0,0 +1,428 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2023 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 +# +# https://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. + +# Generated by synthtool. DO NOT EDIT! + +from __future__ import absolute_import + +import os +import pathlib +import re +import shutil +from typing import Dict, List +import warnings + +import nox + +BLACK_VERSION = "black[jupyter]==23.7.0" +ISORT_VERSION = "isort==5.11.0" + +LINT_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] + + +DEFAULT_PYTHON_VERSION = "3.10" + +UNIT_TEST_PYTHON_VERSIONS: List[str] = ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] +UNIT_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "asyncmock", + "pytest", + "pytest-cov", + "pytest-asyncio", +] +UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = [] +UNIT_TEST_DEPENDENCIES: List[str] = [] +UNIT_TEST_EXTRAS: List[str] = [] +UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +SYSTEM_TEST_PYTHON_VERSIONS: List[str] = ["3.8", "3.9", "3.10", "3.11", "3.12"] +SYSTEM_TEST_STANDARD_DEPENDENCIES = [ + "mock", + "pytest", + "google-cloud-testutils", +] +SYSTEM_TEST_EXTERNAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_DEPENDENCIES: List[str] = [] +SYSTEM_TEST_EXTRAS: List[str] = [] +SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {} + +CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute() + +# 'docfx' is excluded since it only needs to run in 'docs-presubmit' +nox.options.sessions = [ + "unit", + "system", + "cover", + "lint", + "lint_setup_py", + "blacken", + "docs", +] + +# Error if a python version is missing +nox.options.error_on_missing_interpreters = True + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint(session): + """Run linters. + + Returns a failure if the linters find linting errors or sufficiently + serious code quality issues. + """ + session.install("flake8", BLACK_VERSION) + session.run( + "black", + "--check", + *LINT_PATHS, + ) + + session.run("flake8", "google", "tests") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def blacken(session): + """Run black. Format code to uniform standard.""" + session.install(BLACK_VERSION) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def format(session): + """ + Run isort to sort imports. Then run black + to format code to uniform standard. + """ + session.install(BLACK_VERSION, ISORT_VERSION) + # Use the --fss option to sort imports using strict alphabetical order. + # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections + session.run( + "isort", + "--fss", + *LINT_PATHS, + ) + session.run( + "black", + *LINT_PATHS, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def lint_setup_py(session): + """Verify that setup.py is valid (including RST check).""" + session.install("docutils", "pygments") + session.run("python", "setup.py", "check", "--restructuredtext", "--strict") + + +def install_unittest_dependencies(session, *constraints): + standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES + session.install(*standard_deps, *constraints) + + if UNIT_TEST_EXTERNAL_DEPENDENCIES: + warnings.warn( + "'unit_test_external_dependencies' is deprecated. Instead, please " + "use 'unit_test_dependencies' or 'unit_test_local_dependencies'.", + DeprecationWarning, + ) + session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_LOCAL_DEPENDENCIES: + session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints) + + if UNIT_TEST_EXTRAS_BY_PYTHON: + extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif UNIT_TEST_EXTRAS: + extras = UNIT_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +def default(session): + # Install all test dependencies, then install this package in-place. + + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + install_unittest_dependencies(session, "-c", constraints_path) + + # Run py.test against the unit tests. + session.run( + "py.test", + "--quiet", + f"--junitxml=unit_{session.python}_sponge_log.xml", + "--cov=google", + "--cov=tests/unit", + "--cov-append", + "--cov-config=.coveragerc", + "--cov-report=", + "--cov-fail-under=0", + os.path.join("tests", "unit"), + *session.posargs, + ) + + +@nox.session(python=UNIT_TEST_PYTHON_VERSIONS) +def unit(session): + """Run the unit test suite.""" + default(session) + + +def install_systemtest_dependencies(session, *constraints): + # Use pre-release gRPC for system tests. + # Exclude version 1.52.0rc1 which has a known issue. + # See https://github.com/grpc/grpc/issues/32163 + session.install("--pre", "grpcio!=1.52.0rc1") + + session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTERNAL_DEPENDENCIES: + session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_LOCAL_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_DEPENDENCIES: + session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints) + + if SYSTEM_TEST_EXTRAS_BY_PYTHON: + extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, []) + elif SYSTEM_TEST_EXTRAS: + extras = SYSTEM_TEST_EXTRAS + else: + extras = [] + + if extras: + session.install("-e", f".[{','.join(extras)}]", *constraints) + else: + session.install("-e", ".", *constraints) + + +@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS) +def system(session): + """Run the system test suite.""" + constraints_path = str( + CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt" + ) + system_test_path = os.path.join("tests", "system.py") + system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") + # Install pyopenssl for mTLS testing. + if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true": + session.install("pyopenssl") + + system_test_exists = os.path.exists(system_test_path) + system_test_folder_exists = os.path.exists(system_test_folder_path) + # Sanity check: only run tests if found. + if not system_test_exists and not system_test_folder_exists: + session.skip("System tests were not found") + + install_systemtest_dependencies(session, "-c", constraints_path) + + # Run py.test against the system tests. + if system_test_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_path, + *session.posargs, + ) + if system_test_folder_exists: + session.run( + "py.test", + "--quiet", + f"--junitxml=system_{session.python}_sponge_log.xml", + system_test_folder_path, + *session.posargs, + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def cover(session): + """Run the final coverage report. + + This outputs the coverage report aggregating coverage from the unit + test runs (not system test runs), and then erases coverage data. + """ + session.install("coverage", "pytest-cov") + session.run("coverage", "report", "--show-missing", "--fail-under=100") + + session.run("coverage", "erase") + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docs(session): + """Build the docs for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "sphinx==4.5.0", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-W", # warnings as errors + "-T", # show full traceback on exception + "-N", # no colors + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + session.install( + # We need to pin to specific versions of the `sphinxcontrib-*` packages + # which still support sphinx 4.x. + # See https://github.com/googleapis/sphinx-docfx-yaml/issues/344 + # and https://github.com/googleapis/sphinx-docfx-yaml/issues/345. + "sphinxcontrib-applehelp==1.0.4", + "sphinxcontrib-devhelp==1.0.2", + "sphinxcontrib-htmlhelp==2.0.1", + "sphinxcontrib-qthelp==1.0.3", + "sphinxcontrib-serializinghtml==1.1.5", + "gcp-sphinx-docfx-yaml", + "alabaster", + "recommonmark", + ) + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) + + +@nox.session(python="3.12") +def prerelease_deps(session): + """Run all tests with prerelease versions of dependencies installed.""" + + # Install all dependencies + session.install("-e", ".[all, tests, tracing]") + unit_deps_all = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_EXTERNAL_DEPENDENCIES + session.install(*unit_deps_all) + system_deps_all = ( + SYSTEM_TEST_STANDARD_DEPENDENCIES + + SYSTEM_TEST_EXTERNAL_DEPENDENCIES + + SYSTEM_TEST_EXTRAS + ) + session.install(*system_deps_all) + + # Because we test minimum dependency versions on the minimum Python + # version, the first version we test with in the unit tests sessions has a + # constraints file containing all dependencies and extras. + with open( + CURRENT_DIRECTORY + / "testing" + / f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt", + encoding="utf-8", + ) as constraints_file: + constraints_text = constraints_file.read() + + # Ignore leading whitespace and comment lines. + constraints_deps = [ + match.group(1) + for match in re.finditer( + r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE + ) + ] + + session.install(*constraints_deps) + + prerel_deps = [ + "protobuf", + # dependency of grpc + "six", + "googleapis-common-protos", + # Exclude version 1.52.0rc1 which has a known issue. See https://github.com/grpc/grpc/issues/32163 + "grpcio!=1.52.0rc1", + "grpcio-status", + "google-api-core", + "google-auth", + "proto-plus", + "google-cloud-testutils", + # dependencies of google-cloud-testutils" + "click", + ] + + for dep in prerel_deps: + session.install("--pre", "--no-deps", "--upgrade", dep) + + # Remaining dependencies + other_deps = [ + "requests", + ] + session.install(*other_deps) + + # Print out prerelease package versions + session.run( + "python", "-c", "import google.protobuf; print(google.protobuf.__version__)" + ) + session.run("python", "-c", "import grpc; print(grpc.__version__)") + session.run("python", "-c", "import google.auth; print(google.auth.__version__)") + + session.run("py.test", "tests/unit") diff --git a/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py new file mode 100644 index 000000000000..6086f976fcca --- /dev/null +++ b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchOptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routeoptimization_v1 + + +async def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async] diff --git a/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py new file mode 100644 index 000000000000..77ae2122ea29 --- /dev/null +++ b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for BatchOptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routeoptimization_v1 + + +def sample_batch_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + model_configs = routeoptimization_v1.AsyncModelConfig() + model_configs.input_config.gcs_source.uri = "uri_value" + model_configs.input_config.data_format = "PROTO_TEXT" + model_configs.output_config.gcs_destination.uri = "uri_value" + model_configs.output_config.data_format = "PROTO_TEXT" + + request = routeoptimization_v1.BatchOptimizeToursRequest( + parent="parent_value", + model_configs=model_configs, + ) + + # Make the request + operation = client.batch_optimize_tours(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync] diff --git a/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py new file mode 100644 index 000000000000..e27f39d51f1e --- /dev/null +++ b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for OptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_OptimizeTours_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routeoptimization_v1 + + +async def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationAsyncClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = await client.optimize_tours(request=request) + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_OptimizeTours_async] diff --git a/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py new file mode 100644 index 000000000000..dd85447bf985 --- /dev/null +++ b/packages/google-maps-routeoptimization/samples/generated_samples/routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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. +# +# Generated code. DO NOT EDIT! +# +# Snippet for OptimizeTours +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-maps-routeoptimization + + +# [START routeoptimization_v1_generated_RouteOptimization_OptimizeTours_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.maps import routeoptimization_v1 + + +def sample_optimize_tours(): + # Create a client + client = routeoptimization_v1.RouteOptimizationClient() + + # Initialize request argument(s) + request = routeoptimization_v1.OptimizeToursRequest( + parent="parent_value", + ) + + # Make the request + response = client.optimize_tours(request=request) + + # Handle the response + print(response) + +# [END routeoptimization_v1_generated_RouteOptimization_OptimizeTours_sync] diff --git a/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json b/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json new file mode 100644 index 000000000000..c329d83ca2a2 --- /dev/null +++ b/packages/google-maps-routeoptimization/samples/generated_samples/snippet_metadata_google.maps.routeoptimization.v1.json @@ -0,0 +1,321 @@ +{ + "clientLibrary": { + "apis": [ + { + "id": "google.maps.routeoptimization.v1", + "version": "v1" + } + ], + "language": "PYTHON", + "name": "google-maps-routeoptimization", + "version": "0.1.0" + }, + "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient", + "shortName": "RouteOptimizationAsyncClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.batch_optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.BatchOptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "BatchOptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "batch_optimize_tours" + }, + "description": "Sample for BatchOptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_async", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient", + "shortName": "RouteOptimizationClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient.batch_optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.BatchOptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "BatchOptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.BatchOptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "batch_optimize_tours" + }, + "description": "Sample for BatchOptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_BatchOptimizeTours_sync", + "segments": [ + { + "end": 62, + "start": 27, + "type": "FULL" + }, + { + "end": 62, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 52, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 59, + "start": 53, + "type": "REQUEST_EXECUTION" + }, + { + "end": 63, + "start": 60, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routeoptimization_v1_generated_route_optimization_batch_optimize_tours_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient", + "shortName": "RouteOptimizationAsyncClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationAsyncClient.optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.OptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "OptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.OptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", + "shortName": "optimize_tours" + }, + "description": "Sample for OptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_optimize_tours_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_OptimizeTours_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routeoptimization_v1_generated_route_optimization_optimize_tours_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient", + "shortName": "RouteOptimizationClient" + }, + "fullName": "google.maps.routeoptimization_v1.RouteOptimizationClient.optimize_tours", + "method": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization.OptimizeTours", + "service": { + "fullName": "google.maps.routeoptimization.v1.RouteOptimization", + "shortName": "RouteOptimization" + }, + "shortName": "OptimizeTours" + }, + "parameters": [ + { + "name": "request", + "type": "google.maps.routeoptimization_v1.types.OptimizeToursRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.maps.routeoptimization_v1.types.OptimizeToursResponse", + "shortName": "optimize_tours" + }, + "description": "Sample for OptimizeTours", + "file": "routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "routeoptimization_v1_generated_RouteOptimization_OptimizeTours_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "routeoptimization_v1_generated_route_optimization_optimize_tours_sync.py" + } + ] +} diff --git a/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh b/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh new file mode 100755 index 000000000000..0018b421ddf8 --- /dev/null +++ b/packages/google-maps-routeoptimization/scripts/decrypt-secrets.sh @@ -0,0 +1,46 @@ +#!/bin/bash + +# Copyright 2023 Google LLC All rights reserved. +# +# 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. + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +ROOT=$( dirname "$DIR" ) + +# Work from the project root. +cd $ROOT + +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + +# Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. +PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" + +gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ + > testing/test-env.sh +gcloud secrets versions access latest \ + --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ + > testing/service-account.json +gcloud secrets versions access latest \ + --secret="python-docs-samples-client-secrets" \ + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/packages/google-maps-routeoptimization/scripts/fixup_routeoptimization_v1_keywords.py b/packages/google-maps-routeoptimization/scripts/fixup_routeoptimization_v1_keywords.py new file mode 100644 index 000000000000..fd04064542c9 --- /dev/null +++ b/packages/google-maps-routeoptimization/scripts/fixup_routeoptimization_v1_keywords.py @@ -0,0 +1,177 @@ +#! /usr/bin/env python3 +# -*- coding: utf-8 -*- +# Copyright 2024 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 argparse +import os +import libcst as cst +import pathlib +import sys +from typing import (Any, Callable, Dict, List, Sequence, Tuple) + + +def partition( + predicate: Callable[[Any], bool], + iterator: Sequence[Any] +) -> Tuple[List[Any], List[Any]]: + """A stable, out-of-place partition.""" + results = ([], []) + + for i in iterator: + results[int(predicate(i))].append(i) + + # Returns trueList, falseList + return results[1], results[0] + + +class routeoptimizationCallTransformer(cst.CSTTransformer): + CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') + METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'batch_optimize_tours': ('parent', 'model_configs', ), + 'optimize_tours': ('parent', 'timeout', 'model', 'solving_mode', 'search_mode', 'injected_first_solution_routes', 'injected_solution_constraint', 'refresh_details_routes', 'interpret_injected_solutions_using_labels', 'consider_road_traffic', 'populate_polylines', 'populate_transition_polylines', 'allow_large_deadline_despite_interruption_risk', 'use_geodesic_distances', 'geodesic_meters_per_second', 'max_validation_errors', 'label', ), + } + + def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: + try: + key = original.func.attr.value + kword_params = self.METHOD_TO_PARAMS[key] + except (AttributeError, KeyError): + # Either not a method from the API or too convoluted to be sure. + return updated + + # If the existing code is valid, keyword args come after positional args. + # Therefore, all positional args must map to the first parameters. + args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) + if any(k.keyword.value == "request" for k in kwargs): + # We've already fixed this file, don't fix it again. + return updated + + kwargs, ctrl_kwargs = partition( + lambda a: a.keyword.value not in self.CTRL_PARAMS, + kwargs + ) + + args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] + ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) + for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) + + request_arg = cst.Arg( + value=cst.Dict([ + cst.DictElement( + cst.SimpleString("'{}'".format(name)), +cst.Element(value=arg.value) + ) + # Note: the args + kwargs looks silly, but keep in mind that + # the control parameters had to be stripped out, and that + # those could have been passed positionally or by keyword. + for name, arg in zip(kword_params, args + kwargs)]), + keyword=cst.Name("request") + ) + + return updated.with_changes( + args=[request_arg] + ctrl_kwargs + ) + + +def fix_files( + in_dir: pathlib.Path, + out_dir: pathlib.Path, + *, + transformer=routeoptimizationCallTransformer(), +): + """Duplicate the input dir to the output dir, fixing file method calls. + + Preconditions: + * in_dir is a real directory + * out_dir is a real, empty directory + """ + pyfile_gen = ( + pathlib.Path(os.path.join(root, f)) + for root, _, files in os.walk(in_dir) + for f in files if os.path.splitext(f)[1] == ".py" + ) + + for fpath in pyfile_gen: + with open(fpath, 'r') as f: + src = f.read() + + # Parse the code and insert method call fixes. + tree = cst.parse_module(src) + updated = tree.visit(transformer) + + # Create the path and directory structure for the new file. + updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) + updated_path.parent.mkdir(parents=True, exist_ok=True) + + # Generate the updated source file at the corresponding path. + with open(updated_path, 'w') as f: + f.write(updated.code) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser( + description="""Fix up source that uses the routeoptimization client library. + +The existing sources are NOT overwritten but are copied to output_dir with changes made. + +Note: This tool operates at a best-effort level at converting positional + parameters in client method calls to keyword based parameters. + Cases where it WILL FAIL include + A) * or ** expansion in a method call. + B) Calls via function or method alias (includes free function calls) + C) Indirect or dispatched calls (e.g. the method is looked up dynamically) + + These all constitute false negatives. The tool will also detect false + positives when an API method shares a name with another method. +""") + parser.add_argument( + '-d', + '--input-directory', + required=True, + dest='input_dir', + help='the input directory to walk for python files to fix up', + ) + parser.add_argument( + '-o', + '--output-directory', + required=True, + dest='output_dir', + help='the directory to output files fixed via un-flattening', + ) + args = parser.parse_args() + input_dir = pathlib.Path(args.input_dir) + output_dir = pathlib.Path(args.output_dir) + if not input_dir.is_dir(): + print( + f"input directory '{input_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if not output_dir.is_dir(): + print( + f"output directory '{output_dir}' does not exist or is not a directory", + file=sys.stderr, + ) + sys.exit(-1) + + if os.listdir(output_dir): + print( + f"output directory '{output_dir}' is not empty", + file=sys.stderr, + ) + sys.exit(-1) + + fix_files(input_dir, output_dir) diff --git a/packages/google-maps-routeoptimization/setup.py b/packages/google-maps-routeoptimization/setup.py new file mode 100644 index 000000000000..69b130afd6a5 --- /dev/null +++ b/packages/google-maps-routeoptimization/setup.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 io +import os +import re + +import setuptools # type: ignore + +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "google-maps-routeoptimization" + + +description = "Google Maps Routeoptimization API client library" + +version = None + +with open( + os.path.join(package_root, "google/maps/routeoptimization/gapic_version.py") +) as fp: + version_candidates = re.findall(r"(?<=\")\d+.\d+.\d+(?=\")", fp.read()) + assert len(version_candidates) == 1 + version = version_candidates[0] + +if version[0] == "0": + release_status = "Development Status :: 4 - Beta" +else: + release_status = "Development Status :: 5 - Production/Stable" + +dependencies = [ + "google-api-core[grpc] >= 1.34.1, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", + # Exclude incompatible versions of `google-auth` + # See https://github.com/googleapis/google-cloud-python/issues/12364 + "google-auth >= 2.14.1, <3.0.0dev,!=2.24.0,!=2.25.0", + "proto-plus >= 1.22.3, <2.0.0dev", + "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", +] +url = "https://github.com/googleapis/google-cloud-python/tree/main/packages/google-maps-routeoptimization" + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +packages = [ + package + for package in setuptools.find_namespace_packages() + if package.startswith("google") +] + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + classifiers=[ + release_status, + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Operating System :: OS Independent", + "Topic :: Internet", + ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + install_requires=dependencies, + include_package_data=True, + zip_safe=False, +) diff --git a/packages/google-maps-routeoptimization/testing/.gitignore b/packages/google-maps-routeoptimization/testing/.gitignore new file mode 100644 index 000000000000..b05fbd630881 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/.gitignore @@ -0,0 +1,3 @@ +test-env.sh +service-account.json +client-secrets.json \ No newline at end of file diff --git a/packages/google-maps-routeoptimization/testing/constraints-3.10.txt b/packages/google-maps-routeoptimization/testing/constraints-3.10.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/constraints-3.10.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-maps-routeoptimization/testing/constraints-3.11.txt b/packages/google-maps-routeoptimization/testing/constraints-3.11.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/constraints-3.11.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-maps-routeoptimization/testing/constraints-3.12.txt b/packages/google-maps-routeoptimization/testing/constraints-3.12.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/constraints-3.12.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-maps-routeoptimization/testing/constraints-3.7.txt b/packages/google-maps-routeoptimization/testing/constraints-3.7.txt new file mode 100644 index 000000000000..b8a550c73855 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/constraints-3.7.txt @@ -0,0 +1,10 @@ +# This constraints file is used to check that lower bounds +# are correct in setup.py +# List all library dependencies and extras in this file. +# Pin the version to the lower bound. +# e.g., if setup.py has "google-cloud-foo >= 1.14.0, < 2.0.0dev", +# Then this file should have google-cloud-foo==1.14.0 +google-api-core==1.34.1 +google-auth==2.14.1 +proto-plus==1.22.3 +protobuf==3.19.5 diff --git a/packages/google-maps-routeoptimization/testing/constraints-3.8.txt b/packages/google-maps-routeoptimization/testing/constraints-3.8.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/constraints-3.8.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-maps-routeoptimization/testing/constraints-3.9.txt b/packages/google-maps-routeoptimization/testing/constraints-3.9.txt new file mode 100644 index 000000000000..ed7f9aed2559 --- /dev/null +++ b/packages/google-maps-routeoptimization/testing/constraints-3.9.txt @@ -0,0 +1,6 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf diff --git a/packages/google-maps-routeoptimization/tests/__init__.py b/packages/google-maps-routeoptimization/tests/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-maps-routeoptimization/tests/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-maps-routeoptimization/tests/unit/__init__.py b/packages/google-maps-routeoptimization/tests/unit/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-maps-routeoptimization/tests/unit/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-maps-routeoptimization/tests/unit/gapic/__init__.py b/packages/google-maps-routeoptimization/tests/unit/gapic/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-maps-routeoptimization/tests/unit/gapic/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/__init__.py b/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/__init__.py new file mode 100644 index 000000000000..8f6cf068242c --- /dev/null +++ b/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/__init__.py @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py b/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py new file mode 100644 index 000000000000..b485c0bd046c --- /dev/null +++ b/packages/google-maps-routeoptimization/tests/unit/gapic/routeoptimization_v1/test_route_optimization.py @@ -0,0 +1,3276 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 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 os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import Iterable +import json +import math + +from google.api_core import ( + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + operation, + operations_v1, + path_template, +) +from google.api_core import api_core_version, client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import operation_async # type: ignore +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.longrunning import operations_pb2 # type: ignore +from google.oauth2 import service_account +from google.protobuf import duration_pb2 # type: ignore +from google.protobuf import json_format +from google.protobuf import timestamp_pb2 # type: ignore +from google.type import latlng_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.maps.routeoptimization_v1.services.route_optimization import ( + RouteOptimizationAsyncClient, + RouteOptimizationClient, + transports, +) +from google.maps.routeoptimization_v1.types import route_optimization_service + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RouteOptimizationClient._get_default_mtls_endpoint(None) is None + assert ( + RouteOptimizationClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RouteOptimizationClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RouteOptimizationClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RouteOptimizationClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RouteOptimizationClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert RouteOptimizationClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RouteOptimizationClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RouteOptimizationClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + RouteOptimizationClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RouteOptimizationClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RouteOptimizationClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RouteOptimizationClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RouteOptimizationClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert RouteOptimizationClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RouteOptimizationClient._get_client_cert_source(None, False) is None + assert ( + RouteOptimizationClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + RouteOptimizationClient._get_client_cert_source(mock_provided_cert_source, True) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + RouteOptimizationClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RouteOptimizationClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RouteOptimizationClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationClient), +) +@mock.patch.object( + RouteOptimizationAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationAsyncClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + default_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RouteOptimizationClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RouteOptimizationClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + RouteOptimizationClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RouteOptimizationClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RouteOptimizationClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RouteOptimizationClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + RouteOptimizationClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RouteOptimizationClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + RouteOptimizationClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RouteOptimizationClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RouteOptimizationClient._get_universe_domain(None, None) + == RouteOptimizationClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RouteOptimizationClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), + ], +) +def test__validate_universe_domain(client_class, transport_class, transport_name): + client = client_class( + transport=transport_class(credentials=ga_credentials.AnonymousCredentials()) + ) + assert client._validate_universe_domain() == True + + # Test the case when universe is already validated. + assert client._validate_universe_domain() == True + + if transport_name == "grpc": + # Test the case where credentials are provided by the + # `local_channel_credentials`. The default universes in both match. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + client = client_class(transport=transport_class(channel=channel)) + assert client._validate_universe_domain() == True + + # Test the case where credentials do not exist: e.g. a transport is provided + # with no credentials. Validation should still succeed because there is no + # mismatch with non-existent credentials. + channel = grpc.secure_channel( + "http://localhost/", grpc.local_channel_credentials() + ) + transport = transport_class(channel=channel) + transport._credentials = None + client = client_class(transport=transport) + assert client._validate_universe_domain() == True + + # TODO: This is needed to cater for older versions of google-auth + # Make this test unconditional once the minimum supported version of + # google-auth becomes 2.23.0 or higher. + google_auth_major, google_auth_minor = [ + int(part) for part in google.auth.__version__.split(".")[0:2] + ] + if google_auth_major > 2 or (google_auth_major == 2 and google_auth_minor >= 23): + credentials = ga_credentials.AnonymousCredentials() + credentials._universe_domain = "foo.com" + # Test the case when there is a universe mismatch from the credentials. + client = client_class(transport=transport_class(credentials=credentials)) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (googleapis.com) does not match the universe domain found in the credentials (foo.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test the case when there is a universe mismatch from the client. + # + # TODO: Make this test unconditional once the minimum supported version of + # google-api-core becomes 2.15.0 or higher. + api_core_major, api_core_minor = [ + int(part) for part in api_core_version.__version__.split(".")[0:2] + ] + if api_core_major > 2 or (api_core_major == 2 and api_core_minor >= 15): + client = client_class( + client_options={"universe_domain": "bar.com"}, + transport=transport_class( + credentials=ga_credentials.AnonymousCredentials(), + ), + ) + with pytest.raises(ValueError) as excinfo: + client._validate_universe_domain() + assert ( + str(excinfo.value) + == "The configured universe domain (bar.com) does not match the universe domain found in the credentials (googleapis.com). If you haven't configured the universe domain explicitly, `googleapis.com` is the default." + ) + + # Test that ValueError is raised if universe_domain is provided via client options and credentials is None + with pytest.raises(ValueError): + client._compare_universes("foo.bar", None) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RouteOptimizationClient, "grpc"), + (RouteOptimizationAsyncClient, "grpc_asyncio"), + (RouteOptimizationClient, "rest"), + ], +) +def test_route_optimization_client_from_service_account_info( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_info" + ) as factory: + factory.return_value = creds + info = {"valid": True} + client = client_class.from_service_account_info(info, transport=transport_name) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "routeoptimization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://routeoptimization.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.RouteOptimizationGrpcTransport, "grpc"), + (transports.RouteOptimizationGrpcAsyncIOTransport, "grpc_asyncio"), + (transports.RouteOptimizationRestTransport, "rest"), + ], +) +def test_route_optimization_client_service_account_always_use_jwt( + transport_class, transport_name +): + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=True) + use_jwt.assert_called_once_with(True) + + with mock.patch.object( + service_account.Credentials, "with_always_use_jwt_access", create=True + ) as use_jwt: + creds = service_account.Credentials(None, None, None) + transport = transport_class(credentials=creds, always_use_jwt_access=False) + use_jwt.assert_not_called() + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (RouteOptimizationClient, "grpc"), + (RouteOptimizationAsyncClient, "grpc_asyncio"), + (RouteOptimizationClient, "rest"), + ], +) +def test_route_optimization_client_from_service_account_file( + client_class, transport_name +): + creds = ga_credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + client = client_class.from_service_account_json( + "dummy/file/path.json", transport=transport_name + ) + assert client.transport._credentials == creds + assert isinstance(client, client_class) + + assert client.transport._host == ( + "routeoptimization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://routeoptimization.googleapis.com" + ) + + +def test_route_optimization_client_get_transport_class(): + transport = RouteOptimizationClient.get_transport_class() + available_transports = [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationRestTransport, + ] + assert transport in available_transports + + transport = RouteOptimizationClient.get_transport_class("grpc") + assert transport == transports.RouteOptimizationGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), + ], +) +@mock.patch.object( + RouteOptimizationClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationClient), +) +@mock.patch.object( + RouteOptimizationAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationAsyncClient), +) +def test_route_optimization_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RouteOptimizationClient, "get_transport_class") as gtc: + transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RouteOptimizationClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RouteOptimizationClient, + transports.RouteOptimizationGrpcTransport, + "grpc", + "true", + ), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + RouteOptimizationClient, + transports.RouteOptimizationGrpcTransport, + "grpc", + "false", + ), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ( + RouteOptimizationClient, + transports.RouteOptimizationRestTransport, + "rest", + "true", + ), + ( + RouteOptimizationClient, + transports.RouteOptimizationRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RouteOptimizationClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationClient), +) +@mock.patch.object( + RouteOptimizationAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_route_optimization_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class", [RouteOptimizationClient, RouteOptimizationAsyncClient] +) +@mock.patch.object( + RouteOptimizationClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RouteOptimizationClient), +) +@mock.patch.object( + RouteOptimizationAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RouteOptimizationAsyncClient), +) +def test_route_optimization_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize( + "client_class", [RouteOptimizationClient, RouteOptimizationAsyncClient] +) +@mock.patch.object( + RouteOptimizationClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationClient), +) +@mock.patch.object( + RouteOptimizationAsyncClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RouteOptimizationAsyncClient), +) +def test_route_optimization_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RouteOptimizationClient._DEFAULT_UNIVERSE + default_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RouteOptimizationClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport, "grpc"), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + "grpc_asyncio", + ), + (RouteOptimizationClient, transports.RouteOptimizationRestTransport, "rest"), + ], +) +def test_route_optimization_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + RouteOptimizationClient, + transports.RouteOptimizationGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ( + RouteOptimizationClient, + transports.RouteOptimizationRestTransport, + "rest", + None, + ), + ], +) +def test_route_optimization_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_route_optimization_client_client_options_from_dict(): + with mock.patch( + "google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = RouteOptimizationClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + RouteOptimizationClient, + transports.RouteOptimizationGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_route_optimization_client_create_channel_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # test that the credentials from file are saved and used as the credentials. + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel" + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + file_creds = ga_credentials.AnonymousCredentials() + load_creds.return_value = (file_creds, None) + adc.return_value = (creds, None) + client = client_class(client_options=options, transport=transport_name) + create_channel.assert_called_with( + "routeoptimization.googleapis.com:443", + credentials=file_creds, + credentials_file=None, + quota_project_id=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=None, + default_host="routeoptimization.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + route_optimization_service.OptimizeToursRequest, + dict, + ], +) +def test_optimize_tours(request_type, transport: str = "grpc"): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = route_optimization_service.OptimizeToursResponse( + request_label="request_label_value", + ) + response = client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = route_optimization_service.OptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, route_optimization_service.OptimizeToursResponse) + assert response.request_label == "request_label_value" + + +def test_optimize_tours_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.optimize_tours() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.OptimizeToursRequest() + + +def test_optimize_tours_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = route_optimization_service.OptimizeToursRequest( + parent="parent_value", + label="label_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.optimize_tours(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.OptimizeToursRequest( + parent="parent_value", + label="label_value", + ) + + +def test_optimize_tours_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.optimize_tours in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.optimize_tours] = mock_rpc + request = {} + client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_optimize_tours_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + route_optimization_service.OptimizeToursResponse( + request_label="request_label_value", + ) + ) + response = await client.optimize_tours() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.OptimizeToursRequest() + + +@pytest.mark.asyncio +async def test_optimize_tours_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.optimize_tours + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.optimize_tours + ] = mock_object + + request = {} + await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + await client.optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_optimize_tours_async( + transport: str = "grpc_asyncio", + request_type=route_optimization_service.OptimizeToursRequest, +): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + route_optimization_service.OptimizeToursResponse( + request_label="request_label_value", + ) + ) + response = await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = route_optimization_service.OptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, route_optimization_service.OptimizeToursResponse) + assert response.request_label == "request_label_value" + + +@pytest.mark.asyncio +async def test_optimize_tours_async_from_dict(): + await test_optimize_tours_async(request_type=dict) + + +def test_optimize_tours_field_headers(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = route_optimization_service.OptimizeToursRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + call.return_value = route_optimization_service.OptimizeToursResponse() + client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_optimize_tours_field_headers_async(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = route_optimization_service.OptimizeToursRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.optimize_tours), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + route_optimization_service.OptimizeToursResponse() + ) + await client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + route_optimization_service.BatchOptimizeToursRequest, + dict, + ], +) +def test_batch_optimize_tours(request_type, transport: str = "grpc"): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = route_optimization_service.BatchOptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_batch_optimize_tours_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_optimize_tours() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.BatchOptimizeToursRequest() + + +def test_batch_optimize_tours_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = route_optimization_service.BatchOptimizeToursRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.batch_optimize_tours(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.BatchOptimizeToursRequest( + parent="parent_value", + ) + + +def test_batch_optimize_tours_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_optimize_tours in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_optimize_tours + ] = mock_rpc + request = {} + client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_empty_call_async(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.batch_optimize_tours() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == route_optimization_service.BatchOptimizeToursRequest() + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.batch_optimize_tours + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + class AwaitableMock(mock.AsyncMock): + def __await__(self): + self.await_count += 1 + return iter([]) + + mock_object = AwaitableMock() + client._client._transport._wrapped_methods[ + client._client._transport.batch_optimize_tours + ] = mock_object + + request = {} + await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_object.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.batch_optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_object.call_count == 2 + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async( + transport: str = "grpc_asyncio", + request_type=route_optimization_service.BatchOptimizeToursRequest, +): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = route_optimization_service.BatchOptimizeToursRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_async_from_dict(): + await test_batch_optimize_tours_async(request_type=dict) + + +def test_batch_optimize_tours_field_headers(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = route_optimization_service.BatchOptimizeToursRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_batch_optimize_tours_field_headers_async(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = route_optimization_service.BatchOptimizeToursRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.batch_optimize_tours), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + route_optimization_service.OptimizeToursRequest, + dict, + ], +) +def test_optimize_tours_rest(request_type): + client = RouteOptimizationClient( + 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 = route_optimization_service.OptimizeToursResponse( + request_label="request_label_value", + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = route_optimization_service.OptimizeToursResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.optimize_tours(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, route_optimization_service.OptimizeToursResponse) + assert response.request_label == "request_label_value" + + +def test_optimize_tours_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.optimize_tours in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.optimize_tours] = mock_rpc + + request = {} + client.optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_optimize_tours_rest_required_fields( + request_type=route_optimization_service.OptimizeToursRequest, +): + transport_class = transports.RouteOptimizationRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).optimize_tours._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() + ).optimize_tours._get_unset_required_fields(jsonified_request) + 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 = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = route_optimization_service.OptimizeToursResponse() + # 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 + + # Convert return value to protobuf type + return_value = route_optimization_service.OptimizeToursResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.optimize_tours(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_optimize_tours_rest_unset_required_fields(): + transport = transports.RouteOptimizationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.RouteOptimizationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RouteOptimizationRestInterceptor(), + ) + client = RouteOptimizationClient(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.RouteOptimizationRestInterceptor, "post_optimize_tours" + ) as post, mock.patch.object( + transports.RouteOptimizationRestInterceptor, "pre_optimize_tours" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = route_optimization_service.OptimizeToursRequest.pb( + route_optimization_service.OptimizeToursRequest() + ) + 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 = ( + route_optimization_service.OptimizeToursResponse.to_json( + route_optimization_service.OptimizeToursResponse() + ) + ) + + request = route_optimization_service.OptimizeToursRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = route_optimization_service.OptimizeToursResponse() + + client.optimize_tours( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_optimize_tours_rest_bad_request( + transport: str = "rest", + request_type=route_optimization_service.OptimizeToursRequest, +): + client = RouteOptimizationClient( + 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.optimize_tours(request) + + +def test_optimize_tours_rest_error(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + route_optimization_service.BatchOptimizeToursRequest, + dict, + ], +) +def test_batch_optimize_tours_rest(request_type): + client = RouteOptimizationClient( + 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 = 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.batch_optimize_tours(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_batch_optimize_tours_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.batch_optimize_tours in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.batch_optimize_tours + ] = mock_rpc + + request = {} + client.batch_optimize_tours(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.batch_optimize_tours(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_batch_optimize_tours_rest_required_fields( + request_type=route_optimization_service.BatchOptimizeToursRequest, +): + transport_class = transports.RouteOptimizationRestTransport + + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).batch_optimize_tours._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() + ).batch_optimize_tours._get_unset_required_fields(jsonified_request) + 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 = RouteOptimizationClient( + 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.batch_optimize_tours(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_batch_optimize_tours_rest_unset_required_fields(): + transport = transports.RouteOptimizationRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.batch_optimize_tours._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "modelConfigs", + ) + ) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_batch_optimize_tours_rest_interceptors(null_interceptor): + transport = transports.RouteOptimizationRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RouteOptimizationRestInterceptor(), + ) + client = RouteOptimizationClient(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.RouteOptimizationRestInterceptor, "post_batch_optimize_tours" + ) as post, mock.patch.object( + transports.RouteOptimizationRestInterceptor, "pre_batch_optimize_tours" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = route_optimization_service.BatchOptimizeToursRequest.pb( + route_optimization_service.BatchOptimizeToursRequest() + ) + 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 = route_optimization_service.BatchOptimizeToursRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.batch_optimize_tours( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_batch_optimize_tours_rest_bad_request( + transport: str = "rest", + request_type=route_optimization_service.BatchOptimizeToursRequest, +): + client = RouteOptimizationClient( + 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.batch_optimize_tours(request) + + +def test_batch_optimize_tours_rest_error(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RouteOptimizationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RouteOptimizationClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RouteOptimizationClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RouteOptimizationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RouteOptimizationClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RouteOptimizationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RouteOptimizationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + transports.RouteOptimizationRestTransport, + ], +) +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 = RouteOptimizationClient.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 = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.RouteOptimizationGrpcTransport, + ) + + +def test_route_optimization_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RouteOptimizationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_route_optimization_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RouteOptimizationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "optimize_tours", + "batch_optimize_tours", + "get_operation", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_route_optimization_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RouteOptimizationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_route_optimization_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.maps.routeoptimization_v1.services.route_optimization.transports.RouteOptimizationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RouteOptimizationTransport() + adc.assert_called_once() + + +def test_route_optimization_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + RouteOptimizationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + ], +) +def test_route_optimization_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + transports.RouteOptimizationRestTransport, + ], +) +def test_route_optimization_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.RouteOptimizationGrpcTransport, grpc_helpers), + (transports.RouteOptimizationGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_route_optimization_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "routeoptimization.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="routeoptimization.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + ], +) +def test_route_optimization_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +def test_route_optimization_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.RouteOptimizationRestTransport( + 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_route_optimization_rest_lro_client(): + client = RouteOptimizationClient( + 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_route_optimization_host_no_port(transport_name): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="routeoptimization.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "routeoptimization.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://routeoptimization.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + "rest", + ], +) +def test_route_optimization_host_with_port(transport_name): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="routeoptimization.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "routeoptimization.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://routeoptimization.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_route_optimization_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RouteOptimizationClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RouteOptimizationClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.optimize_tours._session + session2 = client2.transport.optimize_tours._session + assert session1 != session2 + session1 = client1.transport.batch_optimize_tours._session + session2 = client2.transport.batch_optimize_tours._session + assert session1 != session2 + + +def test_route_optimization_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RouteOptimizationGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_route_optimization_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.RouteOptimizationGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + ], +) +def test_route_optimization_transport_channel_mtls_with_client_cert_source( + transport_class, +): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [ + transports.RouteOptimizationGrpcTransport, + transports.RouteOptimizationGrpcAsyncIOTransport, + ], +) +def test_route_optimization_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_route_optimization_grpc_lro_client(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_route_optimization_grpc_lro_async_client(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RouteOptimizationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RouteOptimizationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RouteOptimizationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RouteOptimizationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RouteOptimizationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RouteOptimizationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RouteOptimizationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RouteOptimizationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = RouteOptimizationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RouteOptimizationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RouteOptimizationClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RouteOptimizationTransport, "_prep_wrapped_messages" + ) as prep: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RouteOptimizationTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RouteOptimizationClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_get_operation_rest_bad_request( + transport: str = "rest", request_type=operations_pb2.GetOperationRequest +): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # 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_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.GetOperationRequest, + dict, + ], +) +def test_get_operation_rest(request_type): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request_init = {"name": "projects/sample1/locations/sample2/operations/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() + + # 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.get_operation(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation(transport: str = "grpc"): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc_asyncio"): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = operations_pb2.GetOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() + + client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = operations_pb2.GetOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] + + +def test_get_operation_from_dict(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): + client = RouteOptimizationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +def test_transport_close(): + transports = { + "rest": "_session", + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + with mock.patch.object( + type(getattr(client.transport, close_name)), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + "grpc", + ] + for transport in transports: + client = RouteOptimizationClient( + credentials=ga_credentials.AnonymousCredentials(), transport=transport + ) + # Test client calls underlying transport. + with mock.patch.object(type(client.transport), "close") as close: + close.assert_not_called() + with client: + pass + close.assert_called() + + +@pytest.mark.parametrize( + "client_class,transport_class", + [ + (RouteOptimizationClient, transports.RouteOptimizationGrpcTransport), + ( + RouteOptimizationAsyncClient, + transports.RouteOptimizationGrpcAsyncIOTransport, + ), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + )