diff --git a/.coveragerc b/.coveragerc index 463df93..f0ee860 100644 --- a/.coveragerc +++ b/.coveragerc @@ -10,8 +10,3 @@ exclude_lines = pragma: NO COVER # Ignore debug-only repr def __repr__ - # Ignore pkg_resources exceptions. - # This is added at the module level as a safeguard for if someone - # generates the code and tries to run it without pip installing. This - # makes it virtually impossible to test properly. - except pkg_resources.DistributionNotFound diff --git a/.github/release-please.yml b/.github/release-please.yml index 6def37a..e9a4f00 100644 --- a/.github/release-please.yml +++ b/.github/release-please.yml @@ -1,5 +1,6 @@ releaseType: python handleGHRelease: true +manifest: true # NOTE: this section is generated by synthtool.languages.python # See https://github.com/googleapis/synthtool/blob/master/synthtool/languages/python.py branches: diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..50f0c45 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "1.4.4" +} diff --git a/docs/networkconnectivity_v1/policy_based_routing_service.rst b/docs/networkconnectivity_v1/policy_based_routing_service.rst new file mode 100644 index 0000000..8991d76 --- /dev/null +++ b/docs/networkconnectivity_v1/policy_based_routing_service.rst @@ -0,0 +1,10 @@ +PolicyBasedRoutingService +------------------------------------------- + +.. automodule:: google.cloud.networkconnectivity_v1.services.policy_based_routing_service + :members: + :inherited-members: + +.. automodule:: google.cloud.networkconnectivity_v1.services.policy_based_routing_service.pagers + :members: + :inherited-members: diff --git a/docs/networkconnectivity_v1/services.rst b/docs/networkconnectivity_v1/services.rst index a3f383d..a2c4047 100644 --- a/docs/networkconnectivity_v1/services.rst +++ b/docs/networkconnectivity_v1/services.rst @@ -4,3 +4,4 @@ Services for Google Cloud Networkconnectivity v1 API :maxdepth: 2 hub_service + policy_based_routing_service diff --git a/docs/networkconnectivity_v1/types.rst b/docs/networkconnectivity_v1/types.rst index 642ecb4..f12678c 100644 --- a/docs/networkconnectivity_v1/types.rst +++ b/docs/networkconnectivity_v1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Networkconnectivity v1 API .. automodule:: google.cloud.networkconnectivity_v1.types :members: - :undoc-members: :show-inheritance: diff --git a/docs/networkconnectivity_v1alpha1/types.rst b/docs/networkconnectivity_v1alpha1/types.rst index 175ee64..82985cd 100644 --- a/docs/networkconnectivity_v1alpha1/types.rst +++ b/docs/networkconnectivity_v1alpha1/types.rst @@ -3,5 +3,4 @@ Types for Google Cloud Networkconnectivity v1alpha1 API .. automodule:: google.cloud.networkconnectivity_v1alpha1.types :members: - :undoc-members: :show-inheritance: diff --git a/google/cloud/networkconnectivity/__init__.py b/google/cloud/networkconnectivity/__init__.py index f0f939f..07eb4ab 100644 --- a/google/cloud/networkconnectivity/__init__.py +++ b/google/cloud/networkconnectivity/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.networkconnectivity import gapic_version as package_version + +__version__ = package_version.__version__ + from google.cloud.networkconnectivity_v1.services.hub_service.async_client import ( HubServiceAsyncClient, @@ -20,6 +24,12 @@ from google.cloud.networkconnectivity_v1.services.hub_service.client import ( HubServiceClient, ) +from google.cloud.networkconnectivity_v1.services.policy_based_routing_service.async_client import ( + PolicyBasedRoutingServiceAsyncClient, +) +from google.cloud.networkconnectivity_v1.services.policy_based_routing_service.client import ( + PolicyBasedRoutingServiceClient, +) from google.cloud.networkconnectivity_v1.types.common import OperationMetadata from google.cloud.networkconnectivity_v1.types.hub import ( CreateHubRequest, @@ -45,10 +55,20 @@ UpdateHubRequest, UpdateSpokeRequest, ) +from google.cloud.networkconnectivity_v1.types.policy_based_routing import ( + CreatePolicyBasedRouteRequest, + DeletePolicyBasedRouteRequest, + GetPolicyBasedRouteRequest, + ListPolicyBasedRoutesRequest, + ListPolicyBasedRoutesResponse, + PolicyBasedRoute, +) __all__ = ( "HubServiceClient", "HubServiceAsyncClient", + "PolicyBasedRoutingServiceClient", + "PolicyBasedRoutingServiceAsyncClient", "OperationMetadata", "CreateHubRequest", "CreateSpokeRequest", @@ -72,4 +92,10 @@ "UpdateSpokeRequest", "LocationFeature", "State", + "CreatePolicyBasedRouteRequest", + "DeletePolicyBasedRouteRequest", + "GetPolicyBasedRouteRequest", + "ListPolicyBasedRoutesRequest", + "ListPolicyBasedRoutesResponse", + "PolicyBasedRoute", ) diff --git a/google/cloud/networkconnectivity/gapic_version.py b/google/cloud/networkconnectivity/gapic_version.py new file mode 100644 index 0000000..25e4dd6 --- /dev/null +++ b/google/cloud/networkconnectivity/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "1.4.4" # {x-release-please-version} diff --git a/google/cloud/networkconnectivity/py.typed b/google/cloud/networkconnectivity/py.typed index e8bf4d0..cf23681 100644 --- a/google/cloud/networkconnectivity/py.typed +++ b/google/cloud/networkconnectivity/py.typed @@ -1,2 +1,2 @@ # Marker file for PEP 561. -# The google-cloud-networkconnectivity package uses inline types. +# The google-cloud-network-connectivity package uses inline types. diff --git a/google/cloud/networkconnectivity_v1/__init__.py b/google/cloud/networkconnectivity_v1/__init__.py index f2f3170..7d45736 100644 --- a/google/cloud/networkconnectivity_v1/__init__.py +++ b/google/cloud/networkconnectivity_v1/__init__.py @@ -13,8 +13,16 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.networkconnectivity import gapic_version as package_version + +__version__ = package_version.__version__ + from .services.hub_service import HubServiceAsyncClient, HubServiceClient +from .services.policy_based_routing_service import ( + PolicyBasedRoutingServiceAsyncClient, + PolicyBasedRoutingServiceClient, +) from .types.common import OperationMetadata from .types.hub import ( CreateHubRequest, @@ -40,14 +48,26 @@ UpdateHubRequest, UpdateSpokeRequest, ) +from .types.policy_based_routing import ( + CreatePolicyBasedRouteRequest, + DeletePolicyBasedRouteRequest, + GetPolicyBasedRouteRequest, + ListPolicyBasedRoutesRequest, + ListPolicyBasedRoutesResponse, + PolicyBasedRoute, +) __all__ = ( "HubServiceAsyncClient", + "PolicyBasedRoutingServiceAsyncClient", "CreateHubRequest", + "CreatePolicyBasedRouteRequest", "CreateSpokeRequest", "DeleteHubRequest", + "DeletePolicyBasedRouteRequest", "DeleteSpokeRequest", "GetHubRequest", + "GetPolicyBasedRouteRequest", "GetSpokeRequest", "Hub", "HubServiceClient", @@ -56,11 +76,15 @@ "LinkedVpnTunnels", "ListHubsRequest", "ListHubsResponse", + "ListPolicyBasedRoutesRequest", + "ListPolicyBasedRoutesResponse", "ListSpokesRequest", "ListSpokesResponse", "LocationFeature", "LocationMetadata", "OperationMetadata", + "PolicyBasedRoute", + "PolicyBasedRoutingServiceClient", "RouterApplianceInstance", "RoutingVPC", "Spoke", diff --git a/google/cloud/networkconnectivity_v1/gapic_metadata.json b/google/cloud/networkconnectivity_v1/gapic_metadata.json index 11b2166..693c92c 100644 --- a/google/cloud/networkconnectivity_v1/gapic_metadata.json +++ b/google/cloud/networkconnectivity_v1/gapic_metadata.json @@ -118,6 +118,60 @@ } } } + }, + "PolicyBasedRoutingService": { + "clients": { + "grpc": { + "libraryClient": "PolicyBasedRoutingServiceClient", + "rpcs": { + "CreatePolicyBasedRoute": { + "methods": [ + "create_policy_based_route" + ] + }, + "DeletePolicyBasedRoute": { + "methods": [ + "delete_policy_based_route" + ] + }, + "GetPolicyBasedRoute": { + "methods": [ + "get_policy_based_route" + ] + }, + "ListPolicyBasedRoutes": { + "methods": [ + "list_policy_based_routes" + ] + } + } + }, + "grpc-async": { + "libraryClient": "PolicyBasedRoutingServiceAsyncClient", + "rpcs": { + "CreatePolicyBasedRoute": { + "methods": [ + "create_policy_based_route" + ] + }, + "DeletePolicyBasedRoute": { + "methods": [ + "delete_policy_based_route" + ] + }, + "GetPolicyBasedRoute": { + "methods": [ + "get_policy_based_route" + ] + }, + "ListPolicyBasedRoutes": { + "methods": [ + "list_policy_based_routes" + ] + } + } + } + } } } } diff --git a/google/cloud/networkconnectivity_v1/gapic_version.py b/google/cloud/networkconnectivity_v1/gapic_version.py new file mode 100644 index 0000000..25e4dd6 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "1.4.4" # {x-release-please-version} diff --git a/google/cloud/networkconnectivity_v1/py.typed b/google/cloud/networkconnectivity_v1/py.typed index e8bf4d0..cf23681 100644 --- a/google/cloud/networkconnectivity_v1/py.typed +++ b/google/cloud/networkconnectivity_v1/py.typed @@ -1,2 +1,2 @@ # Marker file for PEP 561. -# The google-cloud-networkconnectivity package uses inline types. +# The google-cloud-network-connectivity package uses inline types. diff --git a/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py b/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py index 4d7cfb7..27dc882 100644 --- a/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py +++ b/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py @@ -16,7 +16,17 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + 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 @@ -24,7 +34,8 @@ 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 -import pkg_resources + +from google.cloud.networkconnectivity_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -179,9 +190,9 @@ def transport(self) -> HubServiceTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, HubServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the hub service client. @@ -225,14 +236,15 @@ def __init__( async def list_hubs( self, - request: Union[hub.ListHubsRequest, dict] = None, + request: Optional[Union[hub.ListHubsRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListHubsAsyncPager: - r"""Lists hubs in a given project. + r"""Lists the Network Connectivity Center hubs associated + with a given project. .. code-block:: python @@ -262,7 +274,7 @@ async def sample_list_hubs(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.ListHubsRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListHubsRequest, dict]]): The request object. Request for [HubService.ListHubs][google.cloud.networkconnectivity.v1.HubService.ListHubs] method. @@ -280,8 +292,8 @@ async def sample_list_hubs(): Returns: google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubsAsyncPager: Response for - [HubService.ListHubs][google.cloud.networkconnectivity.v1.HubService.ListHubs] - method. + [HubService.ListHubs][google.cloud.networkconnectivity.v1.HubService.ListHubs] + method. Iterating over this object will yield results and resolve additional pages automatically. @@ -340,14 +352,14 @@ async def sample_list_hubs(): async def get_hub( self, - request: Union[hub.GetHubRequest, dict] = None, + request: Optional[Union[hub.GetHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Hub: - r"""Gets details about the specified hub. + r"""Gets details about a Network Connectivity Center hub. .. code-block:: python @@ -376,7 +388,7 @@ async def sample_get_hub(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.GetHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.GetHubRequest, dict]]): The request object. Request for [HubService.GetHub][google.cloud.networkconnectivity.v1.HubService.GetHub] method. @@ -395,15 +407,16 @@ async def sample_get_hub(): Returns: google.cloud.networkconnectivity_v1.types.Hub: - A hub is a collection of spokes. A - single hub can contain spokes from - multiple regions. However, if any of a - hub's spokes use the data transfer - feature, the resources associated with - those spokes must all reside in the same - VPC network. Spokes that do not use data - transfer can be associated with any VPC - network in your project. + A Network Connectivity Center hub is + a collection of spokes. A single hub can + contain spokes from multiple regions. + However, if any of a hub's spokes use + the data transfer feature, the resources + associated with those spokes must all + reside in the same VPC network. Spokes + that do not use data transfer can be + associated with any VPC network in your + project. """ # Create or coerce a protobuf request object. @@ -450,16 +463,17 @@ async def sample_get_hub(): async def create_hub( self, - request: Union[gcn_hub.CreateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.CreateHubRequest, dict]] = None, *, - parent: str = None, - hub: gcn_hub.Hub = None, - hub_id: str = None, + parent: Optional[str] = None, + hub: Optional[gcn_hub.Hub] = None, + hub_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Creates a new hub in the specified project. + r"""Creates a new Network Connectivity Center hub in the + specified project. .. code-block:: python @@ -487,13 +501,13 @@ async def sample_create_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.CreateHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.CreateHubRequest, dict]]): The request object. Request for [HubService.CreateHub][google.cloud.networkconnectivity.v1.HubService.CreateHub] method. @@ -526,13 +540,13 @@ async def sample_create_hub(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A hub is a collection of spokes. A single hub can contain spokes from - multiple regions. However, if any of a hub's spokes - use the data transfer feature, the resources - associated with those spokes must all reside in the - same VPC network. Spokes that do not use data - transfer can be associated with any VPC network in - your project. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub + can contain spokes from multiple regions. However, if + any of a hub's spokes use the data transfer feature, + the resources associated with those spokes must all + reside in the same VPC network. Spokes that do not + use data transfer can be associated with any VPC + network in your project. """ # Create or coerce a protobuf request object. @@ -591,16 +605,16 @@ async def sample_create_hub(): async def update_hub( self, - request: Union[gcn_hub.UpdateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.UpdateHubRequest, dict]] = None, *, - hub: gcn_hub.Hub = None, - update_mask: field_mask_pb2.FieldMask = None, + hub: Optional[gcn_hub.Hub] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Updates the description and/or labels of the - specified hub. + r"""Updates the description and/or labels of a Network + Connectivity Center hub. .. code-block:: python @@ -626,13 +640,13 @@ async def sample_update_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.UpdateHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.UpdateHubRequest, dict]]): The request object. Request for [HubService.UpdateHub][google.cloud.networkconnectivity.v1.HubService.UpdateHub] method. @@ -664,13 +678,13 @@ async def sample_update_hub(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A hub is a collection of spokes. A single hub can contain spokes from - multiple regions. However, if any of a hub's spokes - use the data transfer feature, the resources - associated with those spokes must all reside in the - same VPC network. Spokes that do not use data - transfer can be associated with any VPC network in - your project. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub + can contain spokes from multiple regions. However, if + any of a hub's spokes use the data transfer feature, + the resources associated with those spokes must all + reside in the same VPC network. Spokes that do not + use data transfer can be associated with any VPC + network in your project. """ # Create or coerce a protobuf request object. @@ -727,14 +741,14 @@ async def sample_update_hub(): async def delete_hub( self, - request: Union[hub.DeleteHubRequest, dict] = None, + request: Optional[Union[hub.DeleteHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Deletes the specified hub. + r"""Deletes a Network Connectivity Center hub. .. code-block:: python @@ -761,13 +775,13 @@ async def sample_delete_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.DeleteHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.DeleteHubRequest, dict]]): The request object. The request for [HubService.DeleteHub][google.cloud.networkconnectivity.v1.HubService.DeleteHub]. name (:class:`str`): @@ -851,15 +865,15 @@ async def sample_delete_hub(): async def list_spokes( self, - request: Union[hub.ListSpokesRequest, dict] = None, + request: Optional[Union[hub.ListSpokesRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSpokesAsyncPager: - r"""Lists the spokes in the specified project and - location. + r"""Lists the Network Connectivity Center spokes in a + specified project and location. .. code-block:: python @@ -889,7 +903,7 @@ async def sample_list_spokes(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.ListSpokesRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListSpokesRequest, dict]]): The request object. The request for [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. parent (:class:`str`): @@ -906,7 +920,7 @@ async def sample_list_spokes(): Returns: google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListSpokesAsyncPager: The response for - [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. + [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. Iterating over this object will yield results and resolve additional pages automatically. @@ -965,14 +979,15 @@ async def sample_list_spokes(): async def get_spoke( self, - request: Union[hub.GetSpokeRequest, dict] = None, + request: Optional[Union[hub.GetSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Spoke: - r"""Gets details about the specified spoke. + r"""Gets details about a Network Connectivity Center + spoke. .. code-block:: python @@ -1001,7 +1016,7 @@ async def sample_get_spoke(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.GetSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.GetSpokeRequest, dict]]): The request object. The request for [HubService.GetSpoke][google.cloud.networkconnectivity.v1.HubService.GetSpoke]. name (:class:`str`): @@ -1019,8 +1034,9 @@ async def sample_get_spoke(): Returns: google.cloud.networkconnectivity_v1.types.Spoke: - A spoke represents a connection between your Google Cloud network resources - and a non-Google-Cloud network. + A Network Connectivity Center spoke represents a connection between your + Google Cloud network resources and a non-Google-Cloud + network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1075,17 +1091,16 @@ async def sample_get_spoke(): async def create_spoke( self, - request: Union[hub.CreateSpokeRequest, dict] = None, + request: Optional[Union[hub.CreateSpokeRequest, dict]] = None, *, - parent: str = None, - spoke: hub.Spoke = None, - spoke_id: str = None, + parent: Optional[str] = None, + spoke: Optional[hub.Spoke] = None, + spoke_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Creates a spoke in the specified project and - location. + r"""Creates a Network Connectivity Center spoke. .. code-block:: python @@ -1113,13 +1128,13 @@ async def sample_create_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.CreateSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.CreateSpokeRequest, dict]]): The request object. The request for [HubService.CreateSpoke][google.cloud.networkconnectivity.v1.HubService.CreateSpoke]. parent (:class:`str`): @@ -1151,8 +1166,9 @@ async def sample_create_spoke(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A spoke represents a connection between your Google Cloud network resources - and a non-Google-Cloud network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your + Google Cloud network resources and a non-Google-Cloud + network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1219,15 +1235,16 @@ async def sample_create_spoke(): async def update_spoke( self, - request: Union[hub.UpdateSpokeRequest, dict] = None, + request: Optional[Union[hub.UpdateSpokeRequest, dict]] = None, *, - spoke: hub.Spoke = None, - update_mask: field_mask_pb2.FieldMask = None, + spoke: Optional[hub.Spoke] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Updates the parameters of the specified spoke. + r"""Updates the parameters of a Network Connectivity + Center spoke. .. code-block:: python @@ -1253,13 +1270,13 @@ async def sample_update_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.UpdateSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.UpdateSpokeRequest, dict]]): The request object. Request for [HubService.UpdateSpoke][google.cloud.networkconnectivity.v1.HubService.UpdateSpoke] method. @@ -1291,8 +1308,9 @@ async def sample_update_spoke(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A spoke represents a connection between your Google Cloud network resources - and a non-Google-Cloud network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your + Google Cloud network resources and a non-Google-Cloud + network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1359,14 +1377,14 @@ async def sample_update_spoke(): async def delete_spoke( self, - request: Union[hub.DeleteSpokeRequest, dict] = None, + request: Optional[Union[hub.DeleteSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: - r"""Deletes the specified spoke. + r"""Deletes a Network Connectivity Center spoke. .. code-block:: python @@ -1393,13 +1411,13 @@ async def sample_delete_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.DeleteSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.DeleteSpokeRequest, dict]]): The request object. The request for [HubService.DeleteSpoke][google.cloud.networkconnectivity.v1.HubService.DeleteSpoke]. name (:class:`str`): @@ -1488,14 +1506,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-networkconnectivity", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("HubServiceAsyncClient",) diff --git a/google/cloud/networkconnectivity_v1/services/hub_service/client.py b/google/cloud/networkconnectivity_v1/services/hub_service/client.py index 60a0858..8338eb0 100644 --- a/google/cloud/networkconnectivity_v1/services/hub_service/client.py +++ b/google/cloud/networkconnectivity_v1/services/hub_service/client.py @@ -16,7 +16,18 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -27,7 +38,8 @@ 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 -import pkg_resources + +from google.cloud.networkconnectivity_v1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -64,7 +76,7 @@ class HubServiceClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[HubServiceTransport]: """Returns an appropriate transport class. @@ -447,8 +459,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, HubServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, HubServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the hub service client. @@ -462,7 +474,7 @@ def __init__( transport (Union[str, HubServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -492,6 +504,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -544,14 +557,15 @@ def __init__( def list_hubs( self, - request: Union[hub.ListHubsRequest, dict] = None, + request: Optional[Union[hub.ListHubsRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListHubsPager: - r"""Lists hubs in a given project. + r"""Lists the Network Connectivity Center hubs associated + with a given project. .. code-block:: python @@ -599,8 +613,8 @@ def sample_list_hubs(): Returns: google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubsPager: Response for - [HubService.ListHubs][google.cloud.networkconnectivity.v1.HubService.ListHubs] - method. + [HubService.ListHubs][google.cloud.networkconnectivity.v1.HubService.ListHubs] + method. Iterating over this object will yield results and resolve additional pages automatically. @@ -659,14 +673,14 @@ def sample_list_hubs(): def get_hub( self, - request: Union[hub.GetHubRequest, dict] = None, + request: Optional[Union[hub.GetHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Hub: - r"""Gets details about the specified hub. + r"""Gets details about a Network Connectivity Center hub. .. code-block:: python @@ -714,15 +728,16 @@ def sample_get_hub(): Returns: google.cloud.networkconnectivity_v1.types.Hub: - A hub is a collection of spokes. A - single hub can contain spokes from - multiple regions. However, if any of a - hub's spokes use the data transfer - feature, the resources associated with - those spokes must all reside in the same - VPC network. Spokes that do not use data - transfer can be associated with any VPC - network in your project. + A Network Connectivity Center hub is + a collection of spokes. A single hub can + contain spokes from multiple regions. + However, if any of a hub's spokes use + the data transfer feature, the resources + associated with those spokes must all + reside in the same VPC network. Spokes + that do not use data transfer can be + associated with any VPC network in your + project. """ # Create or coerce a protobuf request object. @@ -769,16 +784,17 @@ def sample_get_hub(): def create_hub( self, - request: Union[gcn_hub.CreateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.CreateHubRequest, dict]] = None, *, - parent: str = None, - hub: gcn_hub.Hub = None, - hub_id: str = None, + parent: Optional[str] = None, + hub: Optional[gcn_hub.Hub] = None, + hub_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Creates a new hub in the specified project. + r"""Creates a new Network Connectivity Center hub in the + specified project. .. code-block:: python @@ -845,13 +861,13 @@ def sample_create_hub(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A hub is a collection of spokes. A single hub can contain spokes from - multiple regions. However, if any of a hub's spokes - use the data transfer feature, the resources - associated with those spokes must all reside in the - same VPC network. Spokes that do not use data - transfer can be associated with any VPC network in - your project. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub + can contain spokes from multiple regions. However, if + any of a hub's spokes use the data transfer feature, + the resources associated with those spokes must all + reside in the same VPC network. Spokes that do not + use data transfer can be associated with any VPC + network in your project. """ # Create or coerce a protobuf request object. @@ -910,16 +926,16 @@ def sample_create_hub(): def update_hub( self, - request: Union[gcn_hub.UpdateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.UpdateHubRequest, dict]] = None, *, - hub: gcn_hub.Hub = None, - update_mask: field_mask_pb2.FieldMask = None, + hub: Optional[gcn_hub.Hub] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Updates the description and/or labels of the - specified hub. + r"""Updates the description and/or labels of a Network + Connectivity Center hub. .. code-block:: python @@ -983,13 +999,13 @@ def sample_update_hub(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A hub is a collection of spokes. A single hub can contain spokes from - multiple regions. However, if any of a hub's spokes - use the data transfer feature, the resources - associated with those spokes must all reside in the - same VPC network. Spokes that do not use data - transfer can be associated with any VPC network in - your project. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub + can contain spokes from multiple regions. However, if + any of a hub's spokes use the data transfer feature, + the resources associated with those spokes must all + reside in the same VPC network. Spokes that do not + use data transfer can be associated with any VPC + network in your project. """ # Create or coerce a protobuf request object. @@ -1046,14 +1062,14 @@ def sample_update_hub(): def delete_hub( self, - request: Union[hub.DeleteHubRequest, dict] = None, + request: Optional[Union[hub.DeleteHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Deletes the specified hub. + r"""Deletes a Network Connectivity Center hub. .. code-block:: python @@ -1170,15 +1186,15 @@ def sample_delete_hub(): def list_spokes( self, - request: Union[hub.ListSpokesRequest, dict] = None, + request: Optional[Union[hub.ListSpokesRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSpokesPager: - r"""Lists the spokes in the specified project and - location. + r"""Lists the Network Connectivity Center spokes in a + specified project and location. .. code-block:: python @@ -1225,7 +1241,7 @@ def sample_list_spokes(): Returns: google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListSpokesPager: The response for - [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. + [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. Iterating over this object will yield results and resolve additional pages automatically. @@ -1284,14 +1300,15 @@ def sample_list_spokes(): def get_spoke( self, - request: Union[hub.GetSpokeRequest, dict] = None, + request: Optional[Union[hub.GetSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Spoke: - r"""Gets details about the specified spoke. + r"""Gets details about a Network Connectivity Center + spoke. .. code-block:: python @@ -1338,8 +1355,9 @@ def sample_get_spoke(): Returns: google.cloud.networkconnectivity_v1.types.Spoke: - A spoke represents a connection between your Google Cloud network resources - and a non-Google-Cloud network. + A Network Connectivity Center spoke represents a connection between your + Google Cloud network resources and a non-Google-Cloud + network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1394,17 +1412,16 @@ def sample_get_spoke(): def create_spoke( self, - request: Union[hub.CreateSpokeRequest, dict] = None, + request: Optional[Union[hub.CreateSpokeRequest, dict]] = None, *, - parent: str = None, - spoke: hub.Spoke = None, - spoke_id: str = None, + parent: Optional[str] = None, + spoke: Optional[hub.Spoke] = None, + spoke_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Creates a spoke in the specified project and - location. + r"""Creates a Network Connectivity Center spoke. .. code-block:: python @@ -1470,8 +1487,9 @@ def sample_create_spoke(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A spoke represents a connection between your Google Cloud network resources - and a non-Google-Cloud network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your + Google Cloud network resources and a non-Google-Cloud + network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1538,15 +1556,16 @@ def sample_create_spoke(): def update_spoke( self, - request: Union[hub.UpdateSpokeRequest, dict] = None, + request: Optional[Union[hub.UpdateSpokeRequest, dict]] = None, *, - spoke: hub.Spoke = None, - update_mask: field_mask_pb2.FieldMask = None, + spoke: Optional[hub.Spoke] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Updates the parameters of the specified spoke. + r"""Updates the parameters of a Network Connectivity + Center spoke. .. code-block:: python @@ -1610,8 +1629,9 @@ def sample_update_spoke(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A spoke represents a connection between your Google Cloud network resources - and a non-Google-Cloud network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your + Google Cloud network resources and a non-Google-Cloud + network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1678,14 +1698,14 @@ def sample_update_spoke(): def delete_spoke( self, - request: Union[hub.DeleteSpokeRequest, dict] = None, + request: Optional[Union[hub.DeleteSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: - r"""Deletes the specified spoke. + r"""Deletes a Network Connectivity Center spoke. .. code-block:: python @@ -1814,14 +1834,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-networkconnectivity", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("HubServiceClient",) diff --git a/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py b/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py index 04842ae..58b6aec 100644 --- a/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py +++ b/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py @@ -24,19 +24,14 @@ 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 -import pkg_resources +from google.cloud.networkconnectivity_v1 import gapic_version as package_version from google.cloud.networkconnectivity_v1.types import hub from google.cloud.networkconnectivity_v1.types import hub as gcn_hub -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-networkconnectivity", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class HubServiceTransport(abc.ABC): @@ -50,7 +45,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py b/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py index 447ecdb..e43d6be 100644 --- a/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py +++ b/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py @@ -51,14 +51,14 @@ def __init__( self, *, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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, @@ -186,8 +186,8 @@ def __init__( def create_channel( cls, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, @@ -252,7 +252,8 @@ def operations_client(self) -> operations_v1.OperationsClient: def list_hubs(self) -> Callable[[hub.ListHubsRequest], hub.ListHubsResponse]: r"""Return a callable for the list hubs method over gRPC. - Lists hubs in a given project. + Lists the Network Connectivity Center hubs associated + with a given project. Returns: Callable[[~.ListHubsRequest], @@ -276,7 +277,7 @@ def list_hubs(self) -> Callable[[hub.ListHubsRequest], hub.ListHubsResponse]: def get_hub(self) -> Callable[[hub.GetHubRequest], hub.Hub]: r"""Return a callable for the get hub method over gRPC. - Gets details about the specified hub. + Gets details about a Network Connectivity Center hub. Returns: Callable[[~.GetHubRequest], @@ -302,7 +303,8 @@ def create_hub( ) -> Callable[[gcn_hub.CreateHubRequest], operations_pb2.Operation]: r"""Return a callable for the create hub method over gRPC. - Creates a new hub in the specified project. + Creates a new Network Connectivity Center hub in the + specified project. Returns: Callable[[~.CreateHubRequest], @@ -328,8 +330,8 @@ def update_hub( ) -> Callable[[gcn_hub.UpdateHubRequest], operations_pb2.Operation]: r"""Return a callable for the update hub method over gRPC. - Updates the description and/or labels of the - specified hub. + Updates the description and/or labels of a Network + Connectivity Center hub. Returns: Callable[[~.UpdateHubRequest], @@ -353,7 +355,7 @@ def update_hub( def delete_hub(self) -> Callable[[hub.DeleteHubRequest], operations_pb2.Operation]: r"""Return a callable for the delete hub method over gRPC. - Deletes the specified hub. + Deletes a Network Connectivity Center hub. Returns: Callable[[~.DeleteHubRequest], @@ -377,8 +379,8 @@ def delete_hub(self) -> Callable[[hub.DeleteHubRequest], operations_pb2.Operatio def list_spokes(self) -> Callable[[hub.ListSpokesRequest], hub.ListSpokesResponse]: r"""Return a callable for the list spokes method over gRPC. - Lists the spokes in the specified project and - location. + Lists the Network Connectivity Center spokes in a + specified project and location. Returns: Callable[[~.ListSpokesRequest], @@ -402,7 +404,8 @@ def list_spokes(self) -> Callable[[hub.ListSpokesRequest], hub.ListSpokesRespons def get_spoke(self) -> Callable[[hub.GetSpokeRequest], hub.Spoke]: r"""Return a callable for the get spoke method over gRPC. - Gets details about the specified spoke. + Gets details about a Network Connectivity Center + spoke. Returns: Callable[[~.GetSpokeRequest], @@ -428,8 +431,7 @@ def create_spoke( ) -> Callable[[hub.CreateSpokeRequest], operations_pb2.Operation]: r"""Return a callable for the create spoke method over gRPC. - Creates a spoke in the specified project and - location. + Creates a Network Connectivity Center spoke. Returns: Callable[[~.CreateSpokeRequest], @@ -455,7 +457,8 @@ def update_spoke( ) -> Callable[[hub.UpdateSpokeRequest], operations_pb2.Operation]: r"""Return a callable for the update spoke method over gRPC. - Updates the parameters of the specified spoke. + Updates the parameters of a Network Connectivity + Center spoke. Returns: Callable[[~.UpdateSpokeRequest], @@ -481,7 +484,7 @@ def delete_spoke( ) -> Callable[[hub.DeleteSpokeRequest], operations_pb2.Operation]: r"""Return a callable for the delete spoke method over gRPC. - Deletes the specified spoke. + Deletes a Network Connectivity Center spoke. Returns: Callable[[~.DeleteSpokeRequest], diff --git a/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py b/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py index 94b6a6b..d8e32dd 100644 --- a/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py +++ b/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py @@ -53,7 +53,7 @@ class HubServiceGrpcAsyncIOTransport(HubServiceTransport): def create_channel( cls, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -96,15 +96,15 @@ def __init__( self, *, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[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, @@ -259,7 +259,8 @@ def list_hubs( ) -> Callable[[hub.ListHubsRequest], Awaitable[hub.ListHubsResponse]]: r"""Return a callable for the list hubs method over gRPC. - Lists hubs in a given project. + Lists the Network Connectivity Center hubs associated + with a given project. Returns: Callable[[~.ListHubsRequest], @@ -283,7 +284,7 @@ def list_hubs( def get_hub(self) -> Callable[[hub.GetHubRequest], Awaitable[hub.Hub]]: r"""Return a callable for the get hub method over gRPC. - Gets details about the specified hub. + Gets details about a Network Connectivity Center hub. Returns: Callable[[~.GetHubRequest], @@ -309,7 +310,8 @@ def create_hub( ) -> Callable[[gcn_hub.CreateHubRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the create hub method over gRPC. - Creates a new hub in the specified project. + Creates a new Network Connectivity Center hub in the + specified project. Returns: Callable[[~.CreateHubRequest], @@ -335,8 +337,8 @@ def update_hub( ) -> Callable[[gcn_hub.UpdateHubRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the update hub method over gRPC. - Updates the description and/or labels of the - specified hub. + Updates the description and/or labels of a Network + Connectivity Center hub. Returns: Callable[[~.UpdateHubRequest], @@ -362,7 +364,7 @@ def delete_hub( ) -> Callable[[hub.DeleteHubRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the delete hub method over gRPC. - Deletes the specified hub. + Deletes a Network Connectivity Center hub. Returns: Callable[[~.DeleteHubRequest], @@ -388,8 +390,8 @@ def list_spokes( ) -> Callable[[hub.ListSpokesRequest], Awaitable[hub.ListSpokesResponse]]: r"""Return a callable for the list spokes method over gRPC. - Lists the spokes in the specified project and - location. + Lists the Network Connectivity Center spokes in a + specified project and location. Returns: Callable[[~.ListSpokesRequest], @@ -413,7 +415,8 @@ def list_spokes( def get_spoke(self) -> Callable[[hub.GetSpokeRequest], Awaitable[hub.Spoke]]: r"""Return a callable for the get spoke method over gRPC. - Gets details about the specified spoke. + Gets details about a Network Connectivity Center + spoke. Returns: Callable[[~.GetSpokeRequest], @@ -439,8 +442,7 @@ def create_spoke( ) -> Callable[[hub.CreateSpokeRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the create spoke method over gRPC. - Creates a spoke in the specified project and - location. + Creates a Network Connectivity Center spoke. Returns: Callable[[~.CreateSpokeRequest], @@ -466,7 +468,8 @@ def update_spoke( ) -> Callable[[hub.UpdateSpokeRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the update spoke method over gRPC. - Updates the parameters of the specified spoke. + Updates the parameters of a Network Connectivity + Center spoke. Returns: Callable[[~.UpdateSpokeRequest], @@ -492,7 +495,7 @@ def delete_spoke( ) -> Callable[[hub.DeleteSpokeRequest], Awaitable[operations_pb2.Operation]]: r"""Return a callable for the delete spoke method over gRPC. - Deletes the specified spoke. + Deletes a Network Connectivity Center spoke. Returns: Callable[[~.DeleteSpokeRequest], diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/__init__.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/__init__.py new file mode 100644 index 0000000..b48618d --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from .async_client import PolicyBasedRoutingServiceAsyncClient +from .client import PolicyBasedRoutingServiceClient + +__all__ = ( + "PolicyBasedRoutingServiceClient", + "PolicyBasedRoutingServiceAsyncClient", +) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/async_client.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/async_client.py new file mode 100644 index 0000000..20494f5 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/async_client.py @@ -0,0 +1,754 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import functools +import re +from typing import ( + 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 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.cloud.networkconnectivity_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.networkconnectivity_v1.services.policy_based_routing_service import ( + pagers, +) +from google.cloud.networkconnectivity_v1.types import common, policy_based_routing + +from .client import PolicyBasedRoutingServiceClient +from .transports.base import DEFAULT_CLIENT_INFO, PolicyBasedRoutingServiceTransport +from .transports.grpc_asyncio import PolicyBasedRoutingServiceGrpcAsyncIOTransport + + +class PolicyBasedRoutingServiceAsyncClient: + """Policy-Based Routing allows GCP customers to specify + flexibile routing policies for Layer 4 traffic traversing + through the connected service. + """ + + _client: PolicyBasedRoutingServiceClient + + DEFAULT_ENDPOINT = PolicyBasedRoutingServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = PolicyBasedRoutingServiceClient.DEFAULT_MTLS_ENDPOINT + + network_path = staticmethod(PolicyBasedRoutingServiceClient.network_path) + parse_network_path = staticmethod( + PolicyBasedRoutingServiceClient.parse_network_path + ) + policy_based_route_path = staticmethod( + PolicyBasedRoutingServiceClient.policy_based_route_path + ) + parse_policy_based_route_path = staticmethod( + PolicyBasedRoutingServiceClient.parse_policy_based_route_path + ) + common_billing_account_path = staticmethod( + PolicyBasedRoutingServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + PolicyBasedRoutingServiceClient.parse_common_billing_account_path + ) + common_folder_path = staticmethod( + PolicyBasedRoutingServiceClient.common_folder_path + ) + parse_common_folder_path = staticmethod( + PolicyBasedRoutingServiceClient.parse_common_folder_path + ) + common_organization_path = staticmethod( + PolicyBasedRoutingServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + PolicyBasedRoutingServiceClient.parse_common_organization_path + ) + common_project_path = staticmethod( + PolicyBasedRoutingServiceClient.common_project_path + ) + parse_common_project_path = staticmethod( + PolicyBasedRoutingServiceClient.parse_common_project_path + ) + common_location_path = staticmethod( + PolicyBasedRoutingServiceClient.common_location_path + ) + parse_common_location_path = staticmethod( + PolicyBasedRoutingServiceClient.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: + PolicyBasedRoutingServiceAsyncClient: The constructed client. + """ + return PolicyBasedRoutingServiceClient.from_service_account_info.__func__(PolicyBasedRoutingServiceAsyncClient, 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: + PolicyBasedRoutingServiceAsyncClient: The constructed client. + """ + return PolicyBasedRoutingServiceClient.from_service_account_file.__func__(PolicyBasedRoutingServiceAsyncClient, 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 variabel 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 PolicyBasedRoutingServiceClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore + + @property + def transport(self) -> PolicyBasedRoutingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyBasedRoutingServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(PolicyBasedRoutingServiceClient).get_transport_class, + type(PolicyBasedRoutingServiceClient), + ) + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Union[str, PolicyBasedRoutingServiceTransport] = "grpc_asyncio", + client_options: Optional[ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy based routing service 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 (Union[str, ~.PolicyBasedRoutingServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client = PolicyBasedRoutingServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def list_policy_based_routes( + self, + request: Optional[ + Union[policy_based_routing.ListPolicyBasedRoutesRequest, 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.ListPolicyBasedRoutesAsyncPager: + r"""Lists PolicyBasedRoutes in a given project and + location. + + .. 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.cloud import networkconnectivity_v1 + + async def sample_list_policy_based_routes(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListPolicyBasedRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_based_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesRequest, dict]]): + The request object. Request for + [PolicyBasedRouting.ListPolicyBasedRoutes][] method. + parent (:class:`str`): + Required. The parent resource's name. + 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.cloud.networkconnectivity_v1.services.policy_based_routing_service.pagers.ListPolicyBasedRoutesAsyncPager: + Response for + [PolicyBasedRouting.ListPolicyBasedRoutes][] method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 = policy_based_routing.ListPolicyBasedRoutesRequest(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.list_policy_based_routes, + 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((("parent", request.parent),)), + ) + + # 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.ListPolicyBasedRoutesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_policy_based_route( + self, + request: Optional[ + Union[policy_based_routing.GetPolicyBasedRouteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_based_routing.PolicyBasedRoute: + r"""Gets details of a single PolicyBasedRoute. + + .. 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.cloud import networkconnectivity_v1 + + async def sample_get_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetPolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_policy_based_route(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.GetPolicyBasedRouteRequest, dict]]): + The request object. Request for + [PolicyBasedRouting.GetPolicyBasedRoute][] method. + name (:class:`str`): + Required. Name of the + PolicyBasedRoute resource to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.networkconnectivity_v1.types.PolicyBasedRoute: + Policy Based Routes (PBR) are more + powerful routes that allows GCP + customers to route their L4 network + traffic based on not just destination + IP, but also source IP, protocol and + more. A PBR always take precedence when + it conflicts with other types of routes. + Next id: 19 + + """ + # 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([name]) + 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 = policy_based_routing.GetPolicyBasedRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # 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_policy_based_route, + 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),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def create_policy_based_route( + self, + request: Optional[ + Union[policy_based_routing.CreatePolicyBasedRouteRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + policy_based_route: Optional[policy_based_routing.PolicyBasedRoute] = None, + policy_based_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Creates a new PolicyBasedRoute in a given project and + location. + + .. 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.cloud import networkconnectivity_v1 + + async def sample_create_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + policy_based_route = networkconnectivity_v1.PolicyBasedRoute() + policy_based_route.next_hop_ilb_ip = "next_hop_ilb_ip_value" + policy_based_route.network = "network_value" + policy_based_route.filter.protocol_version = "IPV4" + + request = networkconnectivity_v1.CreatePolicyBasedRouteRequest( + parent="parent_value", + policy_based_route=policy_based_route, + ) + + # Make the request + operation = client.create_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.CreatePolicyBasedRouteRequest, dict]]): + The request object. Request for + [PolicyBasedRouting.CreatePolicyBasedRoute][] method. + parent (:class:`str`): + Required. The parent resource's name + of the PolicyBasedRoute. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_based_route (:class:`google.cloud.networkconnectivity_v1.types.PolicyBasedRoute`): + Required. Initial values for a new + Policy Based Route. + + This corresponds to the ``policy_based_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_based_route_id (:class:`str`): + Optional. Unique id for the Policy + Based Route to create. + + This corresponds to the ``policy_based_route_id`` 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.PolicyBasedRoute` Policy Based Routes (PBR) are more powerful routes that allows GCP customers + to route their L4 network traffic based on not just + destination IP, but also source IP, protocol and + more. A PBR always take precedence when it conflicts + with other types of routes. Next id: 19 + + """ + # 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, policy_based_route, policy_based_route_id]) + 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 = policy_based_routing.CreatePolicyBasedRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_based_route is not None: + request.policy_based_route = policy_based_route + if policy_based_route_id is not None: + request.policy_based_route_id = policy_based_route_id + + # 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_policy_based_route, + 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),)), + ) + + # 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, + policy_based_routing.PolicyBasedRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_policy_based_route( + self, + request: Optional[ + Union[policy_based_routing.DeletePolicyBasedRouteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a single PolicyBasedRoute. + + .. 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.cloud import networkconnectivity_v1 + + async def sample_delete_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.DeletePolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.DeletePolicyBasedRouteRequest, dict]]): + The request object. Request for + [PolicyBasedRouting.DeletePolicyBasedRoute][] method. + name (:class:`str`): + Required. Name of the + PolicyBasedRoute resource to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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([name]) + 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 = policy_based_routing.DeletePolicyBasedRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_policy_based_route, + 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((("name", request.name),)), + ) + + # 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, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def __aenter__(self): + 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__ = ("PolicyBasedRoutingServiceAsyncClient",) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/client.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/client.py new file mode 100644 index 0000000..32678e9 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/client.py @@ -0,0 +1,996 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +import os +import re +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +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.cloud.networkconnectivity_v1 import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object] # type: ignore + +from google.api_core import operation # type: ignore +from google.api_core import operation_async # type: ignore +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore + +from google.cloud.networkconnectivity_v1.services.policy_based_routing_service import ( + pagers, +) +from google.cloud.networkconnectivity_v1.types import common, policy_based_routing + +from .transports.base import DEFAULT_CLIENT_INFO, PolicyBasedRoutingServiceTransport +from .transports.grpc import PolicyBasedRoutingServiceGrpcTransport +from .transports.grpc_asyncio import PolicyBasedRoutingServiceGrpcAsyncIOTransport + + +class PolicyBasedRoutingServiceClientMeta(type): + """Metaclass for the PolicyBasedRoutingService 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[PolicyBasedRoutingServiceTransport]] + _transport_registry["grpc"] = PolicyBasedRoutingServiceGrpcTransport + _transport_registry["grpc_asyncio"] = PolicyBasedRoutingServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[PolicyBasedRoutingServiceTransport]: + """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 PolicyBasedRoutingServiceClient(metaclass=PolicyBasedRoutingServiceClientMeta): + """Policy-Based Routing allows GCP customers to specify + flexibile routing policies for Layer 4 traffic traversing + through the connected service. + """ + + @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[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.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") + + DEFAULT_ENDPOINT = "networkconnectivity.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + PolicyBasedRoutingServiceClient: 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: + PolicyBasedRoutingServiceClient: 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) -> PolicyBasedRoutingServiceTransport: + """Returns the transport used by the client instance. + + Returns: + PolicyBasedRoutingServiceTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def network_path( + project: str, + resource_id: str, + ) -> str: + """Returns a fully-qualified network string.""" + return "projects/{project}/global/networks/{resource_id}".format( + project=project, + resource_id=resource_id, + ) + + @staticmethod + def parse_network_path(path: str) -> Dict[str, str]: + """Parses a network path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/global/networks/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def policy_based_route_path( + project: str, + location: str, + policy_based_route: str, + ) -> str: + """Returns a fully-qualified policy_based_route string.""" + return "projects/{project}/{location}/global/PolicyBasedRoutes/{policy_based_route}".format( + project=project, + location=location, + policy_based_route=policy_based_route, + ) + + @staticmethod + def parse_policy_based_route_path(path: str) -> Dict[str, str]: + """Parses a policy_based_route path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/(?P.+?)/global/PolicyBasedRoutes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @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.+?)$", 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.+?)$", 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.+?)$", 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.+?)$", 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.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @classmethod + def get_mtls_endpoint_and_cert_source( + cls, client_options: Optional[client_options_lib.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 variabel 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. + """ + 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 + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[Union[str, PolicyBasedRoutingServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the policy based routing service 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 (Union[str, PolicyBasedRoutingServiceTransport]): The + transport to use. 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. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "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). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS 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. + 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. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) + + api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( + client_options + ) + + api_key_value = getattr(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. + if isinstance(transport, PolicyBasedRoutingServiceTransport): + # transport is a PolicyBasedRoutingServiceTransport instance. + if credentials or client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = transport + else: + 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 = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + client_cert_source_for_mtls=client_cert_source_func, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=client_options.api_audience, + ) + + def list_policy_based_routes( + self, + request: Optional[ + Union[policy_based_routing.ListPolicyBasedRoutesRequest, 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.ListPolicyBasedRoutesPager: + r"""Lists PolicyBasedRoutes in a given project and + location. + + .. 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.cloud import networkconnectivity_v1 + + def sample_list_policy_based_routes(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListPolicyBasedRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_based_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesRequest, dict]): + The request object. Request for + [PolicyBasedRouting.ListPolicyBasedRoutes][] method. + parent (str): + Required. The parent resource's name. + 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.cloud.networkconnectivity_v1.services.policy_based_routing_service.pagers.ListPolicyBasedRoutesPager: + Response for + [PolicyBasedRouting.ListPolicyBasedRoutes][] method. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # 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 policy_based_routing.ListPolicyBasedRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policy_based_routing.ListPolicyBasedRoutesRequest): + request = policy_based_routing.ListPolicyBasedRoutesRequest(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.list_policy_based_routes] + + # 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),)), + ) + + # 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.ListPolicyBasedRoutesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_policy_based_route( + self, + request: Optional[ + Union[policy_based_routing.GetPolicyBasedRouteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy_based_routing.PolicyBasedRoute: + r"""Gets details of a single PolicyBasedRoute. + + .. 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.cloud import networkconnectivity_v1 + + def sample_get_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetPolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_policy_based_route(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.GetPolicyBasedRouteRequest, dict]): + The request object. Request for + [PolicyBasedRouting.GetPolicyBasedRoute][] method. + name (str): + Required. Name of the + PolicyBasedRoute resource to get. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.networkconnectivity_v1.types.PolicyBasedRoute: + Policy Based Routes (PBR) are more + powerful routes that allows GCP + customers to route their L4 network + traffic based on not just destination + IP, but also source IP, protocol and + more. A PBR always take precedence when + it conflicts with other types of routes. + Next id: 19 + + """ + # 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([name]) + 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 policy_based_routing.GetPolicyBasedRouteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policy_based_routing.GetPolicyBasedRouteRequest): + request = policy_based_routing.GetPolicyBasedRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_policy_based_route] + + # 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),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def create_policy_based_route( + self, + request: Optional[ + Union[policy_based_routing.CreatePolicyBasedRouteRequest, dict] + ] = None, + *, + parent: Optional[str] = None, + policy_based_route: Optional[policy_based_routing.PolicyBasedRoute] = None, + policy_based_route_id: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Creates a new PolicyBasedRoute in a given project and + location. + + .. 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.cloud import networkconnectivity_v1 + + def sample_create_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + policy_based_route = networkconnectivity_v1.PolicyBasedRoute() + policy_based_route.next_hop_ilb_ip = "next_hop_ilb_ip_value" + policy_based_route.network = "network_value" + policy_based_route.filter.protocol_version = "IPV4" + + request = networkconnectivity_v1.CreatePolicyBasedRouteRequest( + parent="parent_value", + policy_based_route=policy_based_route, + ) + + # Make the request + operation = client.create_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.CreatePolicyBasedRouteRequest, dict]): + The request object. Request for + [PolicyBasedRouting.CreatePolicyBasedRoute][] method. + parent (str): + Required. The parent resource's name + of the PolicyBasedRoute. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_based_route (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute): + Required. Initial values for a new + Policy Based Route. + + This corresponds to the ``policy_based_route`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + policy_based_route_id (str): + Optional. Unique id for the Policy + Based Route to create. + + This corresponds to the ``policy_based_route_id`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.PolicyBasedRoute` Policy Based Routes (PBR) are more powerful routes that allows GCP customers + to route their L4 network traffic based on not just + destination IP, but also source IP, protocol and + more. A PBR always take precedence when it conflicts + with other types of routes. Next id: 19 + + """ + # 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, policy_based_route, policy_based_route_id]) + 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 policy_based_routing.CreatePolicyBasedRouteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policy_based_routing.CreatePolicyBasedRouteRequest): + request = policy_based_routing.CreatePolicyBasedRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if policy_based_route is not None: + request.policy_based_route = policy_based_route + if policy_based_route_id is not None: + request.policy_based_route_id = policy_based_route_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.create_policy_based_route + ] + + # 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),)), + ) + + # 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, + policy_based_routing.PolicyBasedRoute, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_policy_based_route( + self, + request: Optional[ + Union[policy_based_routing.DeletePolicyBasedRouteRequest, dict] + ] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Deletes a single PolicyBasedRoute. + + .. 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.cloud import networkconnectivity_v1 + + def sample_delete_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.DeletePolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.DeletePolicyBasedRouteRequest, dict]): + The request object. Request for + [PolicyBasedRouting.DeletePolicyBasedRoute][] method. + name (str): + Required. Name of the + PolicyBasedRoute resource to delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + 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.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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([name]) + 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 policy_based_routing.DeletePolicyBasedRouteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, policy_based_routing.DeletePolicyBasedRouteRequest): + request = policy_based_routing.DeletePolicyBasedRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.delete_policy_based_route + ] + + # 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),)), + ) + + # 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, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def __enter__(self): + 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() + + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +__all__ = ("PolicyBasedRoutingServiceClient",) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/pagers.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/pagers.py new file mode 100644 index 0000000..c3f2df5 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/pagers.py @@ -0,0 +1,159 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import ( + Any, + AsyncIterator, + Awaitable, + Callable, + Iterator, + Optional, + Sequence, + Tuple, +) + +from google.cloud.networkconnectivity_v1.types import policy_based_routing + + +class ListPolicyBasedRoutesPager: + """A pager for iterating through ``list_policy_based_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``policy_based_routes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListPolicyBasedRoutes`` requests and continue to iterate + through the ``policy_based_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesResponse` + 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[..., policy_based_routing.ListPolicyBasedRoutesResponse], + request: policy_based_routing.ListPolicyBasedRoutesRequest, + response: policy_based_routing.ListPolicyBasedRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesResponse): + 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 = policy_based_routing.ListPolicyBasedRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[policy_based_routing.ListPolicyBasedRoutesResponse]: + 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[policy_based_routing.PolicyBasedRoute]: + for page in self.pages: + yield from page.policy_based_routes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListPolicyBasedRoutesAsyncPager: + """A pager for iterating through ``list_policy_based_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``policy_based_routes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListPolicyBasedRoutes`` requests and continue to iterate + through the ``policy_based_routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesResponse` + 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[policy_based_routing.ListPolicyBasedRoutesResponse] + ], + request: policy_based_routing.ListPolicyBasedRoutesRequest, + response: policy_based_routing.ListPolicyBasedRoutesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesResponse): + 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 = policy_based_routing.ListPolicyBasedRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterator[policy_based_routing.ListPolicyBasedRoutesResponse]: + 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[policy_based_routing.PolicyBasedRoute]: + async def async_generator(): + async for page in self.pages: + for response in page.policy_based_routes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/__init__.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/__init__.py new file mode 100644 index 0000000..de64dfc --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/__init__.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from collections import OrderedDict +from typing import Dict, Type + +from .base import PolicyBasedRoutingServiceTransport +from .grpc import PolicyBasedRoutingServiceGrpcTransport +from .grpc_asyncio import PolicyBasedRoutingServiceGrpcAsyncIOTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[PolicyBasedRoutingServiceTransport]] +_transport_registry["grpc"] = PolicyBasedRoutingServiceGrpcTransport +_transport_registry["grpc_asyncio"] = PolicyBasedRoutingServiceGrpcAsyncIOTransport + +__all__ = ( + "PolicyBasedRoutingServiceTransport", + "PolicyBasedRoutingServiceGrpcTransport", + "PolicyBasedRoutingServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/base.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/base.py new file mode 100644 index 0000000..35e20a4 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/base.py @@ -0,0 +1,209 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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.cloud.networkconnectivity_v1 import gapic_version as package_version +from google.cloud.networkconnectivity_v1.types import policy_based_routing + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + + +class PolicyBasedRoutingServiceTransport(abc.ABC): + """Abstract transport class for PolicyBasedRoutingService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + DEFAULT_HOST: str = "networkconnectivity.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. + 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 + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.list_policy_based_routes: gapic_v1.method.wrap_method( + self.list_policy_based_routes, + default_timeout=None, + client_info=client_info, + ), + self.get_policy_based_route: gapic_v1.method.wrap_method( + self.get_policy_based_route, + default_timeout=None, + client_info=client_info, + ), + self.create_policy_based_route: gapic_v1.method.wrap_method( + self.create_policy_based_route, + default_timeout=60.0, + client_info=client_info, + ), + self.delete_policy_based_route: gapic_v1.method.wrap_method( + self.delete_policy_based_route, + default_timeout=60.0, + 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 list_policy_based_routes( + self, + ) -> Callable[ + [policy_based_routing.ListPolicyBasedRoutesRequest], + Union[ + policy_based_routing.ListPolicyBasedRoutesResponse, + Awaitable[policy_based_routing.ListPolicyBasedRoutesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.GetPolicyBasedRouteRequest], + Union[ + policy_based_routing.PolicyBasedRoute, + Awaitable[policy_based_routing.PolicyBasedRoute], + ], + ]: + raise NotImplementedError() + + @property + def create_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.CreatePolicyBasedRouteRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.DeletePolicyBasedRouteRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("PolicyBasedRoutingServiceTransport",) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/grpc.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/grpc.py new file mode 100644 index 0000000..768b35d --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/grpc.py @@ -0,0 +1,373 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +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.cloud.networkconnectivity_v1.types import policy_based_routing + +from .base import DEFAULT_CLIENT_INFO, PolicyBasedRoutingServiceTransport + + +class PolicyBasedRoutingServiceGrpcTransport(PolicyBasedRoutingServiceTransport): + """gRPC backend transport for PolicyBasedRoutingService. + + Policy-Based Routing allows GCP customers to specify + flexibile routing policies for Layer 4 traffic traversing + through the connected service. + + 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 = "networkconnectivity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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. + 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 ``channel`` 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. + 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. + 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 ``channel`` 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. + 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 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: + self._grpc_channel = type(self).create_channel( + 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 = "networkconnectivity.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 list_policy_based_routes( + self, + ) -> Callable[ + [policy_based_routing.ListPolicyBasedRoutesRequest], + policy_based_routing.ListPolicyBasedRoutesResponse, + ]: + r"""Return a callable for the list policy based routes method over gRPC. + + Lists PolicyBasedRoutes in a given project and + location. + + Returns: + Callable[[~.ListPolicyBasedRoutesRequest], + ~.ListPolicyBasedRoutesResponse]: + 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 "list_policy_based_routes" not in self._stubs: + self._stubs["list_policy_based_routes"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/ListPolicyBasedRoutes", + request_serializer=policy_based_routing.ListPolicyBasedRoutesRequest.serialize, + response_deserializer=policy_based_routing.ListPolicyBasedRoutesResponse.deserialize, + ) + return self._stubs["list_policy_based_routes"] + + @property + def get_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.GetPolicyBasedRouteRequest], + policy_based_routing.PolicyBasedRoute, + ]: + r"""Return a callable for the get policy based route method over gRPC. + + Gets details of a single PolicyBasedRoute. + + Returns: + Callable[[~.GetPolicyBasedRouteRequest], + ~.PolicyBasedRoute]: + 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 "get_policy_based_route" not in self._stubs: + self._stubs["get_policy_based_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/GetPolicyBasedRoute", + request_serializer=policy_based_routing.GetPolicyBasedRouteRequest.serialize, + response_deserializer=policy_based_routing.PolicyBasedRoute.deserialize, + ) + return self._stubs["get_policy_based_route"] + + @property + def create_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.CreatePolicyBasedRouteRequest], operations_pb2.Operation + ]: + r"""Return a callable for the create policy based route method over gRPC. + + Creates a new PolicyBasedRoute in a given project and + location. + + Returns: + Callable[[~.CreatePolicyBasedRouteRequest], + ~.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 "create_policy_based_route" not in self._stubs: + self._stubs["create_policy_based_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/CreatePolicyBasedRoute", + request_serializer=policy_based_routing.CreatePolicyBasedRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy_based_route"] + + @property + def delete_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.DeletePolicyBasedRouteRequest], operations_pb2.Operation + ]: + r"""Return a callable for the delete policy based route method over gRPC. + + Deletes a single PolicyBasedRoute. + + Returns: + Callable[[~.DeletePolicyBasedRouteRequest], + ~.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 "delete_policy_based_route" not in self._stubs: + self._stubs["delete_policy_based_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/DeletePolicyBasedRoute", + request_serializer=policy_based_routing.DeletePolicyBasedRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy_based_route"] + + def close(self): + self.grpc_channel.close() + + @property + def kind(self) -> str: + return "grpc" + + +__all__ = ("PolicyBasedRoutingServiceGrpcTransport",) diff --git a/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/grpc_asyncio.py b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/grpc_asyncio.py new file mode 100644 index 0000000..273dca7 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/services/policy_based_routing_service/transports/grpc_asyncio.py @@ -0,0 +1,376 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 +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.cloud.networkconnectivity_v1.types import policy_based_routing + +from .base import DEFAULT_CLIENT_INFO, PolicyBasedRoutingServiceTransport +from .grpc import PolicyBasedRoutingServiceGrpcTransport + + +class PolicyBasedRoutingServiceGrpcAsyncIOTransport(PolicyBasedRoutingServiceTransport): + """gRPC AsyncIO backend transport for PolicyBasedRoutingService. + + Policy-Based Routing allows GCP customers to specify + flexibile routing policies for Layer 4 traffic traversing + through the connected service. + + 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 = "networkconnectivity.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`. + 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`. + 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 = "networkconnectivity.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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. + 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 ``channel`` 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. + 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. + 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 ``channel`` 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. + 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 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: + self._grpc_channel = type(self).create_channel( + 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 list_policy_based_routes( + self, + ) -> Callable[ + [policy_based_routing.ListPolicyBasedRoutesRequest], + Awaitable[policy_based_routing.ListPolicyBasedRoutesResponse], + ]: + r"""Return a callable for the list policy based routes method over gRPC. + + Lists PolicyBasedRoutes in a given project and + location. + + Returns: + Callable[[~.ListPolicyBasedRoutesRequest], + Awaitable[~.ListPolicyBasedRoutesResponse]]: + 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 "list_policy_based_routes" not in self._stubs: + self._stubs["list_policy_based_routes"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/ListPolicyBasedRoutes", + request_serializer=policy_based_routing.ListPolicyBasedRoutesRequest.serialize, + response_deserializer=policy_based_routing.ListPolicyBasedRoutesResponse.deserialize, + ) + return self._stubs["list_policy_based_routes"] + + @property + def get_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.GetPolicyBasedRouteRequest], + Awaitable[policy_based_routing.PolicyBasedRoute], + ]: + r"""Return a callable for the get policy based route method over gRPC. + + Gets details of a single PolicyBasedRoute. + + Returns: + Callable[[~.GetPolicyBasedRouteRequest], + Awaitable[~.PolicyBasedRoute]]: + 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 "get_policy_based_route" not in self._stubs: + self._stubs["get_policy_based_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/GetPolicyBasedRoute", + request_serializer=policy_based_routing.GetPolicyBasedRouteRequest.serialize, + response_deserializer=policy_based_routing.PolicyBasedRoute.deserialize, + ) + return self._stubs["get_policy_based_route"] + + @property + def create_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.CreatePolicyBasedRouteRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the create policy based route method over gRPC. + + Creates a new PolicyBasedRoute in a given project and + location. + + Returns: + Callable[[~.CreatePolicyBasedRouteRequest], + 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 "create_policy_based_route" not in self._stubs: + self._stubs["create_policy_based_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/CreatePolicyBasedRoute", + request_serializer=policy_based_routing.CreatePolicyBasedRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["create_policy_based_route"] + + @property + def delete_policy_based_route( + self, + ) -> Callable[ + [policy_based_routing.DeletePolicyBasedRouteRequest], + Awaitable[operations_pb2.Operation], + ]: + r"""Return a callable for the delete policy based route method over gRPC. + + Deletes a single PolicyBasedRoute. + + Returns: + Callable[[~.DeletePolicyBasedRouteRequest], + 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 "delete_policy_based_route" not in self._stubs: + self._stubs["delete_policy_based_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.PolicyBasedRoutingService/DeletePolicyBasedRoute", + request_serializer=policy_based_routing.DeletePolicyBasedRouteRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_policy_based_route"] + + def close(self): + return self.grpc_channel.close() + + +__all__ = ("PolicyBasedRoutingServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/networkconnectivity_v1/types/__init__.py b/google/cloud/networkconnectivity_v1/types/__init__.py index 6a23ffe..e8c7de8 100644 --- a/google/cloud/networkconnectivity_v1/types/__init__.py +++ b/google/cloud/networkconnectivity_v1/types/__init__.py @@ -38,6 +38,14 @@ UpdateHubRequest, UpdateSpokeRequest, ) +from .policy_based_routing import ( + CreatePolicyBasedRouteRequest, + DeletePolicyBasedRouteRequest, + GetPolicyBasedRouteRequest, + ListPolicyBasedRoutesRequest, + ListPolicyBasedRoutesResponse, + PolicyBasedRoute, +) __all__ = ( "OperationMetadata", @@ -63,4 +71,10 @@ "UpdateSpokeRequest", "LocationFeature", "State", + "CreatePolicyBasedRouteRequest", + "DeletePolicyBasedRouteRequest", + "GetPolicyBasedRouteRequest", + "ListPolicyBasedRoutesRequest", + "ListPolicyBasedRoutesResponse", + "PolicyBasedRoute", ) diff --git a/google/cloud/networkconnectivity_v1/types/common.py b/google/cloud/networkconnectivity_v1/types/common.py index 66afb9e..bab5daa 100644 --- a/google/cloud/networkconnectivity_v1/types/common.py +++ b/google/cloud/networkconnectivity_v1/types/common.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore @@ -54,33 +56,33 @@ class OperationMetadata(proto.Message): operation. """ - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) - end_time = proto.Field( + end_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - target = proto.Field( + target: str = proto.Field( proto.STRING, number=3, ) - verb = proto.Field( + verb: str = proto.Field( proto.STRING, number=4, ) - status_message = proto.Field( + status_message: str = proto.Field( proto.STRING, number=5, ) - requested_cancellation = proto.Field( + requested_cancellation: bool = proto.Field( proto.BOOL, number=6, ) - api_version = proto.Field( + api_version: str = proto.Field( proto.STRING, number=7, ) diff --git a/google/cloud/networkconnectivity_v1/types/hub.py b/google/cloud/networkconnectivity_v1/types/hub.py index 4c325a5..d6c3fd8 100644 --- a/google/cloud/networkconnectivity_v1/types/hub.py +++ b/google/cloud/networkconnectivity_v1/types/hub.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore @@ -20,8 +22,8 @@ __protobuf__ = proto.module( package="google.cloud.networkconnectivity.v1", manifest={ - "State", "LocationFeature", + "State", "Hub", "RoutingVPC", "Spoke", @@ -46,6 +48,13 @@ ) +class LocationFeature(proto.Enum): + r"""Supported features for a location""" + LOCATION_FEATURE_UNSPECIFIED = 0 + SITE_TO_CLOUD_SPOKES = 1 + SITE_TO_SITE_SPOKES = 2 + + class State(proto.Enum): r"""The State enum represents the lifecycle stage of a Network Connectivity Center resource. @@ -54,22 +63,16 @@ class State(proto.Enum): CREATING = 1 ACTIVE = 2 DELETING = 3 - - -class LocationFeature(proto.Enum): - r"""Supported features for a location""" - LOCATION_FEATURE_UNSPECIFIED = 0 - SITE_TO_CLOUD_SPOKES = 1 - SITE_TO_SITE_SPOKES = 2 + UPDATING = 6 class Hub(proto.Message): - r"""A hub is a collection of spokes. A single hub can contain - spokes from multiple regions. However, if any of a hub's spokes - use the data transfer feature, the resources associated with - those spokes must all reside in the same VPC network. Spokes - that do not use data transfer can be associated with any VPC - network in your project. + r"""A Network Connectivity Center hub is a collection of spokes. + A single hub can contain spokes from multiple regions. However, + if any of a hub's spokes use the data transfer feature, the + resources associated with those spokes must all reside in the + same VPC network. Spokes that do not use data transfer can be + associated with any VPC network in your project. Attributes: name (str): @@ -81,7 +84,7 @@ class Hub(proto.Message): update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time the hub was last updated. - labels (Mapping[str, str]): + labels (MutableMapping[str, str]): Optional labels in key:value format. For more information about labels, see `Requirements for labels `__. @@ -95,7 +98,7 @@ class Hub(proto.Message): state (google.cloud.networkconnectivity_v1.types.State): Output only. The current lifecycle state of this hub. - routing_vpcs (Sequence[google.cloud.networkconnectivity_v1.types.RoutingVPC]): + routing_vpcs (MutableSequence[google.cloud.networkconnectivity_v1.types.RoutingVPC]): The VPC networks associated with this hub's spokes. This field is read-only. Network Connectivity @@ -103,39 +106,39 @@ class Hub(proto.Message): set of spokes attached to the hub. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - labels = proto.MapField( + labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=4, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=5, ) - unique_id = proto.Field( + unique_id: str = proto.Field( proto.STRING, number=8, ) - state = proto.Field( + state: "State" = proto.Field( proto.ENUM, number=9, enum="State", ) - routing_vpcs = proto.RepeatedField( + routing_vpcs: MutableSequence["RoutingVPC"] = proto.RepeatedField( proto.MESSAGE, number=10, message="RoutingVPC", @@ -143,8 +146,8 @@ class Hub(proto.Message): class RoutingVPC(proto.Message): - r"""RoutingVPC contains information about the VPC networks that - are associated with a hub's spokes. + r"""RoutingVPC contains information about the VPC networks + associated with the spokes of a Network Connectivity Center hub. Attributes: uri (str): @@ -158,19 +161,19 @@ class RoutingVPC(proto.Message): most, one VPC network will have this field set to true. """ - uri = proto.Field( + uri: str = proto.Field( proto.STRING, number=1, ) - required_for_new_site_to_site_data_transfer_spokes = proto.Field( + required_for_new_site_to_site_data_transfer_spokes: bool = proto.Field( proto.BOOL, number=2, ) class Spoke(proto.Message): - r"""A spoke represents a connection between your Google Cloud network - resources and a non-Google-Cloud network. + r"""A Network Connectivity Center spoke represents a connection between + your Google Cloud network resources and a non-Google-Cloud network. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the following fields: @@ -189,7 +192,7 @@ class Spoke(proto.Message): update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The time the spoke was last updated. - labels (Mapping[str, str]): + labels (MutableMapping[str, str]): Optional labels in key:value format. For more information about labels, see `Requirements for labels `__. @@ -217,53 +220,53 @@ class Spoke(proto.Message): this spoke. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - labels = proto.MapField( + labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=4, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=5, ) - hub = proto.Field( + hub: str = proto.Field( proto.STRING, number=6, ) - linked_vpn_tunnels = proto.Field( + linked_vpn_tunnels: "LinkedVpnTunnels" = proto.Field( proto.MESSAGE, number=17, message="LinkedVpnTunnels", ) - linked_interconnect_attachments = proto.Field( + linked_interconnect_attachments: "LinkedInterconnectAttachments" = proto.Field( proto.MESSAGE, number=18, message="LinkedInterconnectAttachments", ) - linked_router_appliance_instances = proto.Field( + linked_router_appliance_instances: "LinkedRouterApplianceInstances" = proto.Field( proto.MESSAGE, number=19, message="LinkedRouterApplianceInstances", ) - unique_id = proto.Field( + unique_id: str = proto.Field( proto.STRING, number=11, ) - state = proto.Field( + state: "State" = proto.Field( proto.ENUM, number=15, enum="State", @@ -290,23 +293,23 @@ class ListHubsRequest(proto.Message): Sort the results by a certain order. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=4, ) - order_by = proto.Field( + order_by: str = proto.Field( proto.STRING, number=5, ) @@ -318,13 +321,13 @@ class ListHubsResponse(proto.Message): method. Attributes: - hubs (Sequence[google.cloud.networkconnectivity_v1.types.Hub]): + hubs (MutableSequence[google.cloud.networkconnectivity_v1.types.Hub]): The requested hubs. next_page_token (str): The next pagination token in the List response. It should be used as page_token for the following request. An empty value means no more result. - unreachable (Sequence[str]): + unreachable (MutableSequence[str]): Locations that could not be reached. """ @@ -332,16 +335,16 @@ class ListHubsResponse(proto.Message): def raw_page(self): return self - hubs = proto.RepeatedField( + hubs: MutableSequence["Hub"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Hub", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) - unreachable = proto.RepeatedField( + unreachable: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, ) @@ -358,7 +361,7 @@ class GetHubRequest(proto.Message): get. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -398,20 +401,20 @@ class CreateHubRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - hub_id = proto.Field( + hub_id: str = proto.Field( proto.STRING, number=2, ) - hub = proto.Field( + hub: "Hub" = proto.Field( proto.MESSAGE, number=3, message="Hub", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=4, ) @@ -455,17 +458,17 @@ class UpdateHubRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=1, message=field_mask_pb2.FieldMask, ) - hub = proto.Field( + hub: "Hub" = proto.Field( proto.MESSAGE, number=2, message="Hub", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=3, ) @@ -500,11 +503,11 @@ class DeleteHubRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=2, ) @@ -529,23 +532,23 @@ class ListSpokesRequest(proto.Message): Sort the results by a certain order. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=4, ) - order_by = proto.Field( + order_by: str = proto.Field( proto.STRING, number=5, ) @@ -556,13 +559,13 @@ class ListSpokesResponse(proto.Message): [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. Attributes: - spokes (Sequence[google.cloud.networkconnectivity_v1.types.Spoke]): + spokes (MutableSequence[google.cloud.networkconnectivity_v1.types.Spoke]): The requested spokes. next_page_token (str): The next pagination token in the List response. It should be used as page_token for the following request. An empty value means no more result. - unreachable (Sequence[str]): + unreachable (MutableSequence[str]): Locations that could not be reached. """ @@ -570,16 +573,16 @@ class ListSpokesResponse(proto.Message): def raw_page(self): return self - spokes = proto.RepeatedField( + spokes: MutableSequence["Spoke"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Spoke", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) - unreachable = proto.RepeatedField( + unreachable: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, ) @@ -594,7 +597,7 @@ class GetSpokeRequest(proto.Message): Required. The name of the spoke resource. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -633,20 +636,20 @@ class CreateSpokeRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - spoke_id = proto.Field( + spoke_id: str = proto.Field( proto.STRING, number=2, ) - spoke = proto.Field( + spoke: "Spoke" = proto.Field( proto.MESSAGE, number=3, message="Spoke", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=4, ) @@ -690,17 +693,17 @@ class UpdateSpokeRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=1, message=field_mask_pb2.FieldMask, ) - spoke = proto.Field( + spoke: "Spoke" = proto.Field( proto.MESSAGE, number=2, message="Spoke", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=3, ) @@ -735,11 +738,11 @@ class DeleteSpokeRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=2, ) @@ -753,23 +756,30 @@ class LinkedVpnTunnels(proto.Message): same prefixes. Attributes: - uris (Sequence[str]): + uris (MutableSequence[str]): The URIs of linked VPN tunnel resources. site_to_site_data_transfer (bool): A value that controls whether site-to-site data transfer is enabled for these resources. Data transfer is available only in `supported locations `__. + vpc_network (str): + Output only. The VPC network where these VPN + tunnels are located. """ - uris = proto.RepeatedField( + uris: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - site_to_site_data_transfer = proto.Field( + site_to_site_data_transfer: bool = proto.Field( proto.BOOL, number=2, ) + vpc_network: str = proto.Field( + proto.STRING, + number=3, + ) class LinkedInterconnectAttachments(proto.Message): @@ -780,7 +790,7 @@ class LinkedInterconnectAttachments(proto.Message): the same prefixes. Attributes: - uris (Sequence[str]): + uris (MutableSequence[str]): The URIs of linked interconnect attachment resources site_to_site_data_transfer (bool): @@ -788,16 +798,23 @@ class LinkedInterconnectAttachments(proto.Message): enabled for these resources. Data transfer is available only in `supported locations `__. + vpc_network (str): + Output only. The VPC network where these VLAN + attachments are located. """ - uris = proto.RepeatedField( + uris: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=1, ) - site_to_site_data_transfer = proto.Field( + site_to_site_data_transfer: bool = proto.Field( proto.BOOL, number=2, ) + vpc_network: str = proto.Field( + proto.STRING, + number=3, + ) class LinkedRouterApplianceInstances(proto.Message): @@ -807,24 +824,31 @@ class LinkedRouterApplianceInstances(proto.Message): associate those instances with the same spoke. Attributes: - instances (Sequence[google.cloud.networkconnectivity_v1.types.RouterApplianceInstance]): + instances (MutableSequence[google.cloud.networkconnectivity_v1.types.RouterApplianceInstance]): The list of router appliance instances. site_to_site_data_transfer (bool): A value that controls whether site-to-site data transfer is enabled for these resources. Data transfer is available only in `supported locations `__. + vpc_network (str): + Output only. The VPC network where these + router appliance instances are located. """ - instances = proto.RepeatedField( + instances: MutableSequence["RouterApplianceInstance"] = proto.RepeatedField( proto.MESSAGE, number=1, message="RouterApplianceInstance", ) - site_to_site_data_transfer = proto.Field( + site_to_site_data_transfer: bool = proto.Field( proto.BOOL, number=2, ) + vpc_network: str = proto.Field( + proto.STRING, + number=3, + ) class RouterApplianceInstance(proto.Message): @@ -840,11 +864,11 @@ class RouterApplianceInstance(proto.Message): The IP address on the VM to use for peering. """ - virtual_machine = proto.Field( + virtual_machine: str = proto.Field( proto.STRING, number=1, ) - ip_address = proto.Field( + ip_address: str = proto.Field( proto.STRING, number=3, ) @@ -854,11 +878,11 @@ class LocationMetadata(proto.Message): r"""Metadata about locations Attributes: - location_features (Sequence[google.cloud.networkconnectivity_v1.types.LocationFeature]): + location_features (MutableSequence[google.cloud.networkconnectivity_v1.types.LocationFeature]): List of supported features """ - location_features = proto.RepeatedField( + location_features: MutableSequence["LocationFeature"] = proto.RepeatedField( proto.ENUM, number=1, enum="LocationFeature", diff --git a/google/cloud/networkconnectivity_v1/types/policy_based_routing.py b/google/cloud/networkconnectivity_v1/types/policy_based_routing.py new file mode 100644 index 0000000..5220e43 --- /dev/null +++ b/google/cloud/networkconnectivity_v1/types/policy_based_routing.py @@ -0,0 +1,476 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from typing import MutableMapping, MutableSequence + +from google.protobuf import timestamp_pb2 # type: ignore +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.networkconnectivity.v1", + manifest={ + "PolicyBasedRoute", + "ListPolicyBasedRoutesRequest", + "ListPolicyBasedRoutesResponse", + "GetPolicyBasedRouteRequest", + "CreatePolicyBasedRouteRequest", + "DeletePolicyBasedRouteRequest", + }, +) + + +class PolicyBasedRoute(proto.Message): + r"""Policy Based Routes (PBR) are more powerful routes that + allows GCP customers to route their L4 network traffic based on + not just destination IP, but also source IP, protocol and more. + A PBR always take precedence when it conflicts with other types + of routes. + Next id: 19 + + 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: + virtual_machine (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute.VirtualMachine): + Optional. VM instances to which this policy + based route applies to. + + This field is a member of `oneof`_ ``target``. + interconnect_attachment (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute.InterconnectAttachment): + Optional. The interconnect attachments to + which this route applies to. + + This field is a member of `oneof`_ ``target``. + next_hop_ilb_ip (str): + Optional. The IP of a global access enabled L4 ILB that + should be the next hop to handle matching packets. For this + version, only next_hop_ilb_ip is supported. + + This field is a member of `oneof`_ ``next_hop``. + name (str): + Immutable. A unique name of the resource in the form of + ``projects/{project_number}/locations/global/PolicyBasedRoutes/{policy_based_route_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the PolicyBasedRoute + was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Time when the PolicyBasedRoute + was updated. + labels (MutableMapping[str, str]): + User-defined labels. + description (str): + Optional. An optional description of this + resource. Provide this field when you create the + resource. + network (str): + Required. Fully-qualified URL of the network + that this route applies to. e.g. + projects/my-project/global/networks/my-network. + filter (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute.Filter): + Required. The filter to match L4 traffic. + priority (int): + Optional. The priority of this policy based + route. Priority is used to break ties in cases + where there are more than one matching policy + based routes found. In cases where multiple + policy based routes are matched, the one with + the lowest-numbered priority value wins. The + default value is 1000. The priority value must + be from 1 to 65535, inclusive. + warnings (MutableSequence[google.cloud.networkconnectivity_v1.types.PolicyBasedRoute.Warnings]): + Output only. If potential misconfigurations + are detected for this route, this field will be + populated with warning messages. + self_link (str): + Output only. Server-defined fully-qualified + URL for this resource. + kind (str): + Output only. Type of this resource. Always + networkconnectivity#policyBasedRoute for Policy + Based Route resources. + """ + + class VirtualMachine(proto.Message): + r"""VM instances to which this policy based route applies to. + + Attributes: + tags (MutableSequence[str]): + Optional. A list of VM instance tags to which + this policy based route applies to. VM instances + that have ANY of tags specified here will + install this PBR. + """ + + tags: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class InterconnectAttachment(proto.Message): + r"""InterconnectAttachment to which this route applies to. + + Attributes: + region (str): + Optional. Cloud region to install this policy based route on + interconnect attachment. Use ``all`` to install it on all + interconnect attachments. + """ + + region: str = proto.Field( + proto.STRING, + number=1, + ) + + class Filter(proto.Message): + r"""Filter matches L4 traffic. + + Attributes: + ip_protocol (str): + Optional. The IP protocol that this policy + based route applies to. Valid values are 'TCP', + 'UDP', and 'ALL'. Default is 'ALL'. + src_range (str): + Optional. The source IP range of outgoing + packets that this policy based route applies to. + Default is "0.0.0.0/0" if protocol version is + IPv4. + dest_range (str): + Optional. The destination IP range of + outgoing packets that this policy based route + applies to. Default is "0.0.0.0/0" if protocol + version is IPv4. + protocol_version (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute.Filter.ProtocolVersion): + Required. Internet protocol versions this + policy based route applies to. For this version, + only IPV4 is supported. + """ + + class ProtocolVersion(proto.Enum): + r"""The internet protocol version.""" + PROTOCOL_VERSION_UNSPECIFIED = 0 + IPV4 = 1 + + ip_protocol: str = proto.Field( + proto.STRING, + number=1, + ) + src_range: str = proto.Field( + proto.STRING, + number=2, + ) + dest_range: str = proto.Field( + proto.STRING, + number=3, + ) + protocol_version: "PolicyBasedRoute.Filter.ProtocolVersion" = proto.Field( + proto.ENUM, + number=6, + enum="PolicyBasedRoute.Filter.ProtocolVersion", + ) + + class Warnings(proto.Message): + r"""Informational warning message. + + Attributes: + code (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute.Warnings.Code): + Output only. A warning code, if applicable. + data (MutableMapping[str, str]): + Output only. Metadata about this warning in + key: value format. The key should provides more + detail on the warning being returned. For + example, for warnings where there are no results + in a list request for a particular zone, this + key might be scope and the key value might be + the zone name. Other examples might be a key + indicating a deprecated resource and a suggested + replacement. + warning_message (str): + Output only. A human-readable description of + the warning code. + """ + + class Code(proto.Enum): + r"""Warning code for Policy Based Routing. Expect to add values + in the future. + """ + WARNING_UNSPECIFIED = 0 + RESOURCE_NOT_ACTIVE = 1 + RESOURCE_BEING_MODIFIED = 2 + + code: "PolicyBasedRoute.Warnings.Code" = proto.Field( + proto.ENUM, + number=1, + enum="PolicyBasedRoute.Warnings.Code", + ) + data: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=2, + ) + warning_message: str = proto.Field( + proto.STRING, + number=3, + ) + + virtual_machine: VirtualMachine = proto.Field( + proto.MESSAGE, + number=18, + oneof="target", + message=VirtualMachine, + ) + interconnect_attachment: InterconnectAttachment = proto.Field( + proto.MESSAGE, + number=9, + oneof="target", + message=InterconnectAttachment, + ) + next_hop_ilb_ip: str = proto.Field( + proto.STRING, + number=12, + oneof="next_hop", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + network: str = proto.Field( + proto.STRING, + number=6, + ) + filter: Filter = proto.Field( + proto.MESSAGE, + number=10, + message=Filter, + ) + priority: int = proto.Field( + proto.INT32, + number=11, + ) + warnings: MutableSequence[Warnings] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message=Warnings, + ) + self_link: str = proto.Field( + proto.STRING, + number=15, + ) + kind: str = proto.Field( + proto.STRING, + number=16, + ) + + +class ListPolicyBasedRoutesRequest(proto.Message): + r"""Request for [PolicyBasedRouting.ListPolicyBasedRoutes][] method. + + Attributes: + parent (str): + Required. The parent resource's name. + page_size (int): + The maximum number of results per page that + should be returned. + page_token (str): + The page token. + filter (str): + A filter expression that filters the results + listed in the response. + order_by (str): + Sort the results by a certain order. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListPolicyBasedRoutesResponse(proto.Message): + r"""Response for [PolicyBasedRouting.ListPolicyBasedRoutes][] method. + + Attributes: + policy_based_routes (MutableSequence[google.cloud.networkconnectivity_v1.types.PolicyBasedRoute]): + Policy based routes to be returned. + next_page_token (str): + The next pagination token in the List response. It should be + used as page_token for the following request. An empty value + means no more result. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + policy_based_routes: MutableSequence["PolicyBasedRoute"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="PolicyBasedRoute", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetPolicyBasedRouteRequest(proto.Message): + r"""Request for [PolicyBasedRouting.GetPolicyBasedRoute][] method. + + Attributes: + name (str): + Required. Name of the PolicyBasedRoute + resource to get. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreatePolicyBasedRouteRequest(proto.Message): + r"""Request for [PolicyBasedRouting.CreatePolicyBasedRoute][] method. + + Attributes: + parent (str): + Required. The parent resource's name of the + PolicyBasedRoute. + policy_based_route_id (str): + Optional. Unique id for the Policy Based + Route to create. + policy_based_route (google.cloud.networkconnectivity_v1.types.PolicyBasedRoute): + Required. Initial values for a new Policy + Based Route. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + policy_based_route_id: str = proto.Field( + proto.STRING, + number=2, + ) + policy_based_route: "PolicyBasedRoute" = proto.Field( + proto.MESSAGE, + number=3, + message="PolicyBasedRoute", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class DeletePolicyBasedRouteRequest(proto.Message): + r"""Request for [PolicyBasedRouting.DeletePolicyBasedRoute][] method. + + Attributes: + name (str): + Required. Name of the PolicyBasedRoute + resource to delete. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + For example, consider a situation where you make + an initial request and t he request times out. + If you make the request again with the same + request ID, the server can check if original + operation with the same request ID was received, + and if so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/networkconnectivity_v1alpha1/__init__.py b/google/cloud/networkconnectivity_v1alpha1/__init__.py index aed8930..2eefb37 100644 --- a/google/cloud/networkconnectivity_v1alpha1/__init__.py +++ b/google/cloud/networkconnectivity_v1alpha1/__init__.py @@ -13,6 +13,10 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from google.cloud.networkconnectivity import gapic_version as package_version + +__version__ = package_version.__version__ + from .services.hub_service import HubServiceAsyncClient, HubServiceClient from .types.common import OperationMetadata diff --git a/google/cloud/networkconnectivity_v1alpha1/gapic_version.py b/google/cloud/networkconnectivity_v1alpha1/gapic_version.py new file mode 100644 index 0000000..25e4dd6 --- /dev/null +++ b/google/cloud/networkconnectivity_v1alpha1/gapic_version.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +__version__ = "1.4.4" # {x-release-please-version} diff --git a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/async_client.py b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/async_client.py index f190e44..c5a7bec 100644 --- a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/async_client.py +++ b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/async_client.py @@ -16,7 +16,17 @@ from collections import OrderedDict import functools import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + 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 @@ -24,7 +34,8 @@ 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 -import pkg_resources + +from google.cloud.networkconnectivity_v1alpha1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -177,9 +188,9 @@ def transport(self) -> HubServiceTransport: def __init__( self, *, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, transport: Union[str, HubServiceTransport] = "grpc_asyncio", - client_options: ClientOptions = None, + client_options: Optional[ClientOptions] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the hub service client. @@ -223,11 +234,11 @@ def __init__( async def list_hubs( self, - request: Union[hub.ListHubsRequest, dict] = None, + request: Optional[Union[hub.ListHubsRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListHubsAsyncPager: r"""Lists Hubs in a given project and location. @@ -260,7 +271,7 @@ async def sample_list_hubs(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.ListHubsRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.ListHubsRequest, dict]]): The request object. Request for [HubService.ListHubs][google.cloud.networkconnectivity.v1alpha1.HubService.ListHubs] method. @@ -338,11 +349,11 @@ async def sample_list_hubs(): async def get_hub( self, - request: Union[hub.GetHubRequest, dict] = None, + request: Optional[Union[hub.GetHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Hub: r"""Gets details of a single Hub. @@ -374,7 +385,7 @@ async def sample_get_hub(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.GetHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.GetHubRequest, dict]]): The request object. Request for [HubService.GetHub][google.cloud.networkconnectivity.v1alpha1.HubService.GetHub] method. @@ -446,13 +457,13 @@ async def sample_get_hub(): async def create_hub( self, - request: Union[gcn_hub.CreateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.CreateHubRequest, dict]] = None, *, - parent: str = None, - hub: gcn_hub.Hub = None, - hub_id: str = None, + parent: Optional[str] = None, + hub: Optional[gcn_hub.Hub] = None, + hub_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new Hub in a given project and location. @@ -482,13 +493,13 @@ async def sample_create_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.CreateHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.CreateHubRequest, dict]]): The request object. Request for [HubService.CreateHub][google.cloud.networkconnectivity.v1alpha1.HubService.CreateHub] method. @@ -586,12 +597,12 @@ async def sample_create_hub(): async def update_hub( self, - request: Union[gcn_hub.UpdateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.UpdateHubRequest, dict]] = None, *, - hub: gcn_hub.Hub = None, - update_mask: field_mask_pb2.FieldMask = None, + hub: Optional[gcn_hub.Hub] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Updates the parameters of a single Hub. @@ -620,13 +631,13 @@ async def sample_update_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.UpdateHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.UpdateHubRequest, dict]]): The request object. Request for [HubService.UpdateHub][google.cloud.networkconnectivity.v1alpha1.HubService.UpdateHub] method. @@ -719,11 +730,11 @@ async def sample_update_hub(): async def delete_hub( self, - request: Union[hub.DeleteHubRequest, dict] = None, + request: Optional[Union[hub.DeleteHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Deletes a single Hub. @@ -753,13 +764,13 @@ async def sample_delete_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.DeleteHubRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.DeleteHubRequest, dict]]): The request object. The request for [HubService.DeleteHub][google.cloud.networkconnectivity.v1alpha1.HubService.DeleteHub]. name (:class:`str`): @@ -843,11 +854,11 @@ async def sample_delete_hub(): async def list_spokes( self, - request: Union[hub.ListSpokesRequest, dict] = None, + request: Optional[Union[hub.ListSpokesRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSpokesAsyncPager: r"""Lists Spokes in a given project and location. @@ -880,7 +891,7 @@ async def sample_list_spokes(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.ListSpokesRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.ListSpokesRequest, dict]]): The request object. The request for [HubService.ListSpokes][google.cloud.networkconnectivity.v1alpha1.HubService.ListSpokes]. parent (:class:`str`): @@ -956,11 +967,11 @@ async def sample_list_spokes(): async def get_spoke( self, - request: Union[hub.GetSpokeRequest, dict] = None, + request: Optional[Union[hub.GetSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Spoke: r"""Gets details of a single Spoke. @@ -992,7 +1003,7 @@ async def sample_get_spoke(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.GetSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.GetSpokeRequest, dict]]): The request object. The request for [HubService.GetSpoke][google.cloud.networkconnectivity.v1alpha1.HubService.GetSpoke]. name (:class:`str`): @@ -1059,13 +1070,13 @@ async def sample_get_spoke(): async def create_spoke( self, - request: Union[hub.CreateSpokeRequest, dict] = None, + request: Optional[Union[hub.CreateSpokeRequest, dict]] = None, *, - parent: str = None, - spoke: hub.Spoke = None, - spoke_id: str = None, + parent: Optional[str] = None, + spoke: Optional[hub.Spoke] = None, + spoke_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Creates a new Spoke in a given project and location. @@ -1095,13 +1106,13 @@ async def sample_create_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.CreateSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.CreateSpokeRequest, dict]]): The request object. The request for [HubService.CreateSpoke][google.cloud.networkconnectivity.v1alpha1.HubService.CreateSpoke]. parent (:class:`str`): @@ -1197,12 +1208,12 @@ async def sample_create_spoke(): async def update_spoke( self, - request: Union[hub.UpdateSpokeRequest, dict] = None, + request: Optional[Union[hub.UpdateSpokeRequest, dict]] = None, *, - spoke: hub.Spoke = None, - update_mask: field_mask_pb2.FieldMask = None, + spoke: Optional[hub.Spoke] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Updates the parameters of a single Spoke. @@ -1231,13 +1242,13 @@ async def sample_update_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.UpdateSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.UpdateSpokeRequest, dict]]): The request object. Request for [HubService.UpdateSpoke][google.cloud.networkconnectivity.v1alpha1.HubService.UpdateSpoke] method. @@ -1331,11 +1342,11 @@ async def sample_update_spoke(): async def delete_spoke( self, - request: Union[hub.DeleteSpokeRequest, dict] = None, + request: Optional[Union[hub.DeleteSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation_async.AsyncOperation: r"""Deletes a single Spoke. @@ -1365,13 +1376,13 @@ async def sample_delete_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) Args: - request (Union[google.cloud.networkconnectivity_v1alpha1.types.DeleteSpokeRequest, dict]): + request (Optional[Union[google.cloud.networkconnectivity_v1alpha1.types.DeleteSpokeRequest, dict]]): The request object. The request for [HubService.DeleteSpoke][google.cloud.networkconnectivity.v1alpha1.HubService.DeleteSpoke]. name (:class:`str`): @@ -1460,14 +1471,9 @@ async def __aexit__(self, exc_type, exc, tb): await self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-network-connectivity", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("HubServiceAsyncClient",) diff --git a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/client.py b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/client.py index 5590869..48c0981 100644 --- a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/client.py +++ b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/client.py @@ -16,7 +16,18 @@ from collections import OrderedDict import os import re -from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union +from typing import ( + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) from google.api_core import client_options as client_options_lib from google.api_core import exceptions as core_exceptions @@ -27,7 +38,8 @@ 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 -import pkg_resources + +from google.cloud.networkconnectivity_v1alpha1 import gapic_version as package_version try: OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault] @@ -64,7 +76,7 @@ class HubServiceClientMeta(type): def get_transport_class( cls, - label: str = None, + label: Optional[str] = None, ) -> Type[HubServiceTransport]: """Returns an appropriate transport class. @@ -428,8 +440,8 @@ def __init__( self, *, credentials: Optional[ga_credentials.Credentials] = None, - transport: Union[str, HubServiceTransport, None] = None, - client_options: Optional[client_options_lib.ClientOptions] = None, + transport: Optional[Union[str, HubServiceTransport]] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiates the hub service client. @@ -443,7 +455,7 @@ def __init__( transport (Union[str, HubServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (google.api_core.client_options.ClientOptions): Custom options for the + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT @@ -473,6 +485,7 @@ def __init__( client_options = client_options_lib.from_dict(client_options) if client_options is None: client_options = client_options_lib.ClientOptions() + client_options = cast(client_options_lib.ClientOptions, client_options) api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( client_options @@ -525,11 +538,11 @@ def __init__( def list_hubs( self, - request: Union[hub.ListHubsRequest, dict] = None, + request: Optional[Union[hub.ListHubsRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListHubsPager: r"""Lists Hubs in a given project and location. @@ -640,11 +653,11 @@ def sample_list_hubs(): def get_hub( self, - request: Union[hub.GetHubRequest, dict] = None, + request: Optional[Union[hub.GetHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Hub: r"""Gets details of a single Hub. @@ -748,13 +761,13 @@ def sample_get_hub(): def create_hub( self, - request: Union[gcn_hub.CreateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.CreateHubRequest, dict]] = None, *, - parent: str = None, - hub: gcn_hub.Hub = None, - hub_id: str = None, + parent: Optional[str] = None, + hub: Optional[gcn_hub.Hub] = None, + hub_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Creates a new Hub in a given project and location. @@ -888,12 +901,12 @@ def sample_create_hub(): def update_hub( self, - request: Union[gcn_hub.UpdateHubRequest, dict] = None, + request: Optional[Union[gcn_hub.UpdateHubRequest, dict]] = None, *, - hub: gcn_hub.Hub = None, - update_mask: field_mask_pb2.FieldMask = None, + hub: Optional[gcn_hub.Hub] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Updates the parameters of a single Hub. @@ -1021,11 +1034,11 @@ def sample_update_hub(): def delete_hub( self, - request: Union[hub.DeleteHubRequest, dict] = None, + request: Optional[Union[hub.DeleteHubRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Deletes a single Hub. @@ -1145,11 +1158,11 @@ def sample_delete_hub(): def list_spokes( self, - request: Union[hub.ListSpokesRequest, dict] = None, + request: Optional[Union[hub.ListSpokesRequest, dict]] = None, *, - parent: str = None, + parent: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> pagers.ListSpokesPager: r"""Lists Spokes in a given project and location. @@ -1258,11 +1271,11 @@ def sample_list_spokes(): def get_spoke( self, - request: Union[hub.GetSpokeRequest, dict] = None, + request: Optional[Union[hub.GetSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> hub.Spoke: r"""Gets details of a single Spoke. @@ -1361,13 +1374,13 @@ def sample_get_spoke(): def create_spoke( self, - request: Union[hub.CreateSpokeRequest, dict] = None, + request: Optional[Union[hub.CreateSpokeRequest, dict]] = None, *, - parent: str = None, - spoke: hub.Spoke = None, - spoke_id: str = None, + parent: Optional[str] = None, + spoke: Optional[hub.Spoke] = None, + spoke_id: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Creates a new Spoke in a given project and location. @@ -1499,12 +1512,12 @@ def sample_create_spoke(): def update_spoke( self, - request: Union[hub.UpdateSpokeRequest, dict] = None, + request: Optional[Union[hub.UpdateSpokeRequest, dict]] = None, *, - spoke: hub.Spoke = None, - update_mask: field_mask_pb2.FieldMask = None, + spoke: Optional[hub.Spoke] = None, + update_mask: Optional[field_mask_pb2.FieldMask] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Updates the parameters of a single Spoke. @@ -1633,11 +1646,11 @@ def sample_update_spoke(): def delete_spoke( self, - request: Union[hub.DeleteSpokeRequest, dict] = None, + request: Optional[Union[hub.DeleteSpokeRequest, dict]] = None, *, - name: str = None, + name: Optional[str] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, - timeout: float = None, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, str]] = (), ) -> operation.Operation: r"""Deletes a single Spoke. @@ -1769,14 +1782,9 @@ def __exit__(self, type, value, traceback): self.transport.close() -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-network-connectivity", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) __all__ = ("HubServiceClient",) diff --git a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/base.py b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/base.py index 26030f3..1f3cd98 100644 --- a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/base.py +++ b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/base.py @@ -24,19 +24,14 @@ 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 -import pkg_resources +from google.cloud.networkconnectivity_v1alpha1 import gapic_version as package_version from google.cloud.networkconnectivity_v1alpha1.types import hub from google.cloud.networkconnectivity_v1alpha1.types import hub as gcn_hub -try: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-network-connectivity", - ).version, - ) -except pkg_resources.DistributionNotFound: - DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) class HubServiceTransport(abc.ABC): @@ -50,7 +45,7 @@ def __init__( self, *, host: str = DEFAULT_HOST, - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, diff --git a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc.py b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc.py index 9682315..6517192 100644 --- a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc.py +++ b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc.py @@ -51,14 +51,14 @@ def __init__( self, *, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: Optional[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, @@ -186,8 +186,8 @@ def __init__( def create_channel( cls, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, - credentials_file: str = None, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, **kwargs, diff --git a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc_asyncio.py b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc_asyncio.py index b7dc8a6..9483c6c 100644 --- a/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc_asyncio.py +++ b/google/cloud/networkconnectivity_v1alpha1/services/hub_service/transports/grpc_asyncio.py @@ -53,7 +53,7 @@ class HubServiceGrpcAsyncIOTransport(HubServiceTransport): def create_channel( cls, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, quota_project_id: Optional[str] = None, @@ -96,15 +96,15 @@ def __init__( self, *, host: str = "networkconnectivity.googleapis.com", - credentials: ga_credentials.Credentials = None, + credentials: Optional[ga_credentials.Credentials] = None, credentials_file: Optional[str] = None, scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - ssl_channel_credentials: grpc.ChannelCredentials = None, - client_cert_source_for_mtls: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, + channel: Optional[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, diff --git a/google/cloud/networkconnectivity_v1alpha1/types/common.py b/google/cloud/networkconnectivity_v1alpha1/types/common.py index e991449..d937fb2 100644 --- a/google/cloud/networkconnectivity_v1alpha1/types/common.py +++ b/google/cloud/networkconnectivity_v1alpha1/types/common.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore @@ -54,33 +56,33 @@ class OperationMetadata(proto.Message): operation. """ - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) - end_time = proto.Field( + end_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - target = proto.Field( + target: str = proto.Field( proto.STRING, number=3, ) - verb = proto.Field( + verb: str = proto.Field( proto.STRING, number=4, ) - status_message = proto.Field( + status_message: str = proto.Field( proto.STRING, number=5, ) - requested_cancellation = proto.Field( + requested_cancellation: bool = proto.Field( proto.BOOL, number=6, ) - api_version = proto.Field( + api_version: str = proto.Field( proto.STRING, number=7, ) diff --git a/google/cloud/networkconnectivity_v1alpha1/types/hub.py b/google/cloud/networkconnectivity_v1alpha1/types/hub.py index fea64dc..ccc3e69 100644 --- a/google/cloud/networkconnectivity_v1alpha1/types/hub.py +++ b/google/cloud/networkconnectivity_v1alpha1/types/hub.py @@ -13,6 +13,8 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from typing import MutableMapping, MutableSequence + from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import proto # type: ignore @@ -64,11 +66,11 @@ class Hub(proto.Message): Time when the Hub was created. update_time (google.protobuf.timestamp_pb2.Timestamp): Time when the Hub was updated. - labels (Mapping[str, str]): + labels (MutableMapping[str, str]): User-defined labels. description (str): Short description of the hub resource. - spokes (Sequence[str]): + spokes (MutableSequence[str]): Output only. A list of the URIs of all attached spokes unique_id (str): @@ -81,38 +83,38 @@ class Hub(proto.Message): this Hub. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - labels = proto.MapField( + labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=4, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=5, ) - spokes = proto.RepeatedField( + spokes: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=6, ) - unique_id = proto.Field( + unique_id: str = proto.Field( proto.STRING, number=8, ) - state = proto.Field( + state: "State" = proto.Field( proto.ENUM, number=9, enum="State", @@ -131,19 +133,19 @@ class Spoke(proto.Message): The time when the Spoke was created. update_time (google.protobuf.timestamp_pb2.Timestamp): The time when the Spoke was updated. - labels (Mapping[str, str]): + labels (MutableMapping[str, str]): User-defined labels. description (str): Short description of the spoke resource hub (str): The resource URL of the hub resource that the spoke is attached to - linked_vpn_tunnels (Sequence[str]): + linked_vpn_tunnels (MutableSequence[str]): The URIs of linked VPN tunnel resources - linked_interconnect_attachments (Sequence[str]): + linked_interconnect_attachments (MutableSequence[str]): The URIs of linked interconnect attachment resources - linked_router_appliance_instances (Sequence[google.cloud.networkconnectivity_v1alpha1.types.RouterApplianceInstance]): + linked_router_appliance_instances (MutableSequence[google.cloud.networkconnectivity_v1alpha1.types.RouterApplianceInstance]): The URIs of linked Router appliance resources unique_id (str): Output only. Google-generated UUID for this resource. This @@ -155,51 +157,53 @@ class Spoke(proto.Message): this Hub. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - create_time = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, message=timestamp_pb2.Timestamp, ) - update_time = proto.Field( + update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, message=timestamp_pb2.Timestamp, ) - labels = proto.MapField( + labels: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, number=4, ) - description = proto.Field( + description: str = proto.Field( proto.STRING, number=5, ) - hub = proto.Field( + hub: str = proto.Field( proto.STRING, number=6, ) - linked_vpn_tunnels = proto.RepeatedField( + linked_vpn_tunnels: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=12, ) - linked_interconnect_attachments = proto.RepeatedField( + linked_interconnect_attachments: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=13, ) - linked_router_appliance_instances = proto.RepeatedField( + linked_router_appliance_instances: MutableSequence[ + "RouterApplianceInstance" + ] = proto.RepeatedField( proto.MESSAGE, number=14, message="RouterApplianceInstance", ) - unique_id = proto.Field( + unique_id: str = proto.Field( proto.STRING, number=11, ) - state = proto.Field( + state: "State" = proto.Field( proto.ENUM, number=15, enum="State", @@ -226,23 +230,23 @@ class ListHubsRequest(proto.Message): Sort the results by a certain order. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=4, ) - order_by = proto.Field( + order_by: str = proto.Field( proto.STRING, number=5, ) @@ -254,13 +258,13 @@ class ListHubsResponse(proto.Message): method. Attributes: - hubs (Sequence[google.cloud.networkconnectivity_v1alpha1.types.Hub]): + hubs (MutableSequence[google.cloud.networkconnectivity_v1alpha1.types.Hub]): Hubs to be returned. next_page_token (str): The next pagination token in the List response. It should be used as page_token for the following request. An empty value means no more result. - unreachable (Sequence[str]): + unreachable (MutableSequence[str]): Locations that could not be reached. """ @@ -268,16 +272,16 @@ class ListHubsResponse(proto.Message): def raw_page(self): return self - hubs = proto.RepeatedField( + hubs: MutableSequence["Hub"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Hub", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) - unreachable = proto.RepeatedField( + unreachable: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, ) @@ -293,7 +297,7 @@ class GetHubRequest(proto.Message): Required. Name of the Hub resource to get. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -332,20 +336,20 @@ class CreateHubRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - hub_id = proto.Field( + hub_id: str = proto.Field( proto.STRING, number=2, ) - hub = proto.Field( + hub: "Hub" = proto.Field( proto.MESSAGE, number=3, message="Hub", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=4, ) @@ -387,17 +391,17 @@ class UpdateHubRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=1, message=field_mask_pb2.FieldMask, ) - hub = proto.Field( + hub: "Hub" = proto.Field( proto.MESSAGE, number=2, message="Hub", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=3, ) @@ -430,11 +434,11 @@ class DeleteHubRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=2, ) @@ -459,23 +463,23 @@ class ListSpokesRequest(proto.Message): Sort the results by a certain order. """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - page_size = proto.Field( + page_size: int = proto.Field( proto.INT32, number=2, ) - page_token = proto.Field( + page_token: str = proto.Field( proto.STRING, number=3, ) - filter = proto.Field( + filter: str = proto.Field( proto.STRING, number=4, ) - order_by = proto.Field( + order_by: str = proto.Field( proto.STRING, number=5, ) @@ -486,13 +490,13 @@ class ListSpokesResponse(proto.Message): [HubService.ListSpokes][google.cloud.networkconnectivity.v1alpha1.HubService.ListSpokes]. Attributes: - spokes (Sequence[google.cloud.networkconnectivity_v1alpha1.types.Spoke]): + spokes (MutableSequence[google.cloud.networkconnectivity_v1alpha1.types.Spoke]): Spokes to be returned. next_page_token (str): The next pagination token in the List response. It should be used as page_token for the following request. An empty value means no more result. - unreachable (Sequence[str]): + unreachable (MutableSequence[str]): Locations that could not be reached. """ @@ -500,16 +504,16 @@ class ListSpokesResponse(proto.Message): def raw_page(self): return self - spokes = proto.RepeatedField( + spokes: MutableSequence["Spoke"] = proto.RepeatedField( proto.MESSAGE, number=1, message="Spoke", ) - next_page_token = proto.Field( + next_page_token: str = proto.Field( proto.STRING, number=2, ) - unreachable = proto.RepeatedField( + unreachable: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, ) @@ -524,7 +528,7 @@ class GetSpokeRequest(proto.Message): Required. The name of Spoke resource. """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) @@ -562,20 +566,20 @@ class CreateSpokeRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - parent = proto.Field( + parent: str = proto.Field( proto.STRING, number=1, ) - spoke_id = proto.Field( + spoke_id: str = proto.Field( proto.STRING, number=2, ) - spoke = proto.Field( + spoke: "Spoke" = proto.Field( proto.MESSAGE, number=3, message="Spoke", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=4, ) @@ -617,17 +621,17 @@ class UpdateSpokeRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - update_mask = proto.Field( + update_mask: field_mask_pb2.FieldMask = proto.Field( proto.MESSAGE, number=1, message=field_mask_pb2.FieldMask, ) - spoke = proto.Field( + spoke: "Spoke" = proto.Field( proto.MESSAGE, number=2, message="Spoke", ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=3, ) @@ -660,11 +664,11 @@ class DeleteSpokeRequest(proto.Message): (00000000-0000-0000-0000-000000000000). """ - name = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - request_id = proto.Field( + request_id: str = proto.Field( proto.STRING, number=2, ) @@ -684,15 +688,15 @@ class RouterApplianceInstance(proto.Message): """ - virtual_machine = proto.Field( + virtual_machine: str = proto.Field( proto.STRING, number=1, ) - ip_address = proto.Field( + ip_address: str = proto.Field( proto.STRING, number=3, ) - network_interface = proto.Field( + network_interface: str = proto.Field( proto.STRING, number=2, ) diff --git a/owlbot.py b/owlbot.py new file mode 100644 index 0000000..ce738f0 --- /dev/null +++ b/owlbot.py @@ -0,0 +1,56 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import json +from pathlib import Path +import shutil + +import synthtool as s +import synthtool.gcp as gcp +from synthtool.languages import python + +# ---------------------------------------------------------------------------- +# Copy the generated client from the owl-bot staging directory +# ---------------------------------------------------------------------------- + +clean_up_generated_samples = True + +# Load the default version defined in .repo-metadata.json. +default_version = json.load(open(".repo-metadata.json", "rt")).get( + "default_version" +) + +for library in s.get_staging_dirs(default_version): + if clean_up_generated_samples: + shutil.rmtree("samples/generated_samples", ignore_errors=True) + clean_up_generated_samples = False + s.move([library], excludes=["**/gapic_version.py"]) +s.remove_staging_dirs() + +# ---------------------------------------------------------------------------- +# Add templated files +# ---------------------------------------------------------------------------- + +templated_files = gcp.CommonTemplates().py_library( + cov_level=100, + microgenerator=True, + versions=gcp.common.detect_versions(path="./google", default_first=True), +) +s.move(templated_files, excludes=[".coveragerc", ".github/release-please.yml"]) + +python.py_samples(skip_readmes=True) + +# run format session for all directories which have a noxfile +for noxfile in Path(".").glob("**/noxfile.py"): + s.shell.run(["nox", "-s", "format"], cwd=noxfile.parent, hide_output=False) diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000..96074cb --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", + "packages": { + ".": { + "release-type": "python", + "extra-files": [ + "google/cloud/networkconnectivity_v1alpha1/gapic_version.py", + "google/cloud/networkconnectivity_v1/gapic_version.py", + "google/cloud/networkconnectivity/gapic_version.py", + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json", + "jsonpath": "$.clientLibrary.version" + }, + { + "type": "json", + "path": "samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json", + "jsonpath": "$.clientLibrary.version" + } + ] + } + }, + "release-type": "python", + "plugins": [ + { + "type": "sentence-case" + } + ], + "initial-version": "0.1.0" +} diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_async.py index 6a1d214..e48a196 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_CreateHub_async] @@ -49,7 +49,7 @@ async def sample_create_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_sync.py index 3523a91..4fced0c 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_hub_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_CreateHub_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_async.py index 8a90beb..5ba763c 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_CreateSpoke_async] @@ -49,7 +49,7 @@ async def sample_create_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_sync.py index 3179628..36f5596 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_create_spoke_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_CreateSpoke_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_async.py index 51a1358..200a42a 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_DeleteHub_async] @@ -48,7 +48,7 @@ async def sample_delete_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_sync.py index cc363cf..a5c8696 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_hub_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_DeleteHub_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_async.py index a964fe3..8861d36 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_DeleteSpoke_async] @@ -48,7 +48,7 @@ async def sample_delete_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_sync.py index 83b47ed..75d6710 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_delete_spoke_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_DeleteSpoke_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_async.py index 989750a..a7f2de5 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_GetHub_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_sync.py index 018dd3a..a80e4a3 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_hub_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_GetHub_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_async.py index 1f3388d..c3a219c 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_GetSpoke_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_sync.py index 1e1319e..35f1e12 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_spoke_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_GetSpoke_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_async.py index c128a32..cd0bd3f 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_ListHubs_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_sync.py index 0d02acc..fe46e3c 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hubs_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_ListHubs_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_async.py index c670d1f..09a7d46 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_ListSpokes_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_sync.py index a33118f..d818f9b 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_spokes_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_ListSpokes_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_async.py index 2a94bd0..1ae39d6 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_UpdateHub_async] @@ -47,7 +47,7 @@ async def sample_update_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_sync.py index 6a99dcb..42b32f6 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_hub_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_UpdateHub_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_async.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_async.py index 2cd0fac..5e35352 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_async.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_UpdateSpoke_async] @@ -47,7 +47,7 @@ async def sample_update_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_sync.py index 88aaddf..127ec16 100644 --- a/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_sync.py +++ b/samples/generated_samples/networkconnectivity_v1_generated_hub_service_update_spoke_sync.py @@ -20,7 +20,7 @@ # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: -# python3 -m pip install google-cloud-networkconnectivity +# python3 -m pip install google-cloud-network-connectivity # [START networkconnectivity_v1_generated_HubService_UpdateSpoke_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_async.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_async.py new file mode 100644 index 0000000..e699c74 --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_async.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePolicyBasedRoute +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_CreatePolicyBasedRoute_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.cloud import networkconnectivity_v1 + + +async def sample_create_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + policy_based_route = networkconnectivity_v1.PolicyBasedRoute() + policy_based_route.next_hop_ilb_ip = "next_hop_ilb_ip_value" + policy_based_route.network = "network_value" + policy_based_route.filter.protocol_version = "IPV4" + + request = networkconnectivity_v1.CreatePolicyBasedRouteRequest( + parent="parent_value", + policy_based_route=policy_based_route, + ) + + # Make the request + operation = client.create_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_CreatePolicyBasedRoute_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_sync.py new file mode 100644 index 0000000..3270e3c --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_sync.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for CreatePolicyBasedRoute +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_CreatePolicyBasedRoute_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.cloud import networkconnectivity_v1 + + +def sample_create_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + policy_based_route = networkconnectivity_v1.PolicyBasedRoute() + policy_based_route.next_hop_ilb_ip = "next_hop_ilb_ip_value" + policy_based_route.network = "network_value" + policy_based_route.filter.protocol_version = "IPV4" + + request = networkconnectivity_v1.CreatePolicyBasedRouteRequest( + parent="parent_value", + policy_based_route=policy_based_route, + ) + + # Make the request + operation = client.create_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_CreatePolicyBasedRoute_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_async.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_async.py new file mode 100644 index 0000000..4ce95f1 --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePolicyBasedRoute +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_DeletePolicyBasedRoute_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.cloud import networkconnectivity_v1 + + +async def sample_delete_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.DeletePolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_DeletePolicyBasedRoute_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_sync.py new file mode 100644 index 0000000..5437ffb --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for DeletePolicyBasedRoute +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_DeletePolicyBasedRoute_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.cloud import networkconnectivity_v1 + + +def sample_delete_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.DeletePolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_policy_based_route(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_DeletePolicyBasedRoute_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_async.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_async.py new file mode 100644 index 0000000..47776c4 --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPolicyBasedRoute +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_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.cloud import networkconnectivity_v1 + + +async def sample_get_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetPolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_policy_based_route(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_sync.py new file mode 100644 index 0000000..9a35dc5 --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetPolicyBasedRoute +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_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.cloud import networkconnectivity_v1 + + +def sample_get_policy_based_route(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetPolicyBasedRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_policy_based_route(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_sync] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_async.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_async.py new file mode 100644 index 0000000..4ce8ac7 --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPolicyBasedRoutes +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_ListPolicyBasedRoutes_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.cloud import networkconnectivity_v1 + + +async def sample_list_policy_based_routes(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListPolicyBasedRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_based_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_ListPolicyBasedRoutes_async] diff --git a/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_sync.py b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_sync.py new file mode 100644 index 0000000..8f5b809 --- /dev/null +++ b/samples/generated_samples/networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListPolicyBasedRoutes +# 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-cloud-network-connectivity + + +# [START networkconnectivity_v1_generated_PolicyBasedRoutingService_ListPolicyBasedRoutes_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.cloud import networkconnectivity_v1 + + +def sample_list_policy_based_routes(): + # Create a client + client = networkconnectivity_v1.PolicyBasedRoutingServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListPolicyBasedRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_policy_based_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_PolicyBasedRoutingService_ListPolicyBasedRoutes_sync] diff --git a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_hub_async.py b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_hub_async.py index b60ae1e..2381c03 100644 --- a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_hub_async.py @@ -48,7 +48,7 @@ async def sample_create_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_spoke_async.py b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_spoke_async.py index 8fbe79d..3c03263 100644 --- a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_create_spoke_async.py @@ -48,7 +48,7 @@ async def sample_create_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_hub_async.py b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_hub_async.py index 287364c..1e841fe 100644 --- a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_hub_async.py @@ -48,7 +48,7 @@ async def sample_delete_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_spoke_async.py b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_spoke_async.py index f41b6ba..e8ccc89 100644 --- a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_delete_spoke_async.py @@ -48,7 +48,7 @@ async def sample_delete_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_hub_async.py b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_hub_async.py index 1e94ac2..70e290b 100644 --- a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_hub_async.py +++ b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_hub_async.py @@ -47,7 +47,7 @@ async def sample_update_hub(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_spoke_async.py b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_spoke_async.py index 3e82d78..f47c343 100644 --- a/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_spoke_async.py +++ b/samples/generated_samples/networkconnectivity_v1alpha1_generated_hub_service_update_spoke_async.py @@ -47,7 +47,7 @@ async def sample_update_spoke(): print("Waiting for operation to complete...") - response = await operation.result() + response = (await operation).result() # Handle the response print(response) diff --git a/samples/generated_samples/snippet_metadata_networkconnectivity_v1.json b/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json similarity index 69% rename from samples/generated_samples/snippet_metadata_networkconnectivity_v1.json rename to samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json index 1b39f0a..3046f00 100644 --- a/samples/generated_samples/snippet_metadata_networkconnectivity_v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-networkconnectivity" + "name": "google-cloud-network-connectivity", + "version": "0.1.0" }, "snippets": [ { @@ -1667,6 +1668,666 @@ } ], "title": "networkconnectivity_v1_generated_hub_service_update_spoke_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient", + "shortName": "PolicyBasedRoutingServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient.create_policy_based_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.CreatePolicyBasedRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "CreatePolicyBasedRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.CreatePolicyBasedRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "policy_based_route", + "type": "google.cloud.networkconnectivity_v1.types.PolicyBasedRoute" + }, + { + "name": "policy_based_route_id", + "type": "str" + }, + { + "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": "create_policy_based_route" + }, + "description": "Sample for CreatePolicyBasedRoute", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_CreatePolicyBasedRoute_async", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient", + "shortName": "PolicyBasedRoutingServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient.create_policy_based_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.CreatePolicyBasedRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "CreatePolicyBasedRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.CreatePolicyBasedRouteRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "policy_based_route", + "type": "google.cloud.networkconnectivity_v1.types.PolicyBasedRoute" + }, + { + "name": "policy_based_route_id", + "type": "str" + }, + { + "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": "create_policy_based_route" + }, + "description": "Sample for CreatePolicyBasedRoute", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_CreatePolicyBasedRoute_sync", + "segments": [ + { + "end": 61, + "start": 27, + "type": "FULL" + }, + { + "end": 61, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 51, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 58, + "start": 52, + "type": "REQUEST_EXECUTION" + }, + { + "end": 62, + "start": 59, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_policy_based_routing_service_create_policy_based_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient", + "shortName": "PolicyBasedRoutingServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient.delete_policy_based_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.DeletePolicyBasedRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "DeletePolicyBasedRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.DeletePolicyBasedRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "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": "delete_policy_based_route" + }, + "description": "Sample for DeletePolicyBasedRoute", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_DeletePolicyBasedRoute_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient", + "shortName": "PolicyBasedRoutingServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient.delete_policy_based_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.DeletePolicyBasedRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "DeletePolicyBasedRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.DeletePolicyBasedRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "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": "delete_policy_based_route" + }, + "description": "Sample for DeletePolicyBasedRoute", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_DeletePolicyBasedRoute_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_policy_based_routing_service_delete_policy_based_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient", + "shortName": "PolicyBasedRoutingServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient.get_policy_based_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.GetPolicyBasedRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "GetPolicyBasedRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.GetPolicyBasedRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.types.PolicyBasedRoute", + "shortName": "get_policy_based_route" + }, + "description": "Sample for GetPolicyBasedRoute", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_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": "networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient", + "shortName": "PolicyBasedRoutingServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient.get_policy_based_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.GetPolicyBasedRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "GetPolicyBasedRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.GetPolicyBasedRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.types.PolicyBasedRoute", + "shortName": "get_policy_based_route" + }, + "description": "Sample for GetPolicyBasedRoute", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_GetPolicyBasedRoute_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": "networkconnectivity_v1_generated_policy_based_routing_service_get_policy_based_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient", + "shortName": "PolicyBasedRoutingServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceAsyncClient.list_policy_based_routes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.ListPolicyBasedRoutes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "ListPolicyBasedRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesRequest" + }, + { + "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.cloud.networkconnectivity_v1.services.policy_based_routing_service.pagers.ListPolicyBasedRoutesAsyncPager", + "shortName": "list_policy_based_routes" + }, + "description": "Sample for ListPolicyBasedRoutes", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_ListPolicyBasedRoutes_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient", + "shortName": "PolicyBasedRoutingServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.PolicyBasedRoutingServiceClient.list_policy_based_routes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService.ListPolicyBasedRoutes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.PolicyBasedRoutingService", + "shortName": "PolicyBasedRoutingService" + }, + "shortName": "ListPolicyBasedRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListPolicyBasedRoutesRequest" + }, + { + "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.cloud.networkconnectivity_v1.services.policy_based_routing_service.pagers.ListPolicyBasedRoutesPager", + "shortName": "list_policy_based_routes" + }, + "description": "Sample for ListPolicyBasedRoutes", + "file": "networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_PolicyBasedRoutingService_ListPolicyBasedRoutes_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_policy_based_routing_service_list_policy_based_routes_sync.py" } ] } diff --git a/samples/generated_samples/snippet_metadata_networkconnectivity_v1alpha1.json b/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json similarity index 99% rename from samples/generated_samples/snippet_metadata_networkconnectivity_v1alpha1.json rename to samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json index f8f52a3..7d9f482 100644 --- a/samples/generated_samples/snippet_metadata_networkconnectivity_v1alpha1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json @@ -7,7 +7,8 @@ } ], "language": "PYTHON", - "name": "google-cloud-network-connectivity" + "name": "google-cloud-network-connectivity", + "version": "0.1.0" }, "snippets": [ { diff --git a/scripts/fixup_networkconnectivity_v1_keywords.py b/scripts/fixup_networkconnectivity_v1_keywords.py index 6c70c76..d1a981e 100644 --- a/scripts/fixup_networkconnectivity_v1_keywords.py +++ b/scripts/fixup_networkconnectivity_v1_keywords.py @@ -40,12 +40,16 @@ class networkconnectivityCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { 'create_hub': ('parent', 'hub_id', 'hub', 'request_id', ), + 'create_policy_based_route': ('parent', 'policy_based_route', 'policy_based_route_id', 'request_id', ), 'create_spoke': ('parent', 'spoke_id', 'spoke', 'request_id', ), 'delete_hub': ('name', 'request_id', ), + 'delete_policy_based_route': ('name', 'request_id', ), 'delete_spoke': ('name', 'request_id', ), 'get_hub': ('name', ), + 'get_policy_based_route': ('name', ), 'get_spoke': ('name', ), 'list_hubs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_policy_based_routes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_spokes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'update_hub': ('hub', 'update_mask', 'request_id', ), 'update_spoke': ('spoke', 'update_mask', 'request_id', ), diff --git a/setup.py b/setup.py index ad2c352..b1db39a 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC +# 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. @@ -14,13 +13,36 @@ # See the License for the specific language governing permissions and # limitations under the License. # - import io import os import setuptools # type: ignore -version = "1.4.4" +package_root = os.path.abspath(os.path.dirname(__file__)) + +name = "google-cloud-network-connectivity" + + +description = "Google Cloud Network Connectivity API client library" + +version = {} +with open( + os.path.join(package_root, "google/cloud/networkconnectivity/gapic_version.py") +) as fp: + exec(fp.read(), version) +version = version["__version__"] + +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.0, <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.*", + "proto-plus >= 1.22.0, <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/python-network-connectivity" package_root = os.path.abspath(os.path.dirname(__file__)) @@ -28,38 +50,43 @@ with io.open(readme_filename, encoding="utf-8") as readme_file: readme = readme_file.read() +packages = [ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") +] + +namespaces = ["google"] +if "google.cloud" in packages: + namespaces.append("google.cloud") + setuptools.setup( - name="google-cloud-network-connectivity", + name=name, version=version, + description=description, long_description=readme, author="Google LLC", author_email="googleapis-packages@google.com", license="Apache 2.0", - url="https://github.com/googleapis/python-network-connectivity", - packages=[ - package - for package in setuptools.PEP420PackageFinder.find() - if package.startswith("google") - ], - namespace_packages=("google", "google.cloud"), - platforms="Posix; MacOS X; Windows", - include_package_data=True, - install_requires=( - "google-api-core[grpc] >= 1.32.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*", - "proto-plus >= 1.22.0, <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", - ), - python_requires=">=3.7", + url=url, classifiers=[ - "Development Status :: 5 - Production/Stable", + release_status, "Intended Audience :: Developers", - "Operating System :: OS Independent", + "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", + "Operating System :: OS Independent", "Topic :: Internet", - "Topic :: Software Development :: Libraries :: Python Modules", ], + platforms="Posix; MacOS X; Windows", + packages=packages, + python_requires=">=3.7", + namespace_packages=namespaces, + install_requires=dependencies, + include_package_data=True, zip_safe=False, ) diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt index e69de29..ed7f9ae 100644 --- a/testing/constraints-3.10.txt +++ b/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/testing/constraints-3.11.txt b/testing/constraints-3.11.txt index e69de29..ed7f9ae 100644 --- a/testing/constraints-3.11.txt +++ b/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/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index a12652c..6c44adf 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -1,24 +1,9 @@ -# Copyright 2021 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. -# # This constraints file is used to check that lower bounds # are correct in setup.py -# List *all* library dependencies and extras in this file. +# List all library dependencies and extras in this file. # Pin the version to the lower bound. -# -# e.g., if setup.py has "foo >= 1.14.0, < 2.0.0dev", -# Then this file should have foo==1.14.0 -google-api-core==1.32.0 +# 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.0 proto-plus==1.22.0 protobuf==3.19.5 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index e69de29..ed7f9ae 100644 --- a/testing/constraints-3.8.txt +++ b/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/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index e69de29..ed7f9ae 100644 --- a/testing/constraints-3.9.txt +++ b/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/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py b/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py index f6fe91a..c9c6f8c 100644 --- a/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py +++ b/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py @@ -41,6 +41,7 @@ from google.auth.exceptions import MutualTLSChannelError from google.longrunning import operations_pb2 from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import grpc diff --git a/tests/unit/gapic/networkconnectivity_v1/test_policy_based_routing_service.py b/tests/unit/gapic/networkconnectivity_v1/test_policy_based_routing_service.py new file mode 100644 index 0000000..5672643 --- /dev/null +++ b/tests/unit/gapic/networkconnectivity_v1/test_policy_based_routing_service.py @@ -0,0 +1,2764 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import 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 + +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 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 +from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore +from google.protobuf import timestamp_pb2 # type: ignore +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest + +from google.cloud.networkconnectivity_v1.services.policy_based_routing_service import ( + PolicyBasedRoutingServiceAsyncClient, + PolicyBasedRoutingServiceClient, + pagers, + transports, +) +from google.cloud.networkconnectivity_v1.types import common, policy_based_routing + + +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 + ) + + +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 PolicyBasedRoutingServiceClient._get_default_mtls_endpoint(None) is None + assert ( + PolicyBasedRoutingServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + PolicyBasedRoutingServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + PolicyBasedRoutingServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + PolicyBasedRoutingServiceClient._get_default_mtls_endpoint( + sandbox_mtls_endpoint + ) + == sandbox_mtls_endpoint + ) + assert ( + PolicyBasedRoutingServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (PolicyBasedRoutingServiceClient, "grpc"), + (PolicyBasedRoutingServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_policy_based_routing_service_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 == ("networkconnectivity.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.PolicyBasedRoutingServiceGrpcTransport, "grpc"), + (transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, "grpc_asyncio"), + ], +) +def test_policy_based_routing_service_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", + [ + (PolicyBasedRoutingServiceClient, "grpc"), + (PolicyBasedRoutingServiceAsyncClient, "grpc_asyncio"), + ], +) +def test_policy_based_routing_service_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 == ("networkconnectivity.googleapis.com:443") + + +def test_policy_based_routing_service_client_get_transport_class(): + transport = PolicyBasedRoutingServiceClient.get_transport_class() + available_transports = [ + transports.PolicyBasedRoutingServiceGrpcTransport, + ] + assert transport in available_transports + + transport = PolicyBasedRoutingServiceClient.get_transport_class("grpc") + assert transport == transports.PolicyBasedRoutingServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + "grpc", + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + PolicyBasedRoutingServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PolicyBasedRoutingServiceClient), +) +@mock.patch.object( + PolicyBasedRoutingServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PolicyBasedRoutingServiceAsyncClient), +) +def test_policy_based_routing_service_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( + PolicyBasedRoutingServiceClient, "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( + PolicyBasedRoutingServiceClient, "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, + 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): + client = client_class(transport=transport_name) + + # 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): + client = client_class(transport=transport_name) + + # 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, + 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, + 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", + [ + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + "grpc", + "true", + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + "grpc", + "false", + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + PolicyBasedRoutingServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PolicyBasedRoutingServiceClient), +) +@mock.patch.object( + PolicyBasedRoutingServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PolicyBasedRoutingServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_policy_based_routing_service_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 + 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 + 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, + 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", + [PolicyBasedRoutingServiceClient, PolicyBasedRoutingServiceAsyncClient], +) +@mock.patch.object( + PolicyBasedRoutingServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PolicyBasedRoutingServiceClient), +) +@mock.patch.object( + PolicyBasedRoutingServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(PolicyBasedRoutingServiceAsyncClient), +) +def test_policy_based_routing_service_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 + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + "grpc", + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_policy_based_routing_service_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, + 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", + [ + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_policy_based_routing_service_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, + 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_policy_based_routing_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.networkconnectivity_v1.services.policy_based_routing_service.transports.PolicyBasedRoutingServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = PolicyBasedRoutingServiceClient( + 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", + [ + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + "grpc", + grpc_helpers, + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + "grpc_asyncio", + grpc_helpers_async, + ), + ], +) +def test_policy_based_routing_service_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, + 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( + "networkconnectivity.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="networkconnectivity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "request_type", + [ + policy_based_routing.ListPolicyBasedRoutesRequest, + dict, + ], +) +def test_list_policy_based_routes(request_type, transport: str = "grpc"): + client = PolicyBasedRoutingServiceClient( + 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_policy_based_routes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy_based_routing.ListPolicyBasedRoutesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_policy_based_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.ListPolicyBasedRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPolicyBasedRoutesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_policy_based_routes_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 = PolicyBasedRoutingServiceClient( + 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_policy_based_routes), "__call__" + ) as call: + client.list_policy_based_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.ListPolicyBasedRoutesRequest() + + +@pytest.mark.asyncio +async def test_list_policy_based_routes_async( + transport: str = "grpc_asyncio", + request_type=policy_based_routing.ListPolicyBasedRoutesRequest, +): + client = PolicyBasedRoutingServiceAsyncClient( + 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_policy_based_routes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_based_routing.ListPolicyBasedRoutesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_policy_based_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.ListPolicyBasedRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPolicyBasedRoutesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_policy_based_routes_async_from_dict(): + await test_list_policy_based_routes_async(request_type=dict) + + +def test_list_policy_based_routes_field_headers(): + client = PolicyBasedRoutingServiceClient( + 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 = policy_based_routing.ListPolicyBasedRoutesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), "__call__" + ) as call: + call.return_value = policy_based_routing.ListPolicyBasedRoutesResponse() + client.list_policy_based_routes(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_list_policy_based_routes_field_headers_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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 = policy_based_routing.ListPolicyBasedRoutesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_based_routing.ListPolicyBasedRoutesResponse() + ) + await client.list_policy_based_routes(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"] + + +def test_list_policy_based_routes_flattened(): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy_based_routing.ListPolicyBasedRoutesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_policy_based_routes( + 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_policy_based_routes_flattened_error(): + client = PolicyBasedRoutingServiceClient( + 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.list_policy_based_routes( + policy_based_routing.ListPolicyBasedRoutesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_policy_based_routes_flattened_async(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy_based_routing.ListPolicyBasedRoutesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_based_routing.ListPolicyBasedRoutesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_policy_based_routes( + parent="parent_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" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_policy_based_routes_flattened_error_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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.list_policy_based_routes( + policy_based_routing.ListPolicyBasedRoutesRequest(), + parent="parent_value", + ) + + +def test_list_policy_based_routes_pager(transport_name: str = "grpc"): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="abc", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[], + next_page_token="def", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="ghi", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_policy_based_routes(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all( + isinstance(i, policy_based_routing.PolicyBasedRoute) for i in results + ) + + +def test_list_policy_based_routes_pages(transport_name: str = "grpc"): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="abc", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[], + next_page_token="def", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="ghi", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + ), + RuntimeError, + ) + pages = list(client.list_policy_based_routes(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_policy_based_routes_async_pager(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="abc", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[], + next_page_token="def", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="ghi", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_policy_based_routes( + 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, policy_based_routing.PolicyBasedRoute) for i in responses + ) + + +@pytest.mark.asyncio +async def test_list_policy_based_routes_async_pages(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_policy_based_routes), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="abc", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[], + next_page_token="def", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + ], + next_page_token="ghi", + ), + policy_based_routing.ListPolicyBasedRoutesResponse( + policy_based_routes=[ + policy_based_routing.PolicyBasedRoute(), + policy_based_routing.PolicyBasedRoute(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_policy_based_routes(request={}) + ).pages: # pragma: no branch + 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", + [ + policy_based_routing.GetPolicyBasedRouteRequest, + dict, + ], +) +def test_get_policy_based_route(request_type, transport: str = "grpc"): + client = PolicyBasedRoutingServiceClient( + 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.get_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy_based_routing.PolicyBasedRoute( + name="name_value", + description="description_value", + network="network_value", + priority=898, + self_link="self_link_value", + kind="kind_value", + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ), + next_hop_ilb_ip="next_hop_ilb_ip_value", + ) + response = client.get_policy_based_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.GetPolicyBasedRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_based_routing.PolicyBasedRoute) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.network == "network_value" + assert response.priority == 898 + assert response.self_link == "self_link_value" + assert response.kind == "kind_value" + + +def test_get_policy_based_route_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 = PolicyBasedRoutingServiceClient( + 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.get_policy_based_route), "__call__" + ) as call: + client.get_policy_based_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.GetPolicyBasedRouteRequest() + + +@pytest.mark.asyncio +async def test_get_policy_based_route_async( + transport: str = "grpc_asyncio", + request_type=policy_based_routing.GetPolicyBasedRouteRequest, +): + client = PolicyBasedRoutingServiceAsyncClient( + 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.get_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_based_routing.PolicyBasedRoute( + name="name_value", + description="description_value", + network="network_value", + priority=898, + self_link="self_link_value", + kind="kind_value", + ) + ) + response = await client.get_policy_based_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.GetPolicyBasedRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy_based_routing.PolicyBasedRoute) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.network == "network_value" + assert response.priority == 898 + assert response.self_link == "self_link_value" + assert response.kind == "kind_value" + + +@pytest.mark.asyncio +async def test_get_policy_based_route_async_from_dict(): + await test_get_policy_based_route_async(request_type=dict) + + +def test_get_policy_based_route_field_headers(): + client = PolicyBasedRoutingServiceClient( + 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 = policy_based_routing.GetPolicyBasedRouteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_based_route), "__call__" + ) as call: + call.return_value = policy_based_routing.PolicyBasedRoute() + client.get_policy_based_route(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=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_policy_based_route_field_headers_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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 = policy_based_routing.GetPolicyBasedRouteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_based_route), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_based_routing.PolicyBasedRoute() + ) + await client.get_policy_based_route(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", + "name=name_value", + ) in kw["metadata"] + + +def test_get_policy_based_route_flattened(): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy_based_routing.PolicyBasedRoute() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_policy_based_route( + name="name_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].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_policy_based_route_flattened_error(): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_policy_based_route( + policy_based_routing.GetPolicyBasedRouteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_policy_based_route_flattened_async(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = policy_based_routing.PolicyBasedRoute() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + policy_based_routing.PolicyBasedRoute() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_policy_based_route( + name="name_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].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_policy_based_route_flattened_error_async(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_policy_based_route( + policy_based_routing.GetPolicyBasedRouteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + policy_based_routing.CreatePolicyBasedRouteRequest, + dict, + ], +) +def test_create_policy_based_route(request_type, transport: str = "grpc"): + client = PolicyBasedRoutingServiceClient( + 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.create_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_policy_based_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.CreatePolicyBasedRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_policy_based_route_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 = PolicyBasedRoutingServiceClient( + 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.create_policy_based_route), "__call__" + ) as call: + client.create_policy_based_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.CreatePolicyBasedRouteRequest() + + +@pytest.mark.asyncio +async def test_create_policy_based_route_async( + transport: str = "grpc_asyncio", + request_type=policy_based_routing.CreatePolicyBasedRouteRequest, +): + client = PolicyBasedRoutingServiceAsyncClient( + 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.create_policy_based_route), "__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.create_policy_based_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.CreatePolicyBasedRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_policy_based_route_async_from_dict(): + await test_create_policy_based_route_async(request_type=dict) + + +def test_create_policy_based_route_field_headers(): + client = PolicyBasedRoutingServiceClient( + 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 = policy_based_routing.CreatePolicyBasedRouteRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_based_route), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_policy_based_route(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_create_policy_based_route_field_headers_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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 = policy_based_routing.CreatePolicyBasedRouteRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_based_route), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_policy_based_route(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"] + + +def test_create_policy_based_route_flattened(): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_policy_based_route( + parent="parent_value", + policy_based_route=policy_based_routing.PolicyBasedRoute( + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ) + ), + policy_based_route_id="policy_based_route_id_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 + arg = args[0].policy_based_route + mock_val = policy_based_routing.PolicyBasedRoute( + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ) + ) + assert arg == mock_val + arg = args[0].policy_based_route_id + mock_val = "policy_based_route_id_value" + assert arg == mock_val + + +def test_create_policy_based_route_flattened_error(): + client = PolicyBasedRoutingServiceClient( + 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.create_policy_based_route( + policy_based_routing.CreatePolicyBasedRouteRequest(), + parent="parent_value", + policy_based_route=policy_based_routing.PolicyBasedRoute( + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ) + ), + policy_based_route_id="policy_based_route_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_policy_based_route_flattened_async(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.create_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_policy_based_route( + parent="parent_value", + policy_based_route=policy_based_routing.PolicyBasedRoute( + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ) + ), + policy_based_route_id="policy_based_route_id_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" + assert arg == mock_val + arg = args[0].policy_based_route + mock_val = policy_based_routing.PolicyBasedRoute( + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ) + ) + assert arg == mock_val + arg = args[0].policy_based_route_id + mock_val = "policy_based_route_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_policy_based_route_flattened_error_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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.create_policy_based_route( + policy_based_routing.CreatePolicyBasedRouteRequest(), + parent="parent_value", + policy_based_route=policy_based_routing.PolicyBasedRoute( + virtual_machine=policy_based_routing.PolicyBasedRoute.VirtualMachine( + tags=["tags_value"] + ) + ), + policy_based_route_id="policy_based_route_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + policy_based_routing.DeletePolicyBasedRouteRequest, + dict, + ], +) +def test_delete_policy_based_route(request_type, transport: str = "grpc"): + client = PolicyBasedRoutingServiceClient( + 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.delete_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_policy_based_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.DeletePolicyBasedRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_policy_based_route_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 = PolicyBasedRoutingServiceClient( + 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.delete_policy_based_route), "__call__" + ) as call: + client.delete_policy_based_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.DeletePolicyBasedRouteRequest() + + +@pytest.mark.asyncio +async def test_delete_policy_based_route_async( + transport: str = "grpc_asyncio", + request_type=policy_based_routing.DeletePolicyBasedRouteRequest, +): + client = PolicyBasedRoutingServiceAsyncClient( + 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.delete_policy_based_route), "__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.delete_policy_based_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == policy_based_routing.DeletePolicyBasedRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_policy_based_route_async_from_dict(): + await test_delete_policy_based_route_async(request_type=dict) + + +def test_delete_policy_based_route_field_headers(): + client = PolicyBasedRoutingServiceClient( + 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 = policy_based_routing.DeletePolicyBasedRouteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_based_route), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_policy_based_route(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=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_policy_based_route_field_headers_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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 = policy_based_routing.DeletePolicyBasedRouteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_based_route), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_policy_based_route(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", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_policy_based_route_flattened(): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_policy_based_route( + name="name_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].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_policy_based_route_flattened_error(): + client = PolicyBasedRoutingServiceClient( + 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.delete_policy_based_route( + policy_based_routing.DeletePolicyBasedRouteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_policy_based_route_flattened_async(): + client = PolicyBasedRoutingServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_policy_based_route), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_policy_based_route( + name="name_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].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_policy_based_route_flattened_error_async(): + client = PolicyBasedRoutingServiceAsyncClient( + 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.delete_policy_based_route( + policy_based_routing.DeletePolicyBasedRouteRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyBasedRoutingServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PolicyBasedRoutingServiceClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = PolicyBasedRoutingServiceClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = PolicyBasedRoutingServiceClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = PolicyBasedRoutingServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PolicyBasedRoutingServiceGrpcTransport, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ], +) +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", + ], +) +def test_transport_kind(transport_name): + transport = PolicyBasedRoutingServiceClient.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 = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.PolicyBasedRoutingServiceGrpcTransport, + ) + + +def test_policy_based_routing_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.PolicyBasedRoutingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_policy_based_routing_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.networkconnectivity_v1.services.policy_based_routing_service.transports.PolicyBasedRoutingServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.PolicyBasedRoutingServiceTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_policy_based_routes", + "get_policy_based_route", + "create_policy_based_route", + "delete_policy_based_route", + ) + 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_policy_based_routing_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.networkconnectivity_v1.services.policy_based_routing_service.transports.PolicyBasedRoutingServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyBasedRoutingServiceTransport( + 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_policy_based_routing_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.networkconnectivity_v1.services.policy_based_routing_service.transports.PolicyBasedRoutingServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.PolicyBasedRoutingServiceTransport() + adc.assert_called_once() + + +def test_policy_based_routing_service_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) + PolicyBasedRoutingServiceClient() + 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.PolicyBasedRoutingServiceGrpcTransport, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ], +) +def test_policy_based_routing_service_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.PolicyBasedRoutingServiceGrpcTransport, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ], +) +def test_policy_based_routing_service_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.PolicyBasedRoutingServiceGrpcTransport, grpc_helpers), + (transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_policy_based_routing_service_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( + "networkconnectivity.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="networkconnectivity.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.PolicyBasedRoutingServiceGrpcTransport, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ], +) +def test_policy_based_routing_service_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 + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_policy_based_routing_service_host_no_port(transport_name): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networkconnectivity.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ("networkconnectivity.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_policy_based_routing_service_host_with_port(transport_name): + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="networkconnectivity.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("networkconnectivity.googleapis.com:8000") + + +def test_policy_based_routing_service_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyBasedRoutingServiceGrpcTransport( + 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_policy_based_routing_service_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport( + 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.PolicyBasedRoutingServiceGrpcTransport, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ], +) +def test_policy_based_routing_service_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.PolicyBasedRoutingServiceGrpcTransport, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ], +) +def test_policy_based_routing_service_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_policy_based_routing_service_grpc_lro_client(): + client = PolicyBasedRoutingServiceClient( + 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_policy_based_routing_service_grpc_lro_async_client(): + client = PolicyBasedRoutingServiceAsyncClient( + 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_network_path(): + project = "squid" + resource_id = "clam" + expected = "projects/{project}/global/networks/{resource_id}".format( + project=project, + resource_id=resource_id, + ) + actual = PolicyBasedRoutingServiceClient.network_path(project, resource_id) + assert expected == actual + + +def test_parse_network_path(): + expected = { + "project": "whelk", + "resource_id": "octopus", + } + path = PolicyBasedRoutingServiceClient.network_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.parse_network_path(path) + assert expected == actual + + +def test_policy_based_route_path(): + project = "oyster" + location = "nudibranch" + policy_based_route = "cuttlefish" + expected = "projects/{project}/{location}/global/PolicyBasedRoutes/{policy_based_route}".format( + project=project, + location=location, + policy_based_route=policy_based_route, + ) + actual = PolicyBasedRoutingServiceClient.policy_based_route_path( + project, location, policy_based_route + ) + assert expected == actual + + +def test_parse_policy_based_route_path(): + expected = { + "project": "mussel", + "location": "winkle", + "policy_based_route": "nautilus", + } + path = PolicyBasedRoutingServiceClient.policy_based_route_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.parse_policy_based_route_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "scallop" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = PolicyBasedRoutingServiceClient.common_billing_account_path( + billing_account + ) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "abalone", + } + path = PolicyBasedRoutingServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "squid" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = PolicyBasedRoutingServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "clam", + } + path = PolicyBasedRoutingServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "whelk" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = PolicyBasedRoutingServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "octopus", + } + path = PolicyBasedRoutingServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "oyster" + expected = "projects/{project}".format( + project=project, + ) + actual = PolicyBasedRoutingServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "nudibranch", + } + path = PolicyBasedRoutingServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "cuttlefish" + location = "mussel" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = PolicyBasedRoutingServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "winkle", + "location": "nautilus", + } + path = PolicyBasedRoutingServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = PolicyBasedRoutingServiceClient.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.PolicyBasedRoutingServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = PolicyBasedRoutingServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.PolicyBasedRoutingServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = PolicyBasedRoutingServiceClient.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 = PolicyBasedRoutingServiceAsyncClient( + 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_transport_close(): + transports = { + "grpc": "_grpc_channel", + } + + for transport, close_name in transports.items(): + client = PolicyBasedRoutingServiceClient( + 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 = [ + "grpc", + ] + for transport in transports: + client = PolicyBasedRoutingServiceClient( + 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", + [ + ( + PolicyBasedRoutingServiceClient, + transports.PolicyBasedRoutingServiceGrpcTransport, + ), + ( + PolicyBasedRoutingServiceAsyncClient, + transports.PolicyBasedRoutingServiceGrpcAsyncIOTransport, + ), + ], +) +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, + 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, + ) diff --git a/tests/unit/gapic/networkconnectivity_v1alpha1/test_hub_service.py b/tests/unit/gapic/networkconnectivity_v1alpha1/test_hub_service.py index bbb5a08..7b82946 100644 --- a/tests/unit/gapic/networkconnectivity_v1alpha1/test_hub_service.py +++ b/tests/unit/gapic/networkconnectivity_v1alpha1/test_hub_service.py @@ -41,6 +41,7 @@ from google.auth.exceptions import MutualTLSChannelError from google.longrunning import operations_pb2 from google.oauth2 import service_account +from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore import grpc