diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/reservation_sub_blocks.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/reservation_sub_blocks.rst new file mode 100644 index 000000000000..12517aa21aef --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/reservation_sub_blocks.rst @@ -0,0 +1,10 @@ +ReservationSubBlocks +-------------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.reservation_sub_blocks + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.reservation_sub_blocks.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst index d30f077aa22b..205fd51fc6c6 100644 --- a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst @@ -91,6 +91,7 @@ Services for Google Cloud Compute v1beta API region_zones reservation_blocks reservations + reservation_sub_blocks resource_policies routers routes diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py index 74065dec3c2d..c6bfa7d177d2 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/__init__.py @@ -113,6 +113,7 @@ from .services.region_zones import RegionZonesClient from .services.regions import RegionsClient from .services.reservation_blocks import ReservationBlocksClient +from .services.reservation_sub_blocks import ReservationSubBlocksClient from .services.reservations import ReservationsClient from .services.resource_policies import ResourcePoliciesClient from .services.routers import RoutersClient @@ -686,6 +687,7 @@ GetRegionUrlMapRequest, GetReservationBlockRequest, GetReservationRequest, + GetReservationSubBlockRequest, GetResourcePolicyRequest, GetRoutePolicyRouterRequest, GetRouteRequest, @@ -875,6 +877,7 @@ InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection, InstanceGroupManagerInstanceFlexibilityPolicyProvisioningModelMix, InstanceGroupManagerInstanceLifecyclePolicy, + InstanceGroupManagerInstanceLifecyclePolicyOnRepair, InstanceGroupManagerList, InstanceGroupManagerParams, InstanceGroupManagerResizeRequest, @@ -1138,6 +1141,7 @@ ListRegionZonesRequest, ListReservationBlocksRequest, ListReservationsRequest, + ListReservationSubBlocksRequest, ListResourcePoliciesRequest, ListRoutePoliciesRoutersRequest, ListRoutersRequest, @@ -1479,6 +1483,10 @@ ReservationsPerformMaintenanceRequest, ReservationsResizeRequest, ReservationsScopedList, + ReservationSubBlock, + ReservationSubBlockPhysicalTopology, + ReservationSubBlocksGetResponse, + ReservationSubBlocksListResponse, ResetInstanceRequest, ResizeAdvancedInstanceGroupManagerRequest, ResizeAdvancedRegionInstanceGroupManagerRequest, @@ -1538,6 +1546,7 @@ RouterNatRuleAction, RouterNatSubnetworkToNat, RouterNatSubnetworkToNat64, + RouterParams, RoutersGetRoutePolicyResponse, RoutersListBgpRoutes, RoutersListRoutePolicies, @@ -1977,7 +1986,10 @@ VpnGatewayVpnGatewayInterface, VpnTunnel, VpnTunnelAggregatedList, + VpnTunnelCipherSuite, VpnTunnelList, + VpnTunnelPhase1Algorithms, + VpnTunnelPhase2Algorithms, VpnTunnelsScopedList, WafExpressionSet, WafExpressionSetExpression, @@ -2570,6 +2582,7 @@ "GetRegionUrlMapRequest", "GetReservationBlockRequest", "GetReservationRequest", + "GetReservationSubBlockRequest", "GetResourcePolicyRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", @@ -2766,6 +2779,7 @@ "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceFlexibilityPolicyProvisioningModelMix", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerParams", "InstanceGroupManagerResizeRequest", @@ -3043,6 +3057,7 @@ "ListRegionZonesRequest", "ListRegionsRequest", "ListReservationBlocksRequest", + "ListReservationSubBlocksRequest", "ListReservationsRequest", "ListResourcePoliciesRequest", "ListRoutePoliciesRoutersRequest", @@ -3429,6 +3444,11 @@ "ReservationBlocksGetResponse", "ReservationBlocksListResponse", "ReservationList", + "ReservationSubBlock", + "ReservationSubBlockPhysicalTopology", + "ReservationSubBlocksClient", + "ReservationSubBlocksGetResponse", + "ReservationSubBlocksListResponse", "ReservationsBlocksPerformMaintenanceRequest", "ReservationsClient", "ReservationsPerformMaintenanceRequest", @@ -3494,6 +3514,7 @@ "RouterNatRuleAction", "RouterNatSubnetworkToNat", "RouterNatSubnetworkToNat64", + "RouterParams", "RouterStatus", "RouterStatusBgpPeerStatus", "RouterStatusNatStatus", @@ -3954,7 +3975,10 @@ "VpnGatewaysScopedList", "VpnTunnel", "VpnTunnelAggregatedList", + "VpnTunnelCipherSuite", "VpnTunnelList", + "VpnTunnelPhase1Algorithms", + "VpnTunnelPhase2Algorithms", "VpnTunnelsClient", "VpnTunnelsScopedList", "WafExpressionSet", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json index d52a4be11199..67096cd6167e 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_metadata.json @@ -4383,6 +4383,25 @@ } } }, + "ReservationSubBlocks": { + "clients": { + "rest": { + "libraryClient": "ReservationSubBlocksClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "Reservations": { "clients": { "rest": { diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py index f2643754be34..20a9cd975b02 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.1.1" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_security_policies/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_security_policies/client.py index 61ba7e7fba06..618c3f7f87a0 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_security_policies/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_security_policies/client.py @@ -720,9 +720,12 @@ def add_association_unary( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: r"""Inserts an association for the specified security - policy. Use of this API to modify firewall policies is - deprecated. Use firewallPolicies.addAssociation instead - if possible. + policy. This has billing implications. Projects in the + hierarchy with effective hierarchical security policies + will be automatically enrolled into Cloud Armor + Enterprise if not already enrolled. Use of this API to + modify firewall policies is deprecated. Use + firewallPolicies.addAssociation instead if possible. .. code-block:: python @@ -850,9 +853,12 @@ def add_association( metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> extended_operation.ExtendedOperation: r"""Inserts an association for the specified security - policy. Use of this API to modify firewall policies is - deprecated. Use firewallPolicies.addAssociation instead - if possible. + policy. This has billing implications. Projects in the + hierarchy with effective hierarchical security policies + will be automatically enrolled into Cloud Armor + Enterprise if not already enrolled. Use of this API to + modify firewall policies is deprecated. Use + firewallPolicies.addAssociation instead if possible. .. code-block:: python diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/__init__.py new file mode 100644 index 000000000000..4a1a944ee416 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 .client import ReservationSubBlocksClient + +__all__ = ("ReservationSubBlocksClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py new file mode 100644 index 000000000000..a4bea4525532 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/client.py @@ -0,0 +1,1016 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 http import HTTPStatus +import json +import logging as std_logging +import os +import re +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +import warnings + +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.compute_v1beta import gapic_version as package_version + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = std_logging.getLogger(__name__) + +from google.cloud.compute_v1beta.services.reservation_sub_blocks import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ReservationSubBlocksTransport +from .transports.rest import ReservationSubBlocksRestTransport + + +class ReservationSubBlocksClientMeta(type): + """Metaclass for the ReservationSubBlocks 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[ReservationSubBlocksTransport]] + _transport_registry["rest"] = ReservationSubBlocksRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ReservationSubBlocksTransport]: + """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 ReservationSubBlocksClient(metaclass=ReservationSubBlocksClientMeta): + """The ReservationSubBlocks API.""" + + @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") + + # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. + DEFAULT_ENDPOINT = "compute.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + _DEFAULT_ENDPOINT_TEMPLATE = "compute.{UNIVERSE_DOMAIN}" + _DEFAULT_UNIVERSE = "googleapis.com" + + @classmethod + def from_service_account_info(cls, info: dict, *args, **kwargs): + """Creates an instance of this client using the provided credentials + info. + + Args: + info (dict): The service account private key info. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + ReservationSubBlocksClient: 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: + ReservationSubBlocksClient: 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) -> ReservationSubBlocksTransport: + """Returns the transport used by the client instance. + + Returns: + ReservationSubBlocksTransport: The transport used by the client + instance. + """ + return self._transport + + @staticmethod + def common_billing_account_path( + billing_account: str, + ) -> str: + """Returns a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", 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 + ): + """Deprecated. Return the API endpoint and client cert source for mutual TLS. + + The client cert source is determined in the following order: + (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the + client cert source is None. + (2) if `client_options.client_cert_source` is provided, use the provided one; if the + default client cert source exists, use the default one; otherwise the client cert + source is None. + + The API endpoint is determined in the following order: + (1) if `client_options.api_endpoint` if provided, use the provided one. + (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the + default mTLS endpoint; if the environment variable is "never", use the default API + endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise + use the default API endpoint. + + More details can be found at https://google.aip.dev/auth/4114. + + Args: + client_options (google.api_core.client_options.ClientOptions): Custom options for the + client. Only the `api_endpoint` and `client_cert_source` properties may be used + in this method. + + Returns: + Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the + client cert source to use. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If any errors happen. + """ + + warnings.warn( + "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", + DeprecationWarning, + ) + if client_options is None: + client_options = client_options_lib.ClientOptions() + use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Figure out the client cert source to use. + client_cert_source = None + if use_client_cert == "true": + if client_options.client_cert_source: + client_cert_source = client_options.client_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + api_endpoint = cls.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = cls.DEFAULT_ENDPOINT + + return api_endpoint, client_cert_source + + @staticmethod + def _read_environment_variables(): + """Returns the environment variables used by the client. + + Returns: + Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, + GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. + + Raises: + ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not + any of ["true", "false"]. + google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT + is not any of ["auto", "never", "always"]. + """ + use_client_cert = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if use_client_cert not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + if use_mtls_endpoint not in ("auto", "never", "always"): + raise MutualTLSChannelError( + "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + return use_client_cert == "true", use_mtls_endpoint, universe_domain_env + + @staticmethod + def _get_client_cert_source(provided_cert_source, use_cert_flag): + """Return the client cert source to be used by the client. + + Args: + provided_cert_source (bytes): The client certificate source provided. + use_cert_flag (bool): A flag indicating whether to use the client certificate. + + Returns: + bytes or None: The client cert source to be used by the client. + """ + client_cert_source = None + if use_cert_flag: + if provided_cert_source: + client_cert_source = provided_cert_source + elif mtls.has_default_client_cert_source(): + client_cert_source = mtls.default_client_cert_source() + return client_cert_source + + @staticmethod + def _get_api_endpoint( + api_override, client_cert_source, universe_domain, use_mtls_endpoint + ): + """Return the API endpoint used by the client. + + Args: + api_override (str): The API endpoint override. If specified, this is always + the return value of this function and the other arguments are not used. + client_cert_source (bytes): The client certificate source used by the client. + universe_domain (str): The universe domain used by the client. + use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. + Possible values are "always", "auto", or "never". + + Returns: + str: The API endpoint to be used by the client. + """ + if api_override is not None: + api_endpoint = api_override + elif use_mtls_endpoint == "always" or ( + use_mtls_endpoint == "auto" and client_cert_source + ): + _default_universe = ReservationSubBlocksClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ReservationSubBlocksClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ReservationSubBlocksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=universe_domain + ) + return api_endpoint + + @staticmethod + def _get_universe_domain( + client_universe_domain: Optional[str], universe_domain_env: Optional[str] + ) -> str: + """Return the universe domain used by the client. + + Args: + client_universe_domain (Optional[str]): The universe domain configured via the client options. + universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. + + Returns: + str: The universe domain to be used by the client. + + Raises: + ValueError: If the universe domain is an empty string. + """ + universe_domain = ReservationSubBlocksClient._DEFAULT_UNIVERSE + if client_universe_domain is not None: + universe_domain = client_universe_domain + elif universe_domain_env is not None: + universe_domain = universe_domain_env + if len(universe_domain.strip()) == 0: + raise ValueError("Universe Domain cannot be an empty string.") + return universe_domain + + def _validate_universe_domain(self): + """Validates client's and credentials' universe domains are consistent. + + Returns: + bool: True iff the configured universe domain is valid. + + Raises: + ValueError: If the configured universe domain is not valid. + """ + + # NOTE (b/349488459): universe validation is disabled until further notice. + return True + + def _add_cred_info_for_auth_errors( + self, error: core_exceptions.GoogleAPICallError + ) -> None: + """Adds credential info string to error details for 401/403/404 errors. + + Args: + error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. + """ + if error.code not in [ + HTTPStatus.UNAUTHORIZED, + HTTPStatus.FORBIDDEN, + HTTPStatus.NOT_FOUND, + ]: + return + + cred = self._transport._credentials + + # get_cred_info is only available in google-auth>=2.35.0 + if not hasattr(cred, "get_cred_info"): + return + + # ignore the type check since pypy test fails when get_cred_info + # is not available + cred_info = cred.get_cred_info() # type: ignore + if cred_info and hasattr(error._details, "append"): + error._details.append(json.dumps(cred_info)) + + @property + def api_endpoint(self): + """Return the API endpoint used by the client instance. + + Returns: + str: The API endpoint used by the client instance. + """ + return self._api_endpoint + + @property + def universe_domain(self) -> str: + """Return the universe domain used by the client instance. + + Returns: + str: The universe domain used by the client instance. + """ + return self._universe_domain + + def __init__( + self, + *, + credentials: Optional[ga_credentials.Credentials] = None, + transport: Optional[ + Union[ + str, + ReservationSubBlocksTransport, + Callable[..., ReservationSubBlocksTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the reservation sub blocks client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Optional[Union[str,ReservationSubBlocksTransport,Callable[..., ReservationSubBlocksTransport]]]): + The transport to use, or a Callable that constructs and returns a new transport. + If a Callable is given, it will be called with the same set of initialization + arguments as used in the ReservationSubBlocksTransport constructor. + If set to None, a transport is chosen automatically. + NOTE: "rest" transport functionality is currently in a + beta state (preview). We welcome your feedback via an + issue in this library's source repository. + client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): + Custom options for the client. + + 1. The ``api_endpoint`` property can be used to override the + default endpoint provided by the client when ``transport`` is + not explicitly provided. Only if this property is not set and + ``transport`` was not explicitly provided, the endpoint is + determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment + variable, which have one of the following values: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto-switch to the + default mTLS endpoint if client certificate is present; this is + the default value). + + 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide a client certificate for mTLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + 3. The ``universe_domain`` property can be used to override the + default "googleapis.com" universe. Note that the ``api_endpoint`` + property still takes precedence; and ``universe_domain`` is + currently not supported for mTLS. + + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + self._client_options = client_options + if isinstance(self._client_options, dict): + self._client_options = client_options_lib.from_dict(self._client_options) + if self._client_options is None: + self._client_options = client_options_lib.ClientOptions() + self._client_options = cast( + client_options_lib.ClientOptions, self._client_options + ) + + universe_domain_opt = getattr(self._client_options, "universe_domain", None) + + ( + self._use_client_cert, + self._use_mtls_endpoint, + self._universe_domain_env, + ) = ReservationSubBlocksClient._read_environment_variables() + self._client_cert_source = ReservationSubBlocksClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ReservationSubBlocksClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint = None # updated below, depending on `transport` + + # Initialize the universe domain validation. + self._is_universe_domain_valid = False + + if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER + # Setup logging. + client_logging.initialize_logging() + + api_key_value = getattr(self._client_options, "api_key", None) + if api_key_value and credentials: + raise ValueError( + "client_options.api_key and credentials are mutually exclusive" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + transport_provided = isinstance(transport, ReservationSubBlocksTransport) + if transport_provided: + # transport is a ReservationSubBlocksTransport instance. + if credentials or self._client_options.credentials_file or api_key_value: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if self._client_options.scopes: + raise ValueError( + "When providing a transport instance, provide its scopes " + "directly." + ) + self._transport = cast(ReservationSubBlocksTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or ReservationSubBlocksClient._get_api_endpoint( + self._client_options.api_endpoint, + self._client_cert_source, + self._universe_domain, + self._use_mtls_endpoint, + ) + ) + + if not transport_provided: + import google.auth._default # type: ignore + + if api_key_value and hasattr( + google.auth._default, "get_api_key_credentials" + ): + credentials = google.auth._default.get_api_key_credentials( + api_key_value + ) + + transport_init: Union[ + Type[ReservationSubBlocksTransport], + Callable[..., ReservationSubBlocksTransport], + ] = ( + ReservationSubBlocksClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ReservationSubBlocksTransport], transport) + ) + # initialize with the provided callable or the passed in class + self._transport = transport_init( + credentials=credentials, + credentials_file=self._client_options.credentials_file, + host=self._api_endpoint, + scopes=self._client_options.scopes, + client_cert_source_for_mtls=self._client_cert_source, + quota_project_id=self._client_options.quota_project_id, + client_info=client_info, + always_use_jwt_access=True, + api_audience=self._client_options.api_audience, + ) + + if "async" not in str(self._transport): + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + std_logging.DEBUG + ): # pragma: NO COVER + _LOGGER.debug( + "Created client `google.cloud.compute_v1beta.ReservationSubBlocksClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "universeDomain": getattr( + self._transport._credentials, "universe_domain", "" + ), + "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", + "credentialsInfo": getattr( + self.transport._credentials, "get_cred_info", lambda: None + )(), + } + if hasattr(self._transport, "_credentials") + else { + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetReservationSubBlockRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + parent_name: Optional[str] = None, + reservation_sub_block: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ReservationSubBlocksGetResponse: + r"""Retrieves information about the specified reservation + subBlock. + + .. 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 compute_v1beta + + def sample_get(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.GetReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetReservationSubBlockRequest, dict]): + The request object. A request message for + ReservationSubBlocks.Get. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + parent_name (str): + The name of the parent reservation and parent block. In + the format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + + This corresponds to the ``parent_name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reservation_sub_block (str): + The name of the reservation subBlock. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``reservation_sub_block`` 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.types.ReservationSubBlocksGetResponse: + + """ + # 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. + flattened_params = [project, zone, parent_name, reservation_sub_block] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.GetReservationSubBlockRequest): + request = compute.GetReservationSubBlockRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if parent_name is not None: + request.parent_name = parent_name + if reservation_sub_block is not None: + request.reservation_sub_block = reservation_sub_block + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("parent_name", request.parent_name), + ("reservation_sub_block", request.reservation_sub_block), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list( + self, + request: Optional[Union[compute.ListReservationSubBlocksRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + parent_name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> pagers.ListPager: + r"""Retrieves a list of reservation subBlocks under a + single reservation. + + .. 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 compute_v1beta + + def sample_list(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.ListReservationSubBlocksRequest( + parent_name="parent_name_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ListReservationSubBlocksRequest, dict]): + The request object. A request message for + ReservationSubBlocks.List. See the + method description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + parent_name (str): + The name of the parent reservation and parent block. In + the format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + + This corresponds to the ``parent_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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + google.cloud.compute_v1beta.services.reservation_sub_blocks.pagers.ListPager: + A list of reservation subBlocks under + a single reservation. + 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. + flattened_params = [project, zone, parent_name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, compute.ListReservationSubBlocksRequest): + request = compute.ListReservationSubBlocksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if parent_name is not None: + request.parent_name = parent_name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("parent_name", request.parent_name), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ReservationSubBlocksClient": + 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__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + +__all__ = ("ReservationSubBlocksClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/pagers.py new file mode 100644 index 000000000000..51a10f719dec --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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, + Union, +) + +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.api_core import retry_async as retries_async + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] + OptionalAsyncRetry = Union[ + retries_async.AsyncRetry, gapic_v1.method._MethodDefault, None + ] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + OptionalAsyncRetry = Union[retries_async.AsyncRetry, object, None] # type: ignore + +from google.cloud.compute_v1beta.types import compute + + +class ListPager: + """A pager for iterating through ``list`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1beta.types.ReservationSubBlocksListResponse` object, and + provides an ``__iter__`` method to iterate through its + ``items`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``List`` requests and continue to iterate + through the ``items`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1beta.types.ReservationSubBlocksListResponse` + 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[..., compute.ReservationSubBlocksListResponse], + request: compute.ListReservationSubBlocksRequest, + response: compute.ReservationSubBlocksListResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.compute_v1beta.types.ListReservationSubBlocksRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.ReservationSubBlocksListResponse): + The initial response object. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + """ + self._method = method + self._request = compute.ListReservationSubBlocksRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[compute.ReservationSubBlocksListResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[compute.ReservationSubBlock]: + for page in self.pages: + yield from page.items + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/README.rst new file mode 100644 index 000000000000..5c23b59d8c44 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`ReservationSubBlocksTransport` is the ABC for all transports. +- public child `ReservationSubBlocksGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `ReservationSubBlocksGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseReservationSubBlocksRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `ReservationSubBlocksRestTransport` for sync REST transport with inner classes `METHOD` derived from the parent's corresponding `_BaseMETHOD` classes (defined in `rest.py`). diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/__init__.py new file mode 100644 index 000000000000..b1aa0cc62777 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/__init__.py @@ -0,0 +1,32 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 ReservationSubBlocksTransport +from .rest import ReservationSubBlocksRestInterceptor, ReservationSubBlocksRestTransport + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[ReservationSubBlocksTransport]] +_transport_registry["rest"] = ReservationSubBlocksRestTransport + +__all__ = ( + "ReservationSubBlocksTransport", + "ReservationSubBlocksRestTransport", + "ReservationSubBlocksRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py new file mode 100644 index 000000000000..2c4188a3634d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/base.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 +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.oauth2 import service_account # type: ignore +import google.protobuf + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.types import compute + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=package_version.__version__ +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ReservationSubBlocksTransport(abc.ABC): + """Abstract transport class for ReservationSubBlocks.""" + + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ) + + DEFAULT_HOST: str = "compute.googleapis.com" + + def __init__( + self, + *, + host: str = DEFAULT_HOST, + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + api_audience: Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + """ + + scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES} + + # Save the scopes. + self._scopes = scopes + if not hasattr(self, "_ignore_credentials"): + self._ignore_credentials: bool = False + + # 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 and not self._ignore_credentials: + credentials, _ = google.auth.default( + **scopes_kwargs, quota_project_id=quota_project_id + ) + # Don't apply audience if the credentials file passed from user. + if hasattr(credentials, "with_gdch_audience"): + credentials = credentials.with_gdch_audience( + api_audience if api_audience else host + ) + + # If the credentials are service account credentials, then always try to use self signed JWT. + if ( + always_use_jwt_access + and isinstance(credentials, service_account.Credentials) + and hasattr(service_account.Credentials, "with_always_use_jwt_access") + ): + credentials = credentials.with_always_use_jwt_access(True) + + # Save the credentials. + self._credentials = credentials + + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.get: gapic_v1.method.wrap_method( + self.get, + default_timeout=None, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_timeout=None, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetReservationSubBlockRequest], + Union[ + compute.ReservationSubBlocksGetResponse, + Awaitable[compute.ReservationSubBlocksGetResponse], + ], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListReservationSubBlocksRequest], + Union[ + compute.ReservationSubBlocksListResponse, + Awaitable[compute.ReservationSubBlocksListResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ReservationSubBlocksTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py new file mode 100644 index 000000000000..46a107d75ad5 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest.py @@ -0,0 +1,618 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import dataclasses +import json # type: ignore +import logging +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union +import warnings + +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1, rest_helpers, rest_streaming +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.transport.requests import AuthorizedSession # type: ignore +import google.protobuf +from google.protobuf import json_format +from requests import __version__ as requests_version + +from google.cloud.compute_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO as BASE_DEFAULT_CLIENT_INFO +from .rest_base import _BaseReservationSubBlocksRestTransport + +try: + OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] +except AttributeError: # pragma: NO COVER + OptionalRetry = Union[retries.Retry, object, None] # type: ignore + +try: + from google.api_core import client_logging # type: ignore + + CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER +except ImportError: # pragma: NO COVER + CLIENT_LOGGING_SUPPORTED = False + +_LOGGER = logging.getLogger(__name__) + +DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=BASE_DEFAULT_CLIENT_INFO.gapic_version, + grpc_version=None, + rest_version=f"requests@{requests_version}", +) + +if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER + DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ + + +class ReservationSubBlocksRestInterceptor: + """Interceptor for ReservationSubBlocks. + + Interceptors are used to manipulate requests, request metadata, and responses + in arbitrary ways. + Example use cases include: + * Logging + * Verifying requests according to service or custom semantics + * Stripping extraneous information from responses + + These use cases and more can be enabled by injecting an + instance of a custom subclass when constructing the ReservationSubBlocksRestTransport. + + .. code-block:: python + class MyCustomReservationSubBlocksInterceptor(ReservationSubBlocksRestInterceptor): + def pre_get(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list(self, response): + logging.log(f"Received response: {response}") + return response + + transport = ReservationSubBlocksRestTransport(interceptor=MyCustomReservationSubBlocksInterceptor()) + client = ReservationSubBlocksClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetReservationSubBlockRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetReservationSubBlockRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationSubBlocks server. + """ + return request, metadata + + def post_get( + self, response: compute.ReservationSubBlocksGetResponse + ) -> compute.ReservationSubBlocksGetResponse: + """Post-rpc interceptor for get + + DEPRECATED. Please use the `post_get_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ReservationSubBlocks server but before + it is returned to user code. This `post_get` interceptor runs + before the `post_get_with_metadata` interceptor. + """ + return response + + def post_get_with_metadata( + self, + response: compute.ReservationSubBlocksGetResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ReservationSubBlocksGetResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ReservationSubBlocks server but before it is returned to user code. + + We recommend only using this `post_get_with_metadata` + interceptor in new development instead of the `post_get` interceptor. + When both interceptors are used, this `post_get_with_metadata` interceptor runs after the + `post_get` interceptor. The (possibly modified) response returned by + `post_get` will be passed to + `post_get_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListReservationSubBlocksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListReservationSubBlocksRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list + + Override in a subclass to manipulate the request or metadata + before they are sent to the ReservationSubBlocks server. + """ + return request, metadata + + def post_list( + self, response: compute.ReservationSubBlocksListResponse + ) -> compute.ReservationSubBlocksListResponse: + """Post-rpc interceptor for list + + DEPRECATED. Please use the `post_list_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the ReservationSubBlocks server but before + it is returned to user code. This `post_list` interceptor runs + before the `post_list_with_metadata` interceptor. + """ + return response + + def post_list_with_metadata( + self, + response: compute.ReservationSubBlocksListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ReservationSubBlocksListResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the ReservationSubBlocks server but before it is returned to user code. + + We recommend only using this `post_list_with_metadata` + interceptor in new development instead of the `post_list` interceptor. + When both interceptors are used, this `post_list_with_metadata` interceptor runs after the + `post_list` interceptor. The (possibly modified) response returned by + `post_list` will be passed to + `post_list_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class ReservationSubBlocksRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReservationSubBlocksRestInterceptor + + +class ReservationSubBlocksRestTransport(_BaseReservationSubBlocksRestTransport): + """REST backend synchronous transport for ReservationSubBlocks. + + The ReservationSubBlocks API. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[ga_credentials.Credentials] = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + interceptor: Optional[ReservationSubBlocksRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + NOTE: This REST transport functionality is currently in a beta + state (preview). We welcome your feedback via a GitHub issue in + this library's repository. Thank you! + + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + client_cert_source_for_mtls (Callable[[], Tuple[bytes, bytes]]): Client + certificate to configure mutual TLS HTTP channel. It is ignored + if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + # TODO(yon-mg): resolve other ctor params i.e. scopes, quota, etc. + # TODO: When custom host (api_endpoint) is set, `scopes` must *also* be set on the + # credentials object + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + url_scheme=url_scheme, + api_audience=api_audience, + ) + self._session = AuthorizedSession( + self._credentials, default_host=self.DEFAULT_HOST + ) + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or ReservationSubBlocksRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get( + _BaseReservationSubBlocksRestTransport._BaseGet, ReservationSubBlocksRestStub + ): + def __hash__(self): + return hash("ReservationSubBlocksRestTransport.Get") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.GetReservationSubBlockRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ReservationSubBlocksGetResponse: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetReservationSubBlockRequest): + The request object. A request message for + ReservationSubBlocks.Get. See the method + description for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.ReservationSubBlocksGetResponse: + + """ + + http_options = ( + _BaseReservationSubBlocksRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseReservationSubBlocksRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseReservationSubBlocksRestTransport._BaseGet._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.ReservationSubBlocksClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReservationSubBlocksRestTransport._Get._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.ReservationSubBlocksGetResponse() + pb_resp = compute.ReservationSubBlocksGetResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.ReservationSubBlocksGetResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.ReservationSubBlocksClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseReservationSubBlocksRestTransport._BaseList, ReservationSubBlocksRestStub + ): + def __hash__(self): + return hash("ReservationSubBlocksRestTransport.List") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: compute.ListReservationSubBlocksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ReservationSubBlocksListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListReservationSubBlocksRequest): + The request object. A request message for + ReservationSubBlocks.List. See the + method description for details. + 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, Union[str, bytes]]]): Key/value pairs which should be + sent along with the request as metadata. Normally, each value must be of type `str`, + but for metadata keys ending with the suffix `-bin`, the corresponding values must + be of type `bytes`. + + Returns: + ~.compute.ReservationSubBlocksListResponse: + A list of reservation subBlocks under + a single reservation. + + """ + + http_options = ( + _BaseReservationSubBlocksRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseReservationSubBlocksRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseReservationSubBlocksRestTransport._BaseList._get_query_params_json( + transcoded_request + ) + ) + + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + request_url = "{host}{uri}".format( + host=self._host, uri=transcoded_request["uri"] + ) + method = transcoded_request["method"] + try: + request_payload = type(request).to_json(request) + except: + request_payload = None + http_request = { + "payload": request_payload, + "requestMethod": method, + "requestUrl": request_url, + "headers": dict(metadata), + } + _LOGGER.debug( + f"Sending request for google.cloud.compute_v1beta.ReservationSubBlocksClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReservationSubBlocksRestTransport._List._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.ReservationSubBlocksListResponse() + pb_resp = compute.ReservationSubBlocksListResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_with_metadata(resp, response_metadata) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.ReservationSubBlocksListResponse.to_json( + response + ) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.compute_v1beta.ReservationSubBlocksClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get( + self, + ) -> Callable[ + [compute.GetReservationSubBlockRequest], compute.ReservationSubBlocksGetResponse + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Get(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[ + [compute.ListReservationSubBlocksRequest], + compute.ReservationSubBlocksListResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._List(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ReservationSubBlocksRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py new file mode 100644 index 000000000000..487cc6588889 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reservation_sub_blocks/transports/rest_base.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 # type: ignore +import re +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +from google.api_core import gapic_v1, path_template +from google.protobuf import json_format + +from google.cloud.compute_v1beta.types import compute + +from .base import DEFAULT_CLIENT_INFO, ReservationSubBlocksTransport + + +class _BaseReservationSubBlocksRestTransport(ReservationSubBlocksTransport): + """Base REST backend transport for ReservationSubBlocks. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): 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. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetReservationSubBlockRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseReservationSubBlocksRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListReservationSubBlocksRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=False, + ) + ) + query_params.update( + _BaseReservationSubBlocksRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseReservationSubBlocksRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py index 71e7f8a721f1..d420c27aacc3 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/__init__.py @@ -559,6 +559,7 @@ GetRegionUrlMapRequest, GetReservationBlockRequest, GetReservationRequest, + GetReservationSubBlockRequest, GetResourcePolicyRequest, GetRoutePolicyRouterRequest, GetRouteRequest, @@ -748,6 +749,7 @@ InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection, InstanceGroupManagerInstanceFlexibilityPolicyProvisioningModelMix, InstanceGroupManagerInstanceLifecyclePolicy, + InstanceGroupManagerInstanceLifecyclePolicyOnRepair, InstanceGroupManagerList, InstanceGroupManagerParams, InstanceGroupManagerResizeRequest, @@ -1011,6 +1013,7 @@ ListRegionZonesRequest, ListReservationBlocksRequest, ListReservationsRequest, + ListReservationSubBlocksRequest, ListResourcePoliciesRequest, ListRoutePoliciesRoutersRequest, ListRoutersRequest, @@ -1352,6 +1355,10 @@ ReservationsPerformMaintenanceRequest, ReservationsResizeRequest, ReservationsScopedList, + ReservationSubBlock, + ReservationSubBlockPhysicalTopology, + ReservationSubBlocksGetResponse, + ReservationSubBlocksListResponse, ResetInstanceRequest, ResizeAdvancedInstanceGroupManagerRequest, ResizeAdvancedRegionInstanceGroupManagerRequest, @@ -1411,6 +1418,7 @@ RouterNatRuleAction, RouterNatSubnetworkToNat, RouterNatSubnetworkToNat64, + RouterParams, RoutersGetRoutePolicyResponse, RoutersListBgpRoutes, RoutersListRoutePolicies, @@ -1850,7 +1858,10 @@ VpnGatewayVpnGatewayInterface, VpnTunnel, VpnTunnelAggregatedList, + VpnTunnelCipherSuite, VpnTunnelList, + VpnTunnelPhase1Algorithms, + VpnTunnelPhase2Algorithms, VpnTunnelsScopedList, WafExpressionSet, WafExpressionSetExpression, @@ -2426,6 +2437,7 @@ "GetRegionUrlMapRequest", "GetReservationBlockRequest", "GetReservationRequest", + "GetReservationSubBlockRequest", "GetResourcePolicyRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", @@ -2615,6 +2627,7 @@ "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceFlexibilityPolicyProvisioningModelMix", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerParams", "InstanceGroupManagerResizeRequest", @@ -2878,6 +2891,7 @@ "ListRegionZonesRequest", "ListReservationBlocksRequest", "ListReservationsRequest", + "ListReservationSubBlocksRequest", "ListResourcePoliciesRequest", "ListRoutePoliciesRoutersRequest", "ListRoutersRequest", @@ -3219,6 +3233,10 @@ "ReservationsPerformMaintenanceRequest", "ReservationsResizeRequest", "ReservationsScopedList", + "ReservationSubBlock", + "ReservationSubBlockPhysicalTopology", + "ReservationSubBlocksGetResponse", + "ReservationSubBlocksListResponse", "ResetInstanceRequest", "ResizeAdvancedInstanceGroupManagerRequest", "ResizeAdvancedRegionInstanceGroupManagerRequest", @@ -3278,6 +3296,7 @@ "RouterNatRuleAction", "RouterNatSubnetworkToNat", "RouterNatSubnetworkToNat64", + "RouterParams", "RoutersGetRoutePolicyResponse", "RoutersListBgpRoutes", "RoutersListRoutePolicies", @@ -3717,7 +3736,10 @@ "VpnGatewayVpnGatewayInterface", "VpnTunnel", "VpnTunnelAggregatedList", + "VpnTunnelCipherSuite", "VpnTunnelList", + "VpnTunnelPhase1Algorithms", + "VpnTunnelPhase2Algorithms", "VpnTunnelsScopedList", "WafExpressionSet", "WafExpressionSetExpression", diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py index 2f778bd299a4..21122296e6c2 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/types/compute.py @@ -571,6 +571,7 @@ "GetRegionUrlMapRequest", "GetReservationBlockRequest", "GetReservationRequest", + "GetReservationSubBlockRequest", "GetResourcePolicyRequest", "GetRoutePolicyRouterRequest", "GetRouteRequest", @@ -758,6 +759,7 @@ "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceFlexibilityPolicyProvisioningModelMix", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerParams", "InstanceGroupManagerResizeRequest", @@ -1020,6 +1022,7 @@ "ListRegionZonesRequest", "ListRegionsRequest", "ListReservationBlocksRequest", + "ListReservationSubBlocksRequest", "ListReservationsRequest", "ListResourcePoliciesRequest", "ListRoutePoliciesRoutersRequest", @@ -1358,6 +1361,10 @@ "ReservationBlocksGetResponse", "ReservationBlocksListResponse", "ReservationList", + "ReservationSubBlock", + "ReservationSubBlockPhysicalTopology", + "ReservationSubBlocksGetResponse", + "ReservationSubBlocksListResponse", "ReservationsBlocksPerformMaintenanceRequest", "ReservationsPerformMaintenanceRequest", "ReservationsResizeRequest", @@ -1421,6 +1428,7 @@ "RouterNatRuleAction", "RouterNatSubnetworkToNat", "RouterNatSubnetworkToNat64", + "RouterParams", "RouterStatus", "RouterStatusBgpPeerStatus", "RouterStatusNatStatus", @@ -1860,7 +1868,10 @@ "VpnGatewaysScopedList", "VpnTunnel", "VpnTunnelAggregatedList", + "VpnTunnelCipherSuite", "VpnTunnelList", + "VpnTunnelPhase1Algorithms", + "VpnTunnelPhase2Algorithms", "VpnTunnelsScopedList", "WafExpressionSet", "WafExpressionSetExpression", @@ -18163,7 +18174,7 @@ class BackendServiceHAPolicy(proto.Message): must belong to that network. However, individual NEGs can belong to different subnetworks of that network. - The maximum number of network endpoints across all backends of a - backend service with fastIPMove is 64. - The maximum number + backend service with fastIPMove is 32. - The maximum number of backend services with fastIPMove that can have the same network endpoint attached to one of its backends is 64. - The maximum number of backend services with fastIPMove in a @@ -18240,7 +18251,7 @@ class FastIPMove(proto.Enum): must belong to that network. However, individual NEGs can belong to different subnetworks of that network. - The maximum number of network endpoints across all backends of a backend service with - fastIPMove is 64. - The maximum number of backend services with + fastIPMove is 32. - The maximum number of backend services with fastIPMove that can have the same network endpoint attached to one of its backends is 64. - The maximum number of backend services with fastIPMove in a VPC in a region is 64. - The network endpoints that @@ -32108,6 +32119,13 @@ class FirewallPolicy(proto.Message): is not applicable to network firewall policies. This field is a member of `oneof`_ ``_parent``. + policy_type (str): + The type of the firewall policy. This field can be either + VPC_POLICY or RDMA_ROCE_POLICY. Note: if not specified then + VPC_POLICY will be used. Check the PolicyType enum for the + list of possible values. + + This field is a member of `oneof`_ ``_policy_type``. region (str): [Output Only] URL of the region where the regional firewall policy resides. This field is not applicable to global @@ -32153,6 +32171,24 @@ class FirewallPolicy(proto.Message): This field is a member of `oneof`_ ``_short_name``. """ + class PolicyType(proto.Enum): + r"""The type of the firewall policy. This field can be either VPC_POLICY + or RDMA_ROCE_POLICY. Note: if not specified then VPC_POLICY will be + used. + + Values: + UNDEFINED_POLICY_TYPE (0): + A value indicating that the enum field is not + set. + RDMA_ROCE_POLICY (148757145): + No description available. + VPC_POLICY (74319208): + No description available. + """ + UNDEFINED_POLICY_TYPE = 0 + RDMA_ROCE_POLICY = 148757145 + VPC_POLICY = 74319208 + associations: MutableSequence["FirewallPolicyAssociation"] = proto.RepeatedField( proto.MESSAGE, number=508736530, @@ -32203,6 +32239,11 @@ class FirewallPolicy(proto.Message): number=78317738, optional=True, ) + policy_type: str = proto.Field( + proto.STRING, + number=18158119, + optional=True, + ) region: str = proto.Field( proto.STRING, number=138946292, @@ -33372,6 +33413,11 @@ class ForwardingRule(proto.Message): [Output Only] Server-defined URL for the resource. This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + [Output Only] Server-defined URL for this resource with the + resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. service_directory_registrations (MutableSequence[google.cloud.compute_v1beta.types.ForwardingRuleServiceDirectoryRegistration]): Service Directory resources to register this forwarding rule with. Currently, only supports a @@ -33780,6 +33826,11 @@ class PscConnectionStatus(proto.Enum): number=456214797, optional=True, ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) service_directory_registrations: MutableSequence[ "ForwardingRuleServiceDirectoryRegistration" ] = proto.RepeatedField( @@ -40051,6 +40102,43 @@ class GetReservationRequest(proto.Message): ) +class GetReservationSubBlockRequest(proto.Message): + r"""A request message for ReservationSubBlocks.Get. See the + method description for details. + + Attributes: + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + project (str): + Project ID for this request. + reservation_sub_block (str): + The name of the reservation subBlock. Name + should conform to RFC1035 or be a resource ID. + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + reservation_sub_block: str = proto.Field( + proto.STRING, + number=22750491, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class GetResourcePolicyRequest(proto.Message): r"""A request message for ResourcePolicies.Get. See the method description for details. @@ -43913,7 +44001,9 @@ class HttpHeaderOption(proto.Message): values that already exist for the header. If true, headerValue is set for the header, discarding any values that were set for that - header. The default value is false. + header. The default value is true, unless a + variable is present in headerValue, in which + case the default value is false. . This field is a member of `oneof`_ ``_replace``. """ @@ -50070,8 +50160,8 @@ class Instance(proto.Message): This field is a member of `oneof`_ ``_machine_type``. metadata (google.cloud.compute_v1beta.types.Metadata): The metadata key/value pairs assigned to this - instance. This includes custom metadata and - predefined keys. + instance. This includes metadata keys that were + explicitly defined for the instance. This field is a member of `oneof`_ ``_metadata``. min_cpu_platform (str): @@ -52054,6 +52144,10 @@ class InstanceGroupManagerInstanceLifecyclePolicy(proto.Message): values. This field is a member of `oneof`_ ``_on_failed_health_check``. + on_repair (google.cloud.compute_v1beta.types.InstanceGroupManagerInstanceLifecyclePolicyOnRepair): + Configuration for VM repairs in the MIG. + + This field is a member of `oneof`_ ``_on_repair``. """ class DefaultActionOnFailure(proto.Enum): @@ -52146,6 +52240,52 @@ class OnFailedHealthCheck(proto.Enum): number=39807943, optional=True, ) + on_repair: "InstanceGroupManagerInstanceLifecyclePolicyOnRepair" = proto.Field( + proto.MESSAGE, + number=371820013, + optional=True, + message="InstanceGroupManagerInstanceLifecyclePolicyOnRepair", + ) + + +class InstanceGroupManagerInstanceLifecyclePolicyOnRepair(proto.Message): + r"""Configuration for VM repairs in the MIG. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_changing_zone (str): + Specifies whether the MIG can change a VM's + zone during a repair. Check the + AllowChangingZone enum for the list of possible + values. + + This field is a member of `oneof`_ ``_allow_changing_zone``. + """ + + class AllowChangingZone(proto.Enum): + r"""Specifies whether the MIG can change a VM's zone during a + repair. + + Values: + UNDEFINED_ALLOW_CHANGING_ZONE (0): + A value indicating that the enum field is not + set. + NO (2497): + [Default] MIG cannot change a VM's zone during a repair. + YES (87751): + MIG can select a different zone for the VM + during a repair. + """ + UNDEFINED_ALLOW_CHANGING_ZONE = 0 + NO = 2497 + YES = 87751 + + allow_changing_zone: str = proto.Field( + proto.STRING, + number=426055112, + optional=True, + ) class InstanceGroupManagerList(proto.Message): @@ -76108,9 +76248,9 @@ class ListReservationBlocksRequest(proto.Message): ) -class ListReservationsRequest(proto.Message): - r"""A request message for Reservations.List. See the method - description for details. +class ListReservationSubBlocksRequest(proto.Message): + r"""A request message for ReservationSubBlocks.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -76188,6 +76328,10 @@ class ListReservationsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} project (str): Project ID for this request. return_partial_success (bool): @@ -76201,7 +76345,8 @@ class ListReservationsRequest(proto.Message): This field is a member of `oneof`_ ``_return_partial_success``. zone (str): - Name of the zone for this request. + Name of the zone for this request. Zone name + should conform to RFC1035. """ filter: str = proto.Field( @@ -76224,6 +76369,10 @@ class ListReservationsRequest(proto.Message): number=19994697, optional=True, ) + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -76239,8 +76388,8 @@ class ListReservationsRequest(proto.Message): ) -class ListResourcePoliciesRequest(proto.Message): - r"""A request message for ResourcePolicies.List. See the method +class ListReservationsRequest(proto.Message): + r"""A request message for Reservations.List. See the method description for details. @@ -76321,8 +76470,6 @@ class ListResourcePoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -76333,6 +76480,8 @@ class ListResourcePoliciesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for this request. """ filter: str = proto.Field( @@ -76359,20 +76508,20 @@ class ListResourcePoliciesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListRoutePoliciesRoutersRequest(proto.Message): - r"""A request message for Routers.ListRoutePolicies. See the - method description for details. +class ListResourcePoliciesRequest(proto.Message): + r"""A request message for ResourcePolicies.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -76464,9 +76613,6 @@ class ListRoutePoliciesRoutersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - router (str): - Name or id of the resource for this request. - Name should conform to RFC1035. """ filter: str = proto.Field( @@ -76502,15 +76648,11 @@ class ListRoutePoliciesRoutersRequest(proto.Message): number=517198390, optional=True, ) - router: str = proto.Field( - proto.STRING, - number=148608841, - ) -class ListRoutersRequest(proto.Message): - r"""A request message for Routers.List. See the method - description for details. +class ListRoutePoliciesRoutersRequest(proto.Message): + r"""A request message for Routers.ListRoutePolicies. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -76602,6 +76744,9 @@ class ListRoutersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + router (str): + Name or id of the resource for this request. + Name should conform to RFC1035. """ filter: str = proto.Field( @@ -76637,11 +76782,15 @@ class ListRoutersRequest(proto.Message): number=517198390, optional=True, ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) -class ListRoutesRequest(proto.Message): - r"""A request message for Routes.List. See the method description - for details. +class ListRoutersRequest(proto.Message): + r"""A request message for Routers.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -76721,6 +76870,8 @@ class ListRoutesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -76757,6 +76908,10 @@ class ListRoutesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -76764,9 +76919,9 @@ class ListRoutesRequest(proto.Message): ) -class ListSecurityPoliciesRequest(proto.Message): - r"""A request message for SecurityPolicies.List. See the method - description for details. +class ListRoutesRequest(proto.Message): + r"""A request message for Routes.List. See the method description + for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -76889,8 +77044,8 @@ class ListSecurityPoliciesRequest(proto.Message): ) -class ListServiceAttachmentsRequest(proto.Message): - r"""A request message for ServiceAttachments.List. See the method +class ListSecurityPoliciesRequest(proto.Message): + r"""A request message for SecurityPolicies.List. See the method description for details. @@ -76971,8 +77126,6 @@ class ListServiceAttachmentsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -77009,10 +77162,6 @@ class ListServiceAttachmentsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -77020,8 +77169,8 @@ class ListServiceAttachmentsRequest(proto.Message): ) -class ListSnapshotsRequest(proto.Message): - r"""A request message for Snapshots.List. See the method +class ListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.List. See the method description for details. @@ -77102,6 +77251,8 @@ class ListSnapshotsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -77138,6 +77289,10 @@ class ListSnapshotsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -77145,8 +77300,8 @@ class ListSnapshotsRequest(proto.Message): ) -class ListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.List. See the method +class ListSnapshotsRequest(proto.Message): + r"""A request message for Snapshots.List. See the method description for details. @@ -77270,8 +77425,8 @@ class ListSslCertificatesRequest(proto.Message): ) -class ListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.List. See the method +class ListSslCertificatesRequest(proto.Message): + r"""A request message for SslCertificates.List. See the method description for details. @@ -77395,8 +77550,8 @@ class ListSslPoliciesRequest(proto.Message): ) -class ListStoragePoolTypesRequest(proto.Message): - r"""A request message for StoragePoolTypes.List. See the method +class ListSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.List. See the method description for details. @@ -77487,8 +77642,6 @@ class ListStoragePoolTypesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -77520,14 +77673,10 @@ class ListStoragePoolTypesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListStoragePoolsRequest(proto.Message): - r"""A request message for StoragePools.List. See the method +class ListStoragePoolTypesRequest(proto.Message): + r"""A request message for StoragePoolTypes.List. See the method description for details. @@ -77657,8 +77806,8 @@ class ListStoragePoolsRequest(proto.Message): ) -class ListSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.List. See the method +class ListStoragePoolsRequest(proto.Message): + r"""A request message for StoragePools.List. See the method description for details. @@ -77739,8 +77888,6 @@ class ListSubnetworksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -77751,6 +77898,8 @@ class ListSubnetworksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -77777,19 +77926,19 @@ class ListSubnetworksRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetGrpcProxiesRequest(proto.Message): - r"""A request message for TargetGrpcProxies.List. See the method +class ListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.List. See the method description for details. @@ -77870,6 +78019,8 @@ class ListTargetGrpcProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -77906,6 +78057,10 @@ class ListTargetGrpcProxiesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -77913,8 +78068,8 @@ class ListTargetGrpcProxiesRequest(proto.Message): ) -class ListTargetHttpProxiesRequest(proto.Message): - r"""A request message for TargetHttpProxies.List. See the method +class ListTargetGrpcProxiesRequest(proto.Message): + r"""A request message for TargetGrpcProxies.List. See the method description for details. @@ -78038,8 +78193,8 @@ class ListTargetHttpProxiesRequest(proto.Message): ) -class ListTargetHttpsProxiesRequest(proto.Message): - r"""A request message for TargetHttpsProxies.List. See the method +class ListTargetHttpProxiesRequest(proto.Message): + r"""A request message for TargetHttpProxies.List. See the method description for details. @@ -78163,8 +78318,8 @@ class ListTargetHttpsProxiesRequest(proto.Message): ) -class ListTargetInstancesRequest(proto.Message): - r"""A request message for TargetInstances.List. See the method +class ListTargetHttpsProxiesRequest(proto.Message): + r"""A request message for TargetHttpsProxies.List. See the method description for details. @@ -78255,8 +78410,6 @@ class ListTargetInstancesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone scoping this request. """ filter: str = proto.Field( @@ -78288,14 +78441,10 @@ class ListTargetInstancesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListTargetPoolsRequest(proto.Message): - r"""A request message for TargetPools.List. See the method +class ListTargetInstancesRequest(proto.Message): + r"""A request message for TargetInstances.List. See the method description for details. @@ -78376,8 +78525,6 @@ class ListTargetPoolsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -78388,6 +78535,8 @@ class ListTargetPoolsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone scoping this request. """ filter: str = proto.Field( @@ -78414,19 +78563,19 @@ class ListTargetPoolsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetSslProxiesRequest(proto.Message): - r"""A request message for TargetSslProxies.List. See the method +class ListTargetPoolsRequest(proto.Message): + r"""A request message for TargetPools.List. See the method description for details. @@ -78507,6 +78656,8 @@ class ListTargetSslProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -78543,6 +78694,10 @@ class ListTargetSslProxiesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -78550,8 +78705,133 @@ class ListTargetSslProxiesRequest(proto.Message): ) -class ListTargetTcpProxiesRequest(proto.Message): - r"""A request message for TargetTcpProxies.List. See the method +class ListTargetSslProxiesRequest(proto.Message): + r"""A request message for TargetSslProxies.List. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + filter (str): + A filter expression that filters resources listed in the + response. Most Compute resources support two types of filter + expressions: expressions that support regular expressions + and expressions that follow API improvement proposal + AIP-160. These two types of filter expressions cannot be + mixed in one request. If you want to use AIP-160, your + expression must specify the field name, an operator, and the + value that you want to use for filtering. The value must be + a string, a number, or a boolean. The operator must be + either ``=``, ``!=``, ``>``, ``<``, ``<=``, ``>=`` or ``:``. + For example, if you are filtering Compute Engine instances, + you can exclude instances named ``example-instance`` by + specifying ``name != example-instance``. The ``:*`` + comparison can be used to test whether a key has been + defined. For example, to find all objects with ``owner`` + label use: ``labels.owner:*`` You can also filter nested + fields. For example, you could specify + ``scheduling.automaticRestart = false`` to include instances + only if they are not scheduled for automatic restarts. You + can use filtering on nested fields to filter based on + resource labels. To filter on multiple expressions, provide + each separate expression within parentheses. For example: + ``(scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake")`` + By default, each expression is an ``AND`` expression. + However, you can include ``AND`` and ``OR`` expressions + explicitly. For example: + ``(cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true)`` + If you want to use a regular expression, use the ``eq`` + (equal) or ``ne`` (not equal) operator against a single + un-parenthesized expression with or without quotes or + against multiple parenthesized expressions. Examples: + ``fieldname eq unquoted literal`` + ``fieldname eq 'single quoted literal'`` + ``fieldname eq "double quoted literal"`` + ``(fieldname1 eq literal) (fieldname2 ne "literal")`` The + literal value is interpreted as a regular expression using + Google RE2 library syntax. The literal value must match the + entire field. For example, to filter for instances that do + not end with name "instance", you would use + ``name ne .*instance``. You cannot combine constraints on + multiple fields using regular expressions. + + This field is a member of `oneof`_ ``_filter``. + max_results (int): + The maximum number of results per page that should be + returned. If the number of available results is larger than + ``maxResults``, Compute Engine returns a ``nextPageToken`` + that can be used to get the next page of results in + subsequent list requests. Acceptable values are ``0`` to + ``500``, inclusive. (Default: ``500``) + + This field is a member of `oneof`_ ``_max_results``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. You can also sort results in descending order based on + the creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. For example, when + partial success behavior is enabled, + aggregatedList for a single zone scope either + returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListTargetTcpProxiesRequest(proto.Message): + r"""A request message for TargetTcpProxies.List. See the method description for details. @@ -101722,8 +102002,9 @@ class Reservation(proto.Message): This field is a member of `oneof`_ ``_description``. enable_emergent_maintenance (bool): - Indicates if this group of VMs have emergent - maintenance enabled. + Indicates whether Compute Engine allows + unplanned maintenance for your VMs; for example, + to fix hardware errors. This field is a member of `oneof`_ ``_enable_emergent_maintenance``. id (int): @@ -102234,6 +102515,17 @@ class ReservationBlock(proto.Message): block. This field is a member of `oneof`_ ``_reservation_maintenance``. + reservation_sub_block_count (int): + [Output Only] The number of reservation subBlocks associated + with this reservation block. + + This field is a member of `oneof`_ ``_reservation_sub_block_count``. + reservation_sub_block_in_use_count (int): + [Output Only] The number of in-use reservation subBlocks + associated with this reservation block. If at least one VM + is running on a subBlock, it is considered in-use. + + This field is a member of `oneof`_ ``_reservation_sub_block_in_use_count``. self_link (str): [Output Only] Server-defined fully-qualified URL for this resource. @@ -102321,6 +102613,16 @@ class Status(proto.Enum): optional=True, message="GroupMaintenanceInfo", ) + reservation_sub_block_count: int = proto.Field( + proto.INT32, + number=330782955, + optional=True, + ) + reservation_sub_block_in_use_count: int = proto.Field( + proto.INT32, + number=186007137, + optional=True, + ) self_link: str = proto.Field( proto.STRING, number=456214797, @@ -102541,6 +102843,287 @@ def raw_page(self): ) +class ReservationSubBlock(proto.Message): + r"""Represents a reservation subBlock resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + count (int): + [Output Only] The number of hosts that are allocated in this + reservation subBlock. + + This field is a member of `oneof`_ ``_count``. + creation_timestamp (str): + [Output Only] Creation timestamp in RFC3339 text format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + id (int): + [Output Only] The unique identifier for the resource. This + identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + in_use_count (int): + [Output Only] The number of instances that are currently in + use on this reservation subBlock. + + This field is a member of `oneof`_ ``_in_use_count``. + kind (str): + [Output Only] Type of the resource. Always + compute#reservationSubBlock for reservation subBlocks. + + This field is a member of `oneof`_ ``_kind``. + name (str): + [Output Only] The name of this reservation subBlock + generated by Google Compute Engine. The name must be 1-63 + characters long, and comply with RFC1035 @pattern + `a-z `__? + + This field is a member of `oneof`_ ``_name``. + physical_topology (google.cloud.compute_v1beta.types.ReservationSubBlockPhysicalTopology): + [Output Only] The physical topology of the reservation + subBlock. + + This field is a member of `oneof`_ ``_physical_topology``. + self_link (str): + [Output Only] Server-defined fully-qualified URL for this + resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + [Output Only] Server-defined URL for this resource with the + resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + status (str): + [Output Only] Status of the reservation subBlock. Check the + Status enum for the list of possible values. + + This field is a member of `oneof`_ ``_status``. + zone (str): + [Output Only] Zone in which the reservation subBlock + resides. + + This field is a member of `oneof`_ ``_zone``. + """ + + class Status(proto.Enum): + r"""[Output Only] Status of the reservation subBlock. + + Values: + UNDEFINED_STATUS (0): + A value indicating that the enum field is not + set. + CREATING (455564985): + Resources are being allocated for the + reservation subBlock. + DELETING (528602024): + Reservation subBlock is currently being + deleted. + INVALID (530283991): + No description available. + READY (77848963): + Reservation subBlock has allocated all its + resources. + """ + UNDEFINED_STATUS = 0 + CREATING = 455564985 + DELETING = 528602024 + INVALID = 530283991 + READY = 77848963 + + count: int = proto.Field( + proto.INT32, + number=94851343, + optional=True, + ) + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + in_use_count: int = proto.Field( + proto.INT32, + number=493458877, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + physical_topology: "ReservationSubBlockPhysicalTopology" = proto.Field( + proto.MESSAGE, + number=279778519, + optional=True, + message="ReservationSubBlockPhysicalTopology", + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + status: str = proto.Field( + proto.STRING, + number=181260274, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class ReservationSubBlockPhysicalTopology(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + block (str): + The hash of the capacity block within the + cluster. + + This field is a member of `oneof`_ ``_block``. + cluster (str): + The cluster name of the reservation subBlock. + + This field is a member of `oneof`_ ``_cluster``. + sub_block (str): + The hash of the capacity sub-block within the + capacity block. + + This field is a member of `oneof`_ ``_sub_block``. + """ + + block: str = proto.Field( + proto.STRING, + number=93832333, + optional=True, + ) + cluster: str = proto.Field( + proto.STRING, + number=335221242, + optional=True, + ) + sub_block: str = proto.Field( + proto.STRING, + number=478033358, + optional=True, + ) + + +class ReservationSubBlocksGetResponse(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + resource (google.cloud.compute_v1beta.types.ReservationSubBlock): + + This field is a member of `oneof`_ ``_resource``. + """ + + resource: "ReservationSubBlock" = proto.Field( + proto.MESSAGE, + number=195806222, + optional=True, + message="ReservationSubBlock", + ) + + +class ReservationSubBlocksListResponse(proto.Message): + r"""A list of reservation subBlocks under a single reservation. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + Unique identifier for the resource; defined + by the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1beta.types.ReservationSubBlock]): + A list of reservation subBlock resources. + kind (str): + Type of the resource. Always + compute#reservationSubBlock for a list of + reservation subBlocks. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + This token allows you to get the next page of + results for list requests. If the number of + results is larger than maxResults, use the + nextPageToken as a value for the query parameter + pageToken in the next list request. Subsequent + list requests will have their own nextPageToken + to continue paging through the results. + + This field is a member of `oneof`_ ``_next_page_token``. + self_link (str): + Server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + warning (google.cloud.compute_v1beta.types.Warning): + Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["ReservationSubBlock"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="ReservationSubBlock", + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class ReservationsBlocksPerformMaintenanceRequest(proto.Message): r""" @@ -105593,6 +106176,11 @@ class Router(proto.Message): belongs. This field is a member of `oneof`_ ``_network``. + params (google.cloud.compute_v1beta.types.RouterParams): + Input only. [Input Only] Additional params passed with the + request, but not persisted as part of resource payload. + + This field is a member of `oneof`_ ``_params``. region (str): [Output Only] URI of the region where the router resides. You must specify this field as part of the HTTP request URL. @@ -105673,6 +106261,12 @@ class Router(proto.Message): number=232872494, optional=True, ) + params: "RouterParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="RouterParams", + ) region: str = proto.Field( proto.STRING, number=138946292, @@ -107401,6 +107995,33 @@ class RouterNatSubnetworkToNat64(proto.Message): ) +class RouterParams(proto.Message): + r"""Additional router parameters. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Tag keys/values directly bound to this resource. Tag keys + and values have the same definition as resource manager + tags. The field is allowed for INSERT only. The keys/values + to set on the resource should be specified in either ID { : + } or Namespaced format { : }. For example the following are + valid inputs: \* {"tagKeys/333" : "tagValues/444", + "tagKeys/123" : "tagValues/456"} \* {"123/environment" : + "production", "345/abc" : "xyz"} Note: \* Invalid + combinations of ID & namespaced format is not supported. For + instance: {"123/environment" : "tagValues/444"} is invalid. + \* Inconsistent format is not supported. For instance: + {"tagKeys/333" : "tagValues/444", "123/env" : "prod"} is + invalid. + """ + + resource_manager_tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class RouterStatus(proto.Message): r""" @@ -108845,6 +109466,13 @@ class Scheduling(proto.Message): the list of possible values. This field is a member of `oneof`_ ``_provisioning_model``. + skip_guest_os_shutdown (bool): + Default is false and there will be 120 + seconds between GCE ACPI G2 Soft Off and ACPI G3 + Mechanical Off for Standard VMs and 30 seconds + for Spot VMs. + + This field is a member of `oneof`_ ``_skip_guest_os_shutdown``. termination_time (str): Specifies the timestamp, when the instance will be terminated, in RFC3339 text format. If @@ -109048,6 +109676,11 @@ class ProvisioningModel(proto.Enum): number=494423, optional=True, ) + skip_guest_os_shutdown: bool = proto.Field( + proto.BOOL, + number=201662378, + optional=True, + ) termination_time: str = proto.Field( proto.STRING, number=428082984, @@ -134156,6 +134789,11 @@ class VpnTunnel(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + cipher_suite (google.cloud.compute_v1beta.types.VpnTunnelCipherSuite): + User specified list of ciphers to use for the + phase 1 and phase 2 of the IKE protocol. + + This field is a member of `oneof`_ ``_cipher_suite``. creation_timestamp (str): [Output Only] Creation timestamp in RFC3339 text format. @@ -134421,6 +135059,12 @@ class Status(proto.Enum): STOPPED = 444276141 WAITING_FOR_FULL_CONFIG = 41640522 + cipher_suite: "VpnTunnelCipherSuite" = proto.Field( + proto.MESSAGE, + number=443788228, + optional=True, + message="VpnTunnelCipherSuite", + ) creation_timestamp: str = proto.Field( proto.STRING, number=30525366, @@ -134622,6 +135266,34 @@ def raw_page(self): ) +class VpnTunnelCipherSuite(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + phase1 (google.cloud.compute_v1beta.types.VpnTunnelPhase1Algorithms): + + This field is a member of `oneof`_ ``_phase1``. + phase2 (google.cloud.compute_v1beta.types.VpnTunnelPhase2Algorithms): + + This field is a member of `oneof`_ ``_phase2``. + """ + + phase1: "VpnTunnelPhase1Algorithms" = proto.Field( + proto.MESSAGE, + number=84289046, + optional=True, + message="VpnTunnelPhase1Algorithms", + ) + phase2: "VpnTunnelPhase2Algorithms" = proto.Field( + proto.MESSAGE, + number=84289047, + optional=True, + message="VpnTunnelPhase2Algorithms", + ) + + class VpnTunnelList(proto.Message): r"""Contains a list of VpnTunnel resources. @@ -134696,6 +135368,64 @@ def raw_page(self): ) +class VpnTunnelPhase1Algorithms(proto.Message): + r""" + + Attributes: + dh (MutableSequence[str]): + + encryption (MutableSequence[str]): + + integrity (MutableSequence[str]): + + prf (MutableSequence[str]): + + """ + + dh: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3204, + ) + encryption: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=97980291, + ) + integrity: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=492830541, + ) + prf: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=111268, + ) + + +class VpnTunnelPhase2Algorithms(proto.Message): + r""" + + Attributes: + encryption (MutableSequence[str]): + + integrity (MutableSequence[str]): + + pfs (MutableSequence[str]): + + """ + + encryption: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=97980291, + ) + integrity: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=492830541, + ) + pfs: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=110909, + ) + + class VpnTunnelsScopedList(proto.Message): r""" @@ -135424,6 +136154,11 @@ class WireGroup(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + reconciling (bool): + [Output Only] Indicates whether there are wire changes yet + to be processed. + + This field is a member of `oneof`_ ``_reconciling``. self_link (str): [Output Only] Server-defined URL for the resource. @@ -135482,6 +136217,11 @@ class WireGroup(proto.Message): number=3373707, optional=True, ) + reconciling: bool = proto.Field( + proto.BOOL, + number=432155787, + optional=True, + ) self_link: str = proto.Field( proto.STRING, number=456214797, diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_get_sync.py new file mode 100644 index 000000000000..d0a338741dcc --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_get_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 Get +# 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-compute-v1beta + + +# [START compute_v1beta_generated_ReservationSubBlocks_Get_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 compute_v1beta + + +def sample_get(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.GetReservationSubBlockRequest( + parent_name="parent_name_value", + project="project_value", + reservation_sub_block="reservation_sub_block_value", + zone="zone_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + +# [END compute_v1beta_generated_ReservationSubBlocks_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_list_sync.py new file mode 100644 index 000000000000..5e08687bec9c --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reservation_sub_blocks_list_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 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 List +# 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-compute-v1beta + + +# [START compute_v1beta_generated_ReservationSubBlocks_List_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 compute_v1beta + + +def sample_list(): + # Create a client + client = compute_v1beta.ReservationSubBlocksClient() + + # Initialize request argument(s) + request = compute_v1beta.ListReservationSubBlocksRequest( + parent_name="parent_name_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END compute_v1beta_generated_ReservationSubBlocks_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json index 80acd52af9a5..c97c7c106539 100644 --- a/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/snippet_metadata_google.cloud.compute.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-compute-v1beta", - "version": "0.1.1" + "version": "0.1.0" }, "snippets": [ { @@ -62683,6 +62683,186 @@ ], "title": "compute_v1beta_generated_reservation_blocks_perform_maintenance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ReservationSubBlocksClient", + "shortName": "ReservationSubBlocksClient" + }, + "fullName": "google.cloud.compute_v1beta.ReservationSubBlocksClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.ReservationSubBlocks.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "shortName": "ReservationSubBlocks" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetReservationSubBlockRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "parent_name", + "type": "str" + }, + { + "name": "reservation_sub_block", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.types.ReservationSubBlocksGetResponse", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_reservation_sub_blocks_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_ReservationSubBlocks_Get_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 48, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 51, + "start": 49, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 52, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_reservation_sub_blocks_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ReservationSubBlocksClient", + "shortName": "ReservationSubBlocksClient" + }, + "fullName": "google.cloud.compute_v1beta.ReservationSubBlocksClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.ReservationSubBlocks.List", + "service": { + "fullName": "google.cloud.compute.v1beta.ReservationSubBlocks", + "shortName": "ReservationSubBlocks" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListReservationSubBlocksRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "zone", + "type": "str" + }, + { + "name": "parent_name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.compute_v1beta.services.reservation_sub_blocks.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_reservation_sub_blocks_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_ReservationSubBlocks_List_sync", + "segments": [ + { + "end": 54, + "start": 27, + "type": "FULL" + }, + { + "end": 54, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 47, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 50, + "start": 48, + "type": "REQUEST_EXECUTION" + }, + { + "end": 55, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_reservation_sub_blocks_list_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_firewall_policies.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_firewall_policies.py index f9b35c1cc28c..e23c36fdc3bf 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_firewall_policies.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_firewall_policies.py @@ -9050,6 +9050,7 @@ def test_get_rest_call_success(request_type): kind="kind_value", name="name_value", parent="parent_value", + policy_type="policy_type_value", region="region_value", rule_tuple_count=1737, self_link="self_link_value", @@ -9079,6 +9080,7 @@ def test_get_rest_call_success(request_type): assert response.kind == "kind_value" assert response.name == "name_value" assert response.parent == "parent_value" + assert response.policy_type == "policy_type_value" assert response.region == "region_value" assert response.rule_tuple_count == 1737 assert response.self_link == "self_link_value" @@ -9844,6 +9846,7 @@ def test_insert_rest_call_success(request_type): } ], "parent": "parent_value", + "policy_type": "policy_type_value", "region": "region_value", "rule_tuple_count": 1737, "rules": {}, @@ -10606,6 +10609,7 @@ def test_patch_rest_call_success(request_type): } ], "parent": "parent_value", + "policy_type": "policy_type_value", "region": "region_value", "rule_tuple_count": 1737, "rules": {}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_forwarding_rules.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_forwarding_rules.py index a8379f478ad9..1a1b90730bca 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_forwarding_rules.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_forwarding_rules.py @@ -4525,6 +4525,7 @@ def test_get_rest_call_success(request_type): psc_connection_status="psc_connection_status_value", region="region_value", self_link="self_link_value", + self_link_with_id="self_link_with_id_value", service_label="service_label_value", service_name="service_name_value", source_ip_ranges=["source_ip_ranges_value"], @@ -4583,6 +4584,7 @@ def test_get_rest_call_success(request_type): assert response.psc_connection_status == "psc_connection_status_value" assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" assert response.service_label == "service_label_value" assert response.service_name == "service_name_value" assert response.source_ip_ranges == ["source_ip_ranges_value"] @@ -4727,6 +4729,7 @@ def test_insert_rest_call_success(request_type): "psc_connection_status": "psc_connection_status_value", "region": "region_value", "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", "service_directory_registrations": [ { "namespace": "namespace_value", @@ -5155,6 +5158,7 @@ def test_patch_rest_call_success(request_type): "psc_connection_status": "psc_connection_status_value", "region": "region_value", "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", "service_directory_registrations": [ { "namespace": "namespace_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_forwarding_rules.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_forwarding_rules.py index aa27d62436dd..630a79c475af 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_forwarding_rules.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_global_forwarding_rules.py @@ -3992,6 +3992,7 @@ def test_get_rest_call_success(request_type): psc_connection_status="psc_connection_status_value", region="region_value", self_link="self_link_value", + self_link_with_id="self_link_with_id_value", service_label="service_label_value", service_name="service_name_value", source_ip_ranges=["source_ip_ranges_value"], @@ -4050,6 +4051,7 @@ def test_get_rest_call_success(request_type): assert response.psc_connection_status == "psc_connection_status_value" assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" assert response.service_label == "service_label_value" assert response.service_name == "service_name_value" assert response.source_ip_ranges == ["source_ip_ranges_value"] @@ -4196,6 +4198,7 @@ def test_insert_rest_call_success(request_type): "psc_connection_status": "psc_connection_status_value", "region": "region_value", "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", "service_directory_registrations": [ { "namespace": "namespace_value", @@ -4616,6 +4619,7 @@ def test_patch_rest_call_success(request_type): "psc_connection_status": "psc_connection_status_value", "region": "region_value", "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", "service_directory_registrations": [ { "namespace": "namespace_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py index 5358145de157..3d6586481928 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py @@ -14123,6 +14123,7 @@ def test_insert_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -15078,6 +15079,7 @@ def test_patch_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -18508,6 +18510,7 @@ def test_update_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py index 305378bcaab0..18c41c9b6735 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_templates.py @@ -3984,6 +3984,7 @@ def test_insert_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "service_accounts": [ diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py index 1338866ecf74..99e0966c10ae 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instances.py @@ -24182,6 +24182,7 @@ def test_bulk_insert_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "service_accounts": [ @@ -26535,6 +26536,7 @@ def test_insert_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "self_link": "self_link_value", @@ -30608,6 +30610,7 @@ def test_set_scheduling_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -33426,6 +33429,7 @@ def test_update_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "self_link": "self_link_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py index 309e729be66f..a91c176a06b6 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_machine_images.py @@ -3964,6 +3964,7 @@ def test_insert_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "service_accounts": [ diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_network_firewall_policies.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_network_firewall_policies.py index 9d99a63fba1e..3210974125ab 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_network_firewall_policies.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_network_firewall_policies.py @@ -9498,6 +9498,7 @@ def test_get_rest_call_success(request_type): kind="kind_value", name="name_value", parent="parent_value", + policy_type="policy_type_value", region="region_value", rule_tuple_count=1737, self_link="self_link_value", @@ -9527,6 +9528,7 @@ def test_get_rest_call_success(request_type): assert response.kind == "kind_value" assert response.name == "name_value" assert response.parent == "parent_value" + assert response.policy_type == "policy_type_value" assert response.region == "region_value" assert response.rule_tuple_count == 1737 assert response.self_link == "self_link_value" @@ -10300,6 +10302,7 @@ def test_insert_rest_call_success(request_type): } ], "parent": "parent_value", + "policy_type": "policy_type_value", "region": "region_value", "rule_tuple_count": 1737, "rules": {}, @@ -10762,6 +10765,7 @@ def test_patch_rest_call_success(request_type): } ], "parent": "parent_value", + "policy_type": "policy_type_value", "region": "region_value", "rule_tuple_count": 1737, "rules": {}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py index 47d6d3730632..9179d6d46fe9 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py @@ -13738,6 +13738,7 @@ def test_insert_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -14708,6 +14709,7 @@ def test_patch_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -18154,6 +18156,7 @@ def test_update_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py index 69bfa6867c15..2954318653fe 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_templates.py @@ -2938,6 +2938,7 @@ def test_insert_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "service_accounts": [ diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py index edb421c36482..2d99311c7d8c 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instances.py @@ -1681,6 +1681,7 @@ def test_bulk_insert_rest_call_success(request_type): "on_instance_stop_action": {"discard_local_ssd": True}, "preemptible": True, "provisioning_model": "provisioning_model_value", + "skip_guest_os_shutdown": True, "termination_time": "termination_time_value", }, "service_accounts": [ diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_firewall_policies.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_firewall_policies.py index 92e9dc388712..a54053d93f1d 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_firewall_policies.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_network_firewall_policies.py @@ -8256,6 +8256,7 @@ def test_get_rest_call_success(request_type): kind="kind_value", name="name_value", parent="parent_value", + policy_type="policy_type_value", region="region_value", rule_tuple_count=1737, self_link="self_link_value", @@ -8285,6 +8286,7 @@ def test_get_rest_call_success(request_type): assert response.kind == "kind_value" assert response.name == "name_value" assert response.parent == "parent_value" + assert response.policy_type == "policy_type_value" assert response.region == "region_value" assert response.rule_tuple_count == 1737 assert response.self_link == "self_link_value" @@ -9066,6 +9068,7 @@ def test_insert_rest_call_success(request_type): } ], "parent": "parent_value", + "policy_type": "policy_type_value", "region": "region_value", "rule_tuple_count": 1737, "rules": {}, @@ -9542,6 +9545,7 @@ def test_patch_rest_call_success(request_type): } ], "parent": "parent_value", + "policy_type": "policy_type_value", "region": "region_value", "rule_tuple_count": 1737, "rules": {}, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py new file mode 100644 index 000000000000..0e233cf50a2f --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_sub_blocks.py @@ -0,0 +1,2243 @@ +# -*- coding: utf-8 -*- +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +import os + +# try/except added for compatibility with python < 3.8 +try: + from unittest import mock + from unittest.mock import AsyncMock # pragma: NO COVER +except ImportError: # pragma: NO COVER + import mock + +from collections.abc import AsyncIterable, Iterable +import json +import math + +from google.api_core import api_core_version +from google.protobuf import json_format +import grpc +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +import pytest +from requests import PreparedRequest, Request, Response +from requests.sessions import Session + +try: + from google.auth.aio import credentials as ga_credentials_async + + HAS_GOOGLE_AUTH_AIO = True +except ImportError: # pragma: NO COVER + HAS_GOOGLE_AUTH_AIO = False + +from google.api_core import gapic_v1, grpc_helpers, grpc_helpers_async, path_template +from google.api_core import client_options +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +import google.auth +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.reservation_sub_blocks import ( + ReservationSubBlocksClient, + pagers, + transports, +) +from google.cloud.compute_v1beta.types import compute + +CRED_INFO_JSON = { + "credential_source": "/path/to/file", + "credential_type": "service account credentials", + "principal": "service-account@example.com", +} +CRED_INFO_STRING = json.dumps(CRED_INFO_JSON) + + +async def mock_async_gen(data, chunk_size=1): + for i in range(0, len(data)): # pragma: NO COVER + chunk = data[i : i + chunk_size] + yield chunk.encode("utf-8") + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# TODO: use async auth anon credentials by default once the minimum version of google-auth is upgraded. +# See related issue: https://github.com/googleapis/gapic-generator-python/issues/2107. +def async_anonymous_credentials(): + if HAS_GOOGLE_AUTH_AIO: + return ga_credentials_async.AnonymousCredentials() + return ga_credentials.AnonymousCredentials() + + +# If default endpoint is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +# If default endpoint template is localhost, then default mtls endpoint will be the same. +# This method modifies the default endpoint template so the client can produce a different +# mtls endpoint for endpoint testing purposes. +def modify_default_endpoint_template(client): + return ( + "test.{UNIVERSE_DOMAIN}" + if ("localhost" in client._DEFAULT_ENDPOINT_TEMPLATE) + else client._DEFAULT_ENDPOINT_TEMPLATE + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert ReservationSubBlocksClient._get_default_mtls_endpoint(None) is None + assert ( + ReservationSubBlocksClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ReservationSubBlocksClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ReservationSubBlocksClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ReservationSubBlocksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ReservationSubBlocksClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert ReservationSubBlocksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ReservationSubBlocksClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ReservationSubBlocksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + ReservationSubBlocksClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ReservationSubBlocksClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ReservationSubBlocksClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ReservationSubBlocksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ReservationSubBlocksClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + with mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}): + assert ReservationSubBlocksClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert ReservationSubBlocksClient._get_client_cert_source(None, False) is None + assert ( + ReservationSubBlocksClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + ReservationSubBlocksClient._get_client_cert_source( + mock_provided_cert_source, True + ) + == mock_provided_cert_source + ) + + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", return_value=True + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_default_cert_source, + ): + assert ( + ReservationSubBlocksClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ReservationSubBlocksClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ReservationSubBlocksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReservationSubBlocksClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ReservationSubBlocksClient._DEFAULT_UNIVERSE + default_endpoint = ReservationSubBlocksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ReservationSubBlocksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ReservationSubBlocksClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ReservationSubBlocksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ReservationSubBlocksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ReservationSubBlocksClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + ReservationSubBlocksClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == ReservationSubBlocksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ReservationSubBlocksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ReservationSubBlocksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ReservationSubBlocksClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ReservationSubBlocksClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ReservationSubBlocksClient._get_api_endpoint( + None, mock_client_cert_source, mock_universe, "auto" + ) + assert ( + str(excinfo.value) + == "mTLS is not supported in any universe other than googleapis.com." + ) + + +def test__get_universe_domain(): + client_universe_domain = "foo.com" + universe_domain_env = "bar.com" + + assert ( + ReservationSubBlocksClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ReservationSubBlocksClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ReservationSubBlocksClient._get_universe_domain(None, None) + == ReservationSubBlocksClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ReservationSubBlocksClient._get_universe_domain("", None) + assert str(excinfo.value) == "Universe Domain cannot be an empty string." + + +@pytest.mark.parametrize( + "error_code,cred_info_json,show_cred_info", + [ + (401, CRED_INFO_JSON, True), + (403, CRED_INFO_JSON, True), + (404, CRED_INFO_JSON, True), + (500, CRED_INFO_JSON, False), + (401, None, False), + (403, None, False), + (404, None, False), + (500, None, False), + ], +) +def test__add_cred_info_for_auth_errors(error_code, cred_info_json, show_cred_info): + cred = mock.Mock(["get_cred_info"]) + cred.get_cred_info = mock.Mock(return_value=cred_info_json) + client = ReservationSubBlocksClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=["foo"]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + if show_cred_info: + assert error.details == ["foo", CRED_INFO_STRING] + else: + assert error.details == ["foo"] + + +@pytest.mark.parametrize("error_code", [401, 403, 404, 500]) +def test__add_cred_info_for_auth_errors_no_get_cred_info(error_code): + cred = mock.Mock([]) + assert not hasattr(cred, "get_cred_info") + client = ReservationSubBlocksClient(credentials=cred) + client._transport._credentials = cred + + error = core_exceptions.GoogleAPICallError("message", details=[]) + error.code = error_code + + client._add_cred_info_for_auth_errors(error) + assert error.details == [] + + +@pytest.mark.parametrize( + "client_class,transport_name", + [ + (ReservationSubBlocksClient, "rest"), + ], +) +def test_reservation_sub_blocks_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 == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_class,transport_name", + [ + (transports.ReservationSubBlocksRestTransport, "rest"), + ], +) +def test_reservation_sub_blocks_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", + [ + (ReservationSubBlocksClient, "rest"), + ], +) +def test_reservation_sub_blocks_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 == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +def test_reservation_sub_blocks_client_get_transport_class(): + transport = ReservationSubBlocksClient.get_transport_class() + available_transports = [ + transports.ReservationSubBlocksRestTransport, + ] + assert transport in available_transports + + transport = ReservationSubBlocksClient.get_transport_class("rest") + assert transport == transports.ReservationSubBlocksRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + ReservationSubBlocksClient, + transports.ReservationSubBlocksRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + ReservationSubBlocksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReservationSubBlocksClient), +) +def test_reservation_sub_blocks_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(ReservationSubBlocksClient, "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(ReservationSubBlocksClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name, client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client = client_class(transport=transport_name) + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + # Check the case api_endpoint is provided + options = client_options.ClientOptions( + api_audience="https://language.googleapis.com" + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience="https://language.googleapis.com", + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + ReservationSubBlocksClient, + transports.ReservationSubBlocksRestTransport, + "rest", + "true", + ), + ( + ReservationSubBlocksClient, + transports.ReservationSubBlocksRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + ReservationSubBlocksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReservationSubBlocksClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_reservation_sub_blocks_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + + if use_client_cert_env == "false": + expected_client_cert_source = None + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + else: + expected_client_cert_source = client_cert_source_callback + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=client_cert_source_callback, + ): + if use_client_cert_env == "false": + expected_host = client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ) + expected_client_cert_source = None + else: + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_client_cert_source = client_cert_source_callback + + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + client_cert_source_for_mtls=expected_client_cert_source, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + patched.return_value = None + client = client_class(transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize("client_class", [ReservationSubBlocksClient]) +@mock.patch.object( + ReservationSubBlocksClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ReservationSubBlocksClient), +) +def test_reservation_sub_blocks_client_get_mtls_endpoint_and_cert_source(client_class): + mock_client_cert_source = mock.Mock() + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source == mock_client_cert_source + + # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + mock_client_cert_source = mock.Mock() + mock_api_endpoint = "foo" + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint + ) + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( + options + ) + assert api_endpoint == mock_api_endpoint + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=False, + ): + api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_ENDPOINT + assert cert_source is None + + # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.mtls.has_default_client_cert_source", + return_value=True, + ): + with mock.patch( + "google.auth.transport.mtls.default_client_cert_source", + return_value=mock_client_cert_source, + ): + ( + api_endpoint, + cert_source, + ) = client_class.get_mtls_endpoint_and_cert_source() + assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + assert cert_source == mock_client_cert_source + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" + ) + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError) as excinfo: + client_class.get_mtls_endpoint_and_cert_source() + + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + + +@pytest.mark.parametrize("client_class", [ReservationSubBlocksClient]) +@mock.patch.object( + ReservationSubBlocksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReservationSubBlocksClient), +) +def test_reservation_sub_blocks_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ReservationSubBlocksClient._DEFAULT_UNIVERSE + default_endpoint = ReservationSubBlocksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ReservationSubBlocksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + # If ClientOptions.api_endpoint is set and GOOGLE_API_USE_CLIENT_CERTIFICATE="true", + # use ClientOptions.api_endpoint as the api endpoint regardless. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ): + options = client_options.ClientOptions( + client_cert_source=mock_client_cert_source, api_endpoint=api_override + ) + client = client_class( + client_options=options, + credentials=ga_credentials.AnonymousCredentials(), + ) + assert client.api_endpoint == api_override + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == default_endpoint + + # If ClientOptions.api_endpoint is not set and GOOGLE_API_USE_MTLS_ENDPOINT="always", + # use the DEFAULT_MTLS_ENDPOINT as the api endpoint. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + client = client_class(credentials=ga_credentials.AnonymousCredentials()) + assert client.api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT + + # If ClientOptions.api_endpoint is not set, GOOGLE_API_USE_MTLS_ENDPOINT="auto" (default), + # GOOGLE_API_USE_CLIENT_CERTIFICATE="false" (default), default cert source doesn't exist, + # and ClientOptions.universe_domain="bar.com", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with universe domain as the api endpoint. + options = client_options.ClientOptions() + universe_exists = hasattr(options, "universe_domain") + if universe_exists: + options = client_options.ClientOptions(universe_domain=mock_universe) + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + else: + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == ( + mock_endpoint if universe_exists else default_endpoint + ) + assert client.universe_domain == ( + mock_universe if universe_exists else default_universe + ) + + # If ClientOptions does not have a universe domain attribute and GOOGLE_API_USE_MTLS_ENDPOINT="never", + # use the _DEFAULT_ENDPOINT_TEMPLATE populated with GDU as the api endpoint. + options = client_options.ClientOptions() + if hasattr(options, "universe_domain"): + delattr(options, "universe_domain") + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + client = client_class( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + assert client.api_endpoint == default_endpoint + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + ReservationSubBlocksClient, + transports.ReservationSubBlocksRestTransport, + "rest", + ), + ], +) +def test_reservation_sub_blocks_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions( + scopes=["1", "2"], + ) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=["1", "2"], + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,grpc_helpers", + [ + ( + ReservationSubBlocksClient, + transports.ReservationSubBlocksRestTransport, + "rest", + None, + ), + ], +) +def test_reservation_sub_blocks_client_client_options_credentials_file( + client_class, transport_class, transport_name, grpc_helpers +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options, transport=transport_name) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) + + +def test_get_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc + + request = {} + client.get(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_get_rest_required_fields(request_type=compute.GetReservationSubBlockRequest): + transport_class = transports.ReservationSubBlocksRestTransport + + request_init = {} + request_init["parent_name"] = "" + request_init["project"] = "" + request_init["reservation_sub_block"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parentName"] = "parent_name_value" + jsonified_request["project"] = "project_value" + jsonified_request["reservationSubBlock"] = "reservation_sub_block_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parentName" in jsonified_request + assert jsonified_request["parentName"] == "parent_name_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "reservationSubBlock" in jsonified_request + assert jsonified_request["reservationSubBlock"] == "reservation_sub_block_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ReservationSubBlocksGetResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ReservationSubBlocksGetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_rest_unset_required_fields(): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parentName", + "project", + "reservationSubBlock", + "zone", + ) + ) + ) + + +def test_get_rest_flattened(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ReservationSubBlocksGetResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.ReservationSubBlocksGetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks/{reservation_sub_block}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get( + compute.GetReservationSubBlockRequest(), + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + reservation_sub_block="reservation_sub_block_value", + ) + + +def test_list_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.list] = mock_rpc + + request = {} + client.list(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_list_rest_required_fields( + request_type=compute.ListReservationSubBlocksRequest, +): + transport_class = transports.ReservationSubBlocksRestTransport + + request_init = {} + request_init["parent_name"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parentName"] = "parent_name_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parentName" in jsonified_request + assert jsonified_request["parentName"] == "parent_name_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ReservationSubBlocksListResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ReservationSubBlocksListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_rest_unset_required_fields(): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "parentName", + "project", + "zone", + ) + ) + ) + + +def test_list_rest_flattened(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ReservationSubBlocksListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.ReservationSubBlocksListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/zones/{zone}/{parent_name}/reservationSubBlocks" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list( + compute.ListReservationSubBlocksRequest(), + project="project_value", + zone="zone_value", + parent_name="parent_name_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + compute.ReservationSubBlocksListResponse( + items=[ + compute.ReservationSubBlock(), + compute.ReservationSubBlock(), + compute.ReservationSubBlock(), + ], + next_page_token="abc", + ), + compute.ReservationSubBlocksListResponse( + items=[], + next_page_token="def", + ), + compute.ReservationSubBlocksListResponse( + items=[ + compute.ReservationSubBlock(), + ], + next_page_token="ghi", + ), + compute.ReservationSubBlocksListResponse( + items=[ + compute.ReservationSubBlock(), + compute.ReservationSubBlock(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.ReservationSubBlocksListResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + } + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.ReservationSubBlock) for i in results) + + pages = list(client.list(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReservationSubBlocksClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReservationSubBlocksClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReservationSubBlocksClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReservationSubBlocksClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReservationSubBlocksClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ReservationSubBlocksRestTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_kind_rest(): + transport = ReservationSubBlocksClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetReservationSubBlockRequest): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetReservationSubBlockRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "parent_name": "sample3", + "reservation_sub_block": "sample4", + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ReservationSubBlocksGetResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ReservationSubBlocksGetResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.get(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.ReservationSubBlocksGetResponse) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationSubBlocksRestInterceptor(), + ) + client = ReservationSubBlocksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetReservationSubBlockRequest.pb( + compute.GetReservationSubBlockRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.ReservationSubBlocksGetResponse.to_json( + compute.ReservationSubBlocksGetResponse() + ) + req.return_value.content = return_value + + request = compute.GetReservationSubBlockRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ReservationSubBlocksGetResponse() + post_with_metadata.return_value = ( + compute.ReservationSubBlocksGetResponse(), + metadata, + ) + + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_rest_bad_request(request_type=compute.ListReservationSubBlocksRequest): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "parent_name": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListReservationSubBlocksRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "parent_name": "sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ReservationSubBlocksListResponse( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.ReservationSubBlocksListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListPager) + assert response.id == "id_value" + assert response.kind == "kind_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.ReservationSubBlocksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReservationSubBlocksRestInterceptor(), + ) + client = ReservationSubBlocksClient(transport=transport) + + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.ReservationSubBlocksRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListReservationSubBlocksRequest.pb( + compute.ListReservationSubBlocksRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + return_value = compute.ReservationSubBlocksListResponse.to_json( + compute.ReservationSubBlocksListResponse() + ) + req.return_value.content = return_value + + request = compute.ListReservationSubBlocksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ReservationSubBlocksListResponse() + post_with_metadata.return_value = ( + compute.ReservationSubBlocksListResponse(), + metadata, + ) + + client.list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_initialize_client_w_rest(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + assert client is not None + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_get_empty_call_rest(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get), "__call__") as call: + client.get(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetReservationSubBlockRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_empty_call_rest(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list), "__call__") as call: + client.list(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListReservationSubBlocksRequest() + + assert args[0] == request_msg + + +def test_reservation_sub_blocks_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReservationSubBlocksTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_reservation_sub_blocks_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.reservation_sub_blocks.transports.ReservationSubBlocksTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ReservationSubBlocksTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get", + "list", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_reservation_sub_blocks_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.compute_v1beta.services.reservation_sub_blocks.transports.ReservationSubBlocksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReservationSubBlocksTransport( + 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/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_reservation_sub_blocks_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.compute_v1beta.services.reservation_sub_blocks.transports.ReservationSubBlocksTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReservationSubBlocksTransport() + adc.assert_called_once() + + +def test_reservation_sub_blocks_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) + ReservationSubBlocksClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute.readonly", + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_reservation_sub_blocks_http_transport_client_cert_source_for_mtls(): + cred = ga_credentials.AnonymousCredentials() + with mock.patch( + "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" + ) as mock_configure_mtls_channel: + transports.ReservationSubBlocksRestTransport( + credentials=cred, client_cert_source_for_mtls=client_cert_source_callback + ) + mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_reservation_sub_blocks_host_no_port(transport_name): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:443" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_reservation_sub_blocks_host_with_port(transport_name): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="compute.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ( + "compute.googleapis.com:8000" + if transport_name in ["grpc", "grpc_asyncio"] + else "https://compute.googleapis.com:8000" + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "rest", + ], +) +def test_reservation_sub_blocks_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReservationSubBlocksClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReservationSubBlocksClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.list._session + session2 = client2.transport.list._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ReservationSubBlocksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ReservationSubBlocksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ReservationSubBlocksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ReservationSubBlocksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ReservationSubBlocksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ReservationSubBlocksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ReservationSubBlocksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ReservationSubBlocksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ReservationSubBlocksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ReservationSubBlocksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ReservationSubBlocksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ReservationSubBlocksClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = ReservationSubBlocksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ReservationSubBlocksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ReservationSubBlocksClient.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.ReservationSubBlocksTransport, "_prep_wrapped_messages" + ) as prep: + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ReservationSubBlocksTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ReservationSubBlocksClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +def test_transport_close_rest(): + client = ReservationSubBlocksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + with mock.patch.object( + type(getattr(client.transport, "_session")), "close" + ) as close: + with client: + close.assert_not_called() + close.assert_called_once() + + +def test_client_ctx(): + transports = [ + "rest", + ] + for transport in transports: + client = ReservationSubBlocksClient( + 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", + [ + (ReservationSubBlocksClient, transports.ReservationSubBlocksRestTransport), + ], +) +def test_api_key_credentials(client_class, transport_class): + with mock.patch.object( + google.auth._default, "get_api_key_credentials", create=True + ) as get_api_key_credentials: + mock_cred = mock.Mock() + get_api_key_credentials.return_value = mock_cred + options = client_options.ClientOptions() + options.api_key = "api_key" + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=mock_cred, + credentials_file=None, + host=client._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=client._DEFAULT_UNIVERSE + ), + scopes=None, + client_cert_source_for_mtls=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + always_use_jwt_access=True, + api_audience=None, + ) diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py index 08d2224be4c3..9e47f08f34f9 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py @@ -7935,6 +7935,7 @@ def test_insert_rest_call_success(request_type): ], "ncc_gateway": "ncc_gateway_value", "network": "network_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "self_link": "self_link_value", } @@ -8703,6 +8704,7 @@ def test_patch_rest_call_success(request_type): ], "ncc_gateway": "ncc_gateway_value", "network": "network_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "self_link": "self_link_value", } @@ -9328,6 +9330,7 @@ def test_preview_rest_call_success(request_type): ], "ncc_gateway": "ncc_gateway_value", "network": "network_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "self_link": "self_link_value", } @@ -9857,6 +9860,7 @@ def test_update_rest_call_success(request_type): ], "ncc_gateway": "ncc_gateway_value", "network": "network_value", + "params": {"resource_manager_tags": {}}, "region": "region_value", "self_link": "self_link_value", } diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_vpn_tunnels.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_vpn_tunnels.py index a9c9e0b6192f..396ab1b68703 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_vpn_tunnels.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_vpn_tunnels.py @@ -1972,7 +1972,9 @@ def test_insert_rest_flattened(): project="project_value", region="region_value", vpn_tunnel_resource=compute.VpnTunnel( - creation_timestamp="creation_timestamp_value" + cipher_suite=compute.VpnTunnelCipherSuite( + phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) + ) ), ) mock_args.update(sample_request) @@ -2014,7 +2016,9 @@ def test_insert_rest_flattened_error(transport: str = "rest"): project="project_value", region="region_value", vpn_tunnel_resource=compute.VpnTunnel( - creation_timestamp="creation_timestamp_value" + cipher_suite=compute.VpnTunnelCipherSuite( + phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) + ) ), ) @@ -2176,7 +2180,9 @@ def test_insert_unary_rest_flattened(): project="project_value", region="region_value", vpn_tunnel_resource=compute.VpnTunnel( - creation_timestamp="creation_timestamp_value" + cipher_suite=compute.VpnTunnelCipherSuite( + phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) + ) ), ) mock_args.update(sample_request) @@ -2218,7 +2224,9 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): project="project_value", region="region_value", vpn_tunnel_resource=compute.VpnTunnel( - creation_timestamp="creation_timestamp_value" + cipher_suite=compute.VpnTunnelCipherSuite( + phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) + ) ), ) @@ -3730,6 +3738,19 @@ def test_insert_rest_call_success(request_type): # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2"} request_init["vpn_tunnel_resource"] = { + "cipher_suite": { + "phase1": { + "dh": ["dh_value1", "dh_value2"], + "encryption": ["encryption_value1", "encryption_value2"], + "integrity": ["integrity_value1", "integrity_value2"], + "prf": ["prf_value1", "prf_value2"], + }, + "phase2": { + "encryption": ["encryption_value1", "encryption_value2"], + "integrity": ["integrity_value1", "integrity_value2"], + "pfs": ["pfs_value1", "pfs_value2"], + }, + }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "detailed_status": "detailed_status_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_wire_groups.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_wire_groups.py index cab6eac3ed59..f5c2a67e691b 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_wire_groups.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_wire_groups.py @@ -2989,6 +2989,7 @@ def test_get_rest_call_success(request_type): id=205, kind="kind_value", name="name_value", + reconciling=True, self_link="self_link_value", ) @@ -3012,6 +3013,7 @@ def test_get_rest_call_success(request_type): assert response.id == 205 assert response.kind == "kind_value" assert response.name == "name_value" + assert response.reconciling is True assert response.self_link == "self_link_value" @@ -3120,6 +3122,7 @@ def test_insert_rest_call_success(request_type): "id": 205, "kind": "kind_value", "name": "name_value", + "reconciling": True, "self_link": "self_link_value", "topology": {"endpoints": [{"city": "city_value", "label": "label_value"}]}, "wire_group_properties": {"type_": "type__value"}, @@ -3517,6 +3520,7 @@ def test_patch_rest_call_success(request_type): "id": 205, "kind": "kind_value", "name": "name_value", + "reconciling": True, "self_link": "self_link_value", "topology": {"endpoints": [{"city": "city_value", "label": "label_value"}]}, "wire_group_properties": {"type_": "type__value"},