diff --git a/.librarian/state.yaml b/.librarian/state.yaml index d06edcf23b71..490ca92ac14d 100644 --- a/.librarian/state.yaml +++ b/.librarian/state.yaml @@ -995,7 +995,7 @@ libraries: tag_format: '{id}-v{version}' - id: google-cloud-compute-v1beta version: 0.5.0 - last_generated_commit: 136a2c43b38a67cfe07317031764dd1ca1043fc6 + last_generated_commit: cfe62b3c5ceb9f81879c61480f26707980534462 apis: - path: google/cloud/compute/v1beta service_config: compute_v1beta.yaml diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_multi_mig_members.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_multi_mig_members.rst new file mode 100644 index 000000000000..0f5d82ee7908 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/region_multi_mig_members.rst @@ -0,0 +1,10 @@ +RegionMultiMigMembers +--------------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.region_multi_mig_members + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.region_multi_mig_members.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 796d41813acc..dc8b7b4eafae 100644 --- a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst @@ -78,6 +78,7 @@ Services for Google Cloud Compute v1beta API region_instances region_instance_templates region_instant_snapshots + region_multi_mig_members region_multi_migs region_network_endpoint_groups region_network_firewall_policies 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 fae6f41a6265..40c9cdffb1a3 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 @@ -111,6 +111,7 @@ from .services.region_instance_templates import RegionInstanceTemplatesClient from .services.region_instances import RegionInstancesClient from .services.region_instant_snapshots import RegionInstantSnapshotsClient +from .services.region_multi_mig_members import RegionMultiMigMembersClient from .services.region_multi_migs import RegionMultiMigsClient from .services.region_network_endpoint_groups import RegionNetworkEndpointGroupsClient from .services.region_network_firewall_policies import ( @@ -733,6 +734,7 @@ GetRegionInstanceGroupRequest, GetRegionInstanceTemplateRequest, GetRegionInstantSnapshotRequest, + GetRegionMultiMigMemberRequest, GetRegionMultiMigRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, @@ -1140,6 +1142,7 @@ License, LicenseCode, LicenseCodeLicenseAlias, + LicenseParams, LicenseResourceCommitment, LicenseResourceRequirements, LicensesListResponse, @@ -1231,6 +1234,7 @@ ListRegionInstanceGroupsRequest, ListRegionInstanceTemplatesRequest, ListRegionInstantSnapshotsRequest, + ListRegionMultiMigMembersRequest, ListRegionMultiMigsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, @@ -1314,6 +1318,9 @@ MoveInstanceProjectRequest, MoveOrganizationSecurityPolicyRequest, MultiMig, + MultiMigMember, + MultiMigMemberList, + MultiMigMemberStatus, MultiMigResourcePolicies, MultiMigsList, MultiMigStatus, @@ -1371,6 +1378,7 @@ NetworkProfile, NetworkProfileLocation, NetworkProfileNetworkFeatures, + NetworkProfileNetworkFeaturesPredefinedSubnetworkRange, NetworkProfileProfileType, NetworkProfilesListResponse, NetworkRoutingConfig, @@ -1944,6 +1952,7 @@ StoragePoolExapoolProvisionedCapacityGb, StoragePoolList, StoragePoolListDisks, + StoragePoolParams, StoragePoolResourceStatus, StoragePoolsScopedList, StoragePoolType, @@ -2887,6 +2896,7 @@ def _get_version(dependency_name): "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", "GetRegionInstantSnapshotRequest", + "GetRegionMultiMigMemberRequest", "GetRegionMultiMigRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", @@ -3316,6 +3326,7 @@ def _get_version(dependency_name): "LicenseCode", "LicenseCodeLicenseAlias", "LicenseCodesClient", + "LicenseParams", "LicenseResourceCommitment", "LicenseResourceRequirements", "LicensesClient", @@ -3408,6 +3419,7 @@ def _get_version(dependency_name): "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", "ListRegionInstantSnapshotsRequest", + "ListRegionMultiMigMembersRequest", "ListRegionMultiMigsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", @@ -3493,6 +3505,9 @@ def _get_version(dependency_name): "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "MultiMig", + "MultiMigMember", + "MultiMigMemberList", + "MultiMigMemberStatus", "MultiMigResourcePolicies", "MultiMigStatus", "MultiMigStatusAcceleratorTopology", @@ -3554,6 +3569,7 @@ def _get_version(dependency_name): "NetworkProfile", "NetworkProfileLocation", "NetworkProfileNetworkFeatures", + "NetworkProfileNetworkFeaturesPredefinedSubnetworkRange", "NetworkProfileProfileType", "NetworkProfilesClient", "NetworkProfilesListResponse", @@ -3787,6 +3803,7 @@ def _get_version(dependency_name): "RegionInstancesClient", "RegionInstantSnapshotsClient", "RegionList", + "RegionMultiMigMembersClient", "RegionMultiMigsClient", "RegionNetworkEndpointGroupsAttachEndpointsRequest", "RegionNetworkEndpointGroupsClient", @@ -4187,6 +4204,7 @@ def _get_version(dependency_name): "StoragePoolExapoolProvisionedCapacityGb", "StoragePoolList", "StoragePoolListDisks", + "StoragePoolParams", "StoragePoolResourceStatus", "StoragePoolType", "StoragePoolTypeAggregatedList", 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 16545765b573..cb855828176d 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 @@ -3955,6 +3955,25 @@ } } }, + "RegionMultiMigMembers": { + "clients": { + "rest": { + "libraryClient": "RegionMultiMigMembersClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "RegionMultiMigs": { "clients": { "rest": { diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/__init__.py new file mode 100644 index 000000000000..a3e0ab519b90 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/__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 RegionMultiMigMembersClient + +__all__ = ("RegionMultiMigMembersClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/client.py new file mode 100644 index 000000000000..91f9e235bf9e --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/client.py @@ -0,0 +1,1035 @@ +# -*- 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.region_multi_mig_members import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, RegionMultiMigMembersTransport +from .transports.rest import RegionMultiMigMembersRestTransport + + +class RegionMultiMigMembersClientMeta(type): + """Metaclass for the RegionMultiMigMembers 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[RegionMultiMigMembersTransport]] + _transport_registry["rest"] = RegionMultiMigMembersRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[RegionMultiMigMembersTransport]: + """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 RegionMultiMigMembersClient(metaclass=RegionMultiMigMembersClientMeta): + """The RegionMultiMigMembers 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" + + @staticmethod + def _use_client_cert_effective(): + """Returns whether client certificate should be used for mTLS if the + google-auth version supports should_use_client_cert automatic mTLS enablement. + + Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. + + Returns: + bool: whether client certificate should be used for mTLS + Raises: + ValueError: (If using a version of google-auth without should_use_client_cert and + GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) + """ + # check if google-auth version supports should_use_client_cert for automatic mTLS enablement + if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER + return mtls.should_use_client_cert() + else: # pragma: NO COVER + # if unsupported, fallback to reading from env var + use_client_cert_str = os.getenv( + "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" + ).lower() + if use_client_cert_str not in ("true", "false"): + raise ValueError( + "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" + " either `true` or `false`" + ) + return use_client_cert_str == "true" + + @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: + RegionMultiMigMembersClient: 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: + RegionMultiMigMembersClient: 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) -> RegionMultiMigMembersTransport: + """Returns the transport used by the client instance. + + Returns: + RegionMultiMigMembersTransport: 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 = RegionMultiMigMembersClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + 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: + 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 = RegionMultiMigMembersClient._use_client_cert_effective() + use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() + universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + 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, 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 = RegionMultiMigMembersClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = RegionMultiMigMembersClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + RegionMultiMigMembersClient._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 = RegionMultiMigMembersClient._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, + RegionMultiMigMembersTransport, + Callable[..., RegionMultiMigMembersTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the region multi mig members 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,RegionMultiMigMembersTransport,Callable[..., RegionMultiMigMembersTransport]]]): + 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 RegionMultiMigMembersTransport 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, + ) = RegionMultiMigMembersClient._read_environment_variables() + self._client_cert_source = RegionMultiMigMembersClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = RegionMultiMigMembersClient._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, RegionMultiMigMembersTransport) + if transport_provided: + # transport is a RegionMultiMigMembersTransport 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(RegionMultiMigMembersTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or RegionMultiMigMembersClient._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[RegionMultiMigMembersTransport], + Callable[..., RegionMultiMigMembersTransport], + ] = ( + RegionMultiMigMembersClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., RegionMultiMigMembersTransport], 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.RegionMultiMigMembersClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "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.RegionMultiMigMembers", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetRegionMultiMigMemberRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + multi_mig: Optional[str] = None, + multi_mig_member: 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.MultiMigMember: + r"""Retrieves information about the specified multi-MIG + member. + + .. 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.RegionMultiMigMembersClient() + + # Initialize request argument(s) + request = compute_v1beta.GetRegionMultiMigMemberRequest( + multi_mig="multi_mig_value", + multi_mig_member="multi_mig_member_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetRegionMultiMigMemberRequest, dict]): + The request object. A request message for + RegionMultiMigMembers.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. + region (str): + Name of the region for this request. + Region name should conform to RFC1035. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + multi_mig (str): + The name of the multi-MIG. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``multi_mig`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + multi_mig_member (str): + The name of the multi-MIG member. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``multi_mig_member`` 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.MultiMigMember: + Represents a Multi-MIG member + resource. + + """ + # 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, region, multi_mig, multi_mig_member] + 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.GetRegionMultiMigMemberRequest): + request = compute.GetRegionMultiMigMemberRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if multi_mig is not None: + request.multi_mig = multi_mig + if multi_mig_member is not None: + request.multi_mig_member = multi_mig_member + + # 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), + ("region", request.region), + ("multi_mig", request.multi_mig), + ("multi_mig_member", request.multi_mig_member), + ) + ), + ) + + # 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.ListRegionMultiMigMembersRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + multi_mig: 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 members of a specific multi-MIG. + + .. 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.RegionMultiMigMembersClient() + + # Initialize request argument(s) + request = compute_v1beta.ListRegionMultiMigMembersRequest( + multi_mig="multi_mig_value", + project="project_value", + region="region_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.ListRegionMultiMigMembersRequest, dict]): + The request object. A request message for + RegionMultiMigMembers.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. + region (str): + Name of the region for this request. + Region name should conform to RFC1035. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + multi_mig (str): + The name of the multi-MIG. + Name should conform to RFC1035 or be a + resource ID. + + This corresponds to the ``multi_mig`` 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.region_multi_mig_members.pagers.ListPager: + 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, region, multi_mig] + 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.ListRegionMultiMigMembersRequest): + request = compute.ListRegionMultiMigMembersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if region is not None: + request.region = region + if multi_mig is not None: + request.multi_mig = multi_mig + + # 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), + ("region", request.region), + ("multi_mig", request.multi_mig), + ) + ), + ) + + # 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) -> "RegionMultiMigMembersClient": + 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__ = ("RegionMultiMigMembersClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/pagers.py new file mode 100644 index 000000000000..07d4eccab9fa --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/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.MultiMigMemberList` 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.MultiMigMemberList` + 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.MultiMigMemberList], + request: compute.ListRegionMultiMigMembersRequest, + response: compute.MultiMigMemberList, + *, + 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.ListRegionMultiMigMembersRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.MultiMigMemberList): + 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.ListRegionMultiMigMembersRequest(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.MultiMigMemberList]: + 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.MultiMigMember]: + 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/region_multi_mig_members/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/README.rst new file mode 100644 index 000000000000..c73a4e65516a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/README.rst @@ -0,0 +1,9 @@ + +transport inheritance structure +_______________________________ + +`RegionMultiMigMembersTransport` is the ABC for all transports. +- public child `RegionMultiMigMembersGrpcTransport` for sync gRPC transport (defined in `grpc.py`). +- public child `RegionMultiMigMembersGrpcAsyncIOTransport` for async gRPC transport (defined in `grpc_asyncio.py`). +- private child `_BaseRegionMultiMigMembersRestTransport` for base REST transport with inner classes `_BaseMETHOD` (defined in `rest_base.py`). +- public child `RegionMultiMigMembersRestTransport` 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/region_multi_mig_members/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/__init__.py new file mode 100644 index 000000000000..3c6a7fe7211d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/__init__.py @@ -0,0 +1,35 @@ +# -*- 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 RegionMultiMigMembersTransport +from .rest import ( + RegionMultiMigMembersRestInterceptor, + RegionMultiMigMembersRestTransport, +) + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegionMultiMigMembersTransport]] +_transport_registry["rest"] = RegionMultiMigMembersRestTransport + +__all__ = ( + "RegionMultiMigMembersTransport", + "RegionMultiMigMembersRestTransport", + "RegionMultiMigMembersRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/base.py new file mode 100644 index 000000000000..e0d742df9f5d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/base.py @@ -0,0 +1,187 @@ +# -*- 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 RegionMultiMigMembersTransport(abc.ABC): + """Abstract transport class for RegionMultiMigMembers.""" + + 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. This argument will be + removed in the next major version of this library. + 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. + """ + + # 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=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + elif credentials is None and not self._ignore_credentials: + credentials, _ = google.auth.default( + scopes=scopes, + quota_project_id=quota_project_id, + default_scopes=self.AUTH_SCOPES, + ) + # 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.GetRegionMultiMigMemberRequest], + Union[compute.MultiMigMember, Awaitable[compute.MultiMigMember]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListRegionMultiMigMembersRequest], + Union[compute.MultiMigMemberList, Awaitable[compute.MultiMigMemberList]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("RegionMultiMigMembersTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/rest.py new file mode 100644 index 000000000000..c6c470d2b0ac --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/rest.py @@ -0,0 +1,602 @@ +# -*- 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 _BaseRegionMultiMigMembersRestTransport + +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 RegionMultiMigMembersRestInterceptor: + """Interceptor for RegionMultiMigMembers. + + 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 RegionMultiMigMembersRestTransport. + + .. code-block:: python + class MyCustomRegionMultiMigMembersInterceptor(RegionMultiMigMembersRestInterceptor): + 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 = RegionMultiMigMembersRestTransport(interceptor=MyCustomRegionMultiMigMembersInterceptor()) + client = RegionMultiMigMembersClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetRegionMultiMigMemberRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetRegionMultiMigMemberRequest, 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 RegionMultiMigMembers server. + """ + return request, metadata + + def post_get(self, response: compute.MultiMigMember) -> compute.MultiMigMember: + """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 RegionMultiMigMembers 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.MultiMigMember, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.MultiMigMember, 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 RegionMultiMigMembers 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.ListRegionMultiMigMembersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListRegionMultiMigMembersRequest, + 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 RegionMultiMigMembers server. + """ + return request, metadata + + def post_list( + self, response: compute.MultiMigMemberList + ) -> compute.MultiMigMemberList: + """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 RegionMultiMigMembers 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.MultiMigMemberList, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.MultiMigMemberList, 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 RegionMultiMigMembers 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 RegionMultiMigMembersRestStub: + _session: AuthorizedSession + _host: str + _interceptor: RegionMultiMigMembersRestInterceptor + + +class RegionMultiMigMembersRestTransport(_BaseRegionMultiMigMembersRestTransport): + """REST backend synchronous transport for RegionMultiMigMembers. + + The RegionMultiMigMembers 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[RegionMultiMigMembersRestInterceptor] = 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]): Deprecated. A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. This argument will be + removed in the next major version of this library. + 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 RegionMultiMigMembersRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get( + _BaseRegionMultiMigMembersRestTransport._BaseGet, RegionMultiMigMembersRestStub + ): + def __hash__(self): + return hash("RegionMultiMigMembersRestTransport.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.GetRegionMultiMigMemberRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.MultiMigMember: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetRegionMultiMigMemberRequest): + The request object. A request message for + RegionMultiMigMembers.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.MultiMigMember: + Represents a Multi-MIG member + resource. + + """ + + http_options = ( + _BaseRegionMultiMigMembersRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = _BaseRegionMultiMigMembersRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseRegionMultiMigMembersRestTransport._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.RegionMultiMigMembersClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionMultiMigMembersRestTransport._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.MultiMigMember() + pb_resp = compute.MultiMigMember.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.MultiMigMember.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.RegionMultiMigMembersClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseRegionMultiMigMembersRestTransport._BaseList, RegionMultiMigMembersRestStub + ): + def __hash__(self): + return hash("RegionMultiMigMembersRestTransport.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.ListRegionMultiMigMembersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.MultiMigMemberList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRegionMultiMigMembersRequest): + The request object. A request message for + RegionMultiMigMembers.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.MultiMigMemberList: + + """ + + http_options = ( + _BaseRegionMultiMigMembersRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseRegionMultiMigMembersRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseRegionMultiMigMembersRestTransport._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.RegionMultiMigMembersClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RegionMultiMigMembersRestTransport._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.MultiMigMemberList() + pb_resp = compute.MultiMigMemberList.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.MultiMigMemberList.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.RegionMultiMigMembersClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get( + self, + ) -> Callable[[compute.GetRegionMultiMigMemberRequest], compute.MultiMigMember]: + # 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.ListRegionMultiMigMembersRequest], compute.MultiMigMemberList + ]: + # 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__ = ("RegionMultiMigMembersRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/transports/rest_base.py new file mode 100644 index 000000000000..925df3bb2209 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_multi_mig_members/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, RegionMultiMigMembersTransport + + +class _BaseRegionMultiMigMembersRestTransport(RegionMultiMigMembersTransport): + """Base REST backend transport for RegionMultiMigMembers. + + 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}/regions/{region}/multiMigs/{multi_mig}/multiMigMembers/{multi_mig_member}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetRegionMultiMigMemberRequest.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( + _BaseRegionMultiMigMembersRestTransport._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}/regions/{region}/multiMigs/{multi_mig}/multiMigMembers", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListRegionMultiMigMembersRequest.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( + _BaseRegionMultiMigMembersRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseRegionMultiMigMembersRestTransport",) 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 63e19bfd7a86..f451baf911f2 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 @@ -584,6 +584,7 @@ GetRegionInstanceGroupRequest, GetRegionInstanceTemplateRequest, GetRegionInstantSnapshotRequest, + GetRegionMultiMigMemberRequest, GetRegionMultiMigRequest, GetRegionNetworkEndpointGroupRequest, GetRegionNetworkFirewallPolicyRequest, @@ -991,6 +992,7 @@ License, LicenseCode, LicenseCodeLicenseAlias, + LicenseParams, LicenseResourceCommitment, LicenseResourceRequirements, LicensesListResponse, @@ -1082,6 +1084,7 @@ ListRegionInstanceGroupsRequest, ListRegionInstanceTemplatesRequest, ListRegionInstantSnapshotsRequest, + ListRegionMultiMigMembersRequest, ListRegionMultiMigsRequest, ListRegionNetworkEndpointGroupsRequest, ListRegionNetworkFirewallPoliciesRequest, @@ -1165,6 +1168,9 @@ MoveInstanceProjectRequest, MoveOrganizationSecurityPolicyRequest, MultiMig, + MultiMigMember, + MultiMigMemberList, + MultiMigMemberStatus, MultiMigResourcePolicies, MultiMigsList, MultiMigStatus, @@ -1222,6 +1228,7 @@ NetworkProfile, NetworkProfileLocation, NetworkProfileNetworkFeatures, + NetworkProfileNetworkFeaturesPredefinedSubnetworkRange, NetworkProfileProfileType, NetworkProfilesListResponse, NetworkRoutingConfig, @@ -1795,6 +1802,7 @@ StoragePoolExapoolProvisionedCapacityGb, StoragePoolList, StoragePoolListDisks, + StoragePoolParams, StoragePoolResourceStatus, StoragePoolsScopedList, StoragePoolType, @@ -2627,6 +2635,7 @@ "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", "GetRegionInstantSnapshotRequest", + "GetRegionMultiMigMemberRequest", "GetRegionMultiMigRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", @@ -3034,6 +3043,7 @@ "License", "LicenseCode", "LicenseCodeLicenseAlias", + "LicenseParams", "LicenseResourceCommitment", "LicenseResourceRequirements", "LicensesListResponse", @@ -3125,6 +3135,7 @@ "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", "ListRegionInstantSnapshotsRequest", + "ListRegionMultiMigMembersRequest", "ListRegionMultiMigsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", @@ -3208,6 +3219,9 @@ "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "MultiMig", + "MultiMigMember", + "MultiMigMemberList", + "MultiMigMemberStatus", "MultiMigResourcePolicies", "MultiMigsList", "MultiMigStatus", @@ -3265,6 +3279,7 @@ "NetworkProfile", "NetworkProfileLocation", "NetworkProfileNetworkFeatures", + "NetworkProfileNetworkFeaturesPredefinedSubnetworkRange", "NetworkProfileProfileType", "NetworkProfilesListResponse", "NetworkRoutingConfig", @@ -3838,6 +3853,7 @@ "StoragePoolExapoolProvisionedCapacityGb", "StoragePoolList", "StoragePoolListDisks", + "StoragePoolParams", "StoragePoolResourceStatus", "StoragePoolsScopedList", "StoragePoolType", 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 ff1b2a700452..3ce24539f4e5 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 @@ -596,6 +596,7 @@ "GetRegionInstanceGroupRequest", "GetRegionInstanceTemplateRequest", "GetRegionInstantSnapshotRequest", + "GetRegionMultiMigMemberRequest", "GetRegionMultiMigRequest", "GetRegionNetworkEndpointGroupRequest", "GetRegionNetworkFirewallPolicyRequest", @@ -1001,6 +1002,7 @@ "License", "LicenseCode", "LicenseCodeLicenseAlias", + "LicenseParams", "LicenseResourceCommitment", "LicenseResourceRequirements", "LicensesListResponse", @@ -1092,6 +1094,7 @@ "ListRegionInstanceGroupsRequest", "ListRegionInstanceTemplatesRequest", "ListRegionInstantSnapshotsRequest", + "ListRegionMultiMigMembersRequest", "ListRegionMultiMigsRequest", "ListRegionNetworkEndpointGroupsRequest", "ListRegionNetworkFirewallPoliciesRequest", @@ -1175,6 +1178,9 @@ "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "MultiMig", + "MultiMigMember", + "MultiMigMemberList", + "MultiMigMemberStatus", "MultiMigResourcePolicies", "MultiMigStatus", "MultiMigStatusAcceleratorTopology", @@ -1232,6 +1238,7 @@ "NetworkProfile", "NetworkProfileLocation", "NetworkProfileNetworkFeatures", + "NetworkProfileNetworkFeaturesPredefinedSubnetworkRange", "NetworkProfileProfileType", "NetworkProfilesListResponse", "NetworkRoutingConfig", @@ -1805,6 +1812,7 @@ "StoragePoolExapoolProvisionedCapacityGb", "StoragePoolList", "StoragePoolListDisks", + "StoragePoolParams", "StoragePoolResourceStatus", "StoragePoolType", "StoragePoolTypeAggregatedList", @@ -26092,12 +26100,30 @@ class Type(proto.Enum): No description available. MEMORY_OPTIMIZED_M4_6TB (210543650): No description available. + MEMORY_OPTIMIZED_X4_1440_24T (206669823): + CUD bucket for X4 machine with 1440 vCPUs and + 24TB of memory. MEMORY_OPTIMIZED_X4_16TB (183089120): No description available. + MEMORY_OPTIMIZED_X4_1920_32T (291963529): + CUD bucket for X4 machine with 1920 vCPUs and + 32TB of memory. MEMORY_OPTIMIZED_X4_24TB (183116989): No description available. MEMORY_OPTIMIZED_X4_32TB (183144858): No description available. + MEMORY_OPTIMIZED_X4_480_6T (478547742): + CUD bucket for X4 machine with 480 vCPUs and + 6TB of memory. + MEMORY_OPTIMIZED_X4_480_8T (478547804): + CUD bucket for X4 machine with 480 vCPUs and + 8TB of memory. + MEMORY_OPTIMIZED_X4_960_12T (424752410): + CUD bucket for X4 machine with 960 vCPUs and + 12TB of memory. + MEMORY_OPTIMIZED_X4_960_16T (424752534): + CUD bucket for X4 machine with 960 vCPUs and + 16TB of memory. STORAGE_OPTIMIZED_Z3 (316796085): No description available. TYPE_UNSPECIFIED (437714322): @@ -26134,9 +26160,15 @@ class Type(proto.Enum): MEMORY_OPTIMIZED_M3 = 276301372 MEMORY_OPTIMIZED_M4 = 276301373 MEMORY_OPTIMIZED_M4_6TB = 210543650 + MEMORY_OPTIMIZED_X4_1440_24T = 206669823 MEMORY_OPTIMIZED_X4_16TB = 183089120 + MEMORY_OPTIMIZED_X4_1920_32T = 291963529 MEMORY_OPTIMIZED_X4_24TB = 183116989 MEMORY_OPTIMIZED_X4_32TB = 183144858 + MEMORY_OPTIMIZED_X4_480_6T = 478547742 + MEMORY_OPTIMIZED_X4_480_8T = 478547804 + MEMORY_OPTIMIZED_X4_960_12T = 424752410 + MEMORY_OPTIMIZED_X4_960_16T = 424752534 STORAGE_OPTIMIZED_Z3 = 316796085 TYPE_UNSPECIFIED = 437714322 @@ -46495,6 +46527,44 @@ class GetRegionInstantSnapshotRequest(proto.Message): ) +class GetRegionMultiMigMemberRequest(proto.Message): + r"""A request message for RegionMultiMigMembers.Get. See the + method description for details. + + Attributes: + multi_mig (str): + The name of the multi-MIG. + Name should conform to RFC1035 or be a resource + ID. + multi_mig_member (str): + The name of the multi-MIG member. + Name should conform to RFC1035 or be a resource + ID. + project (str): + Project ID for this request. + region (str): + Name of the region for this request. Region + name should conform to RFC1035. + """ + + multi_mig: str = proto.Field( + proto.STRING, + number=403990085, + ) + multi_mig_member: str = proto.Field( + proto.STRING, + number=36731348, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetRegionMultiMigRequest(proto.Message): r"""A request message for RegionMultiMigs.Get. See the method description for details. @@ -73576,6 +73646,12 @@ class License(proto.Message): image at a time. This field is a member of `oneof`_ ``_os_license``. + params (google.cloud.compute_v1beta.types.LicenseParams): + Input only. Additional params passed with the + request, but not persisted as part of resource + payload. + + This field is a member of `oneof`_ ``_params``. removable_from_disk (bool): If true, this license can be removed from a disk's set of licenses, with no replacement @@ -73685,6 +73761,12 @@ class License(proto.Message): number=487986406, optional=True, ) + params: "LicenseParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="LicenseParams", + ) removable_from_disk: bool = proto.Field( proto.BOOL, number=25854638, @@ -73888,6 +73970,28 @@ class LicenseCodeLicenseAlias(proto.Message): ) +class LicenseParams(proto.Message): + r"""Additional license params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Input only. Resource manager tags to be bound to the + license. Tag keys and values have the same definition as + resource manager tags. Keys and values can be either in + numeric format, such as ``tagKeys/{tag_key_id}`` and + ``tagValues/456`` or in namespaced format such as + ``{org_id|project_id}/{tag_key_short_name}`` and + ``{tag_value_short_name}``. The field is ignored (both PUT & + PATCH) when empty. + """ + + resource_manager_tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class LicenseResourceCommitment(proto.Message): r"""Commitment for a particular license resource. @@ -88338,6 +88442,178 @@ class ListRegionInstantSnapshotsRequest(proto.Message): ) +class ListRegionMultiMigMembersRequest(proto.Message): + r"""A request message for RegionMultiMigMembers.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 onresource 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 GoogleRE2 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``. + multi_mig (str): + The name of the multi-MIG. + Name should conform to RFC1035 or be a resource + ID. + 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. + region (str): + Name of the region for this request. Region + name should conform to RFC1035. + 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, + ) + multi_mig: str = proto.Field( + proto.STRING, + number=403990085, + ) + 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, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + class ListRegionMultiMigsRequest(proto.Message): r"""A request message for RegionMultiMigs.List. See the method description for details. @@ -99339,6 +99615,184 @@ class MultiMig(proto.Message): ) +class MultiMigMember(proto.Message): + r"""Represents a Multi-MIG member resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + creation_timestamp (str): + Output only. [Output Only] Creation timestamp of this + multi-MIG member inRFC3339 text format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + id (int): + Output only. [Output only] The unique identifier for this + resource type. The server generates this identifier. + + This field is a member of `oneof`_ ``_id``. + kind (str): + Output only. Type of the resource. + Alwayscompute#multiMigMember for a list of + multi-MIG members. + + This field is a member of `oneof`_ ``_kind``. + name (str): + Output only. [Output Only] Server-defined name for the + multi-MIG member. + + This field is a member of `oneof`_ ``_name``. + region (str): + Output only. [Output Only] The URL of the region where the + multi-MIG resides. + + This field is a member of `oneof`_ ``_region``. + self_link (str): + Output only. [Output Only] Server-defined fully-qualified + URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + status (google.cloud.compute_v1beta.types.MultiMigMemberStatus): + Output only. [Output Only] The status of this multi-MIG + member + + This field is a member of `oneof`_ ``_status``. + """ + + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + id: int = proto.Field( + proto.UINT64, + number=3355, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + status: "MultiMigMemberStatus" = proto.Field( + proto.MESSAGE, + number=181260274, + optional=True, + message="MultiMigMemberStatus", + ) + + +class MultiMigMemberList(proto.Message): + r""" + + .. _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.MultiMigMember]): + A list of multi-MIG member resources. + kind (str): + Output only. Type of the resource. + Alwayscompute#multiMigMember for a list of + multi-MIG members. + + 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 thanmaxResults, 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): + Output only. [Output only] 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["MultiMigMember"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="MultiMigMember", + ) + 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 MultiMigMemberStatus(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_group_manager (str): + [Output Only] URL of member instance group manager + + This field is a member of `oneof`_ ``_instance_group_manager``. + """ + + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + optional=True, + ) + + class MultiMigResourcePolicies(proto.Message): r"""Resource policies message for a multi-MIG. Specifies the workload policy configuration of the multi-MIG. @@ -99374,11 +99828,18 @@ class MultiMigResourcePolicies(proto.Message): class MultiMigStatus(proto.Message): r""" + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: applied_accelerator_topologies (MutableSequence[google.cloud.compute_v1beta.types.MultiMigStatusAcceleratorTopology]): Output only. [Output Only] The accelerator topology applied to this multi-MIG. Currently only one accelerator topology is supported. + members_count (int): + Output only. [Output Only] The number of instance group + manager members in this multi-MIG. + + This field is a member of `oneof`_ ``_members_count``. """ applied_accelerator_topologies: MutableSequence[ @@ -99388,6 +99849,11 @@ class MultiMigStatus(proto.Message): number=481392547, message="MultiMigStatusAcceleratorTopology", ) + members_count: int = proto.Field( + proto.INT32, + number=215189097, + optional=True, + ) class MultiMigStatusAcceleratorTopology(proto.Message): @@ -102151,6 +102617,11 @@ class NetworkInterface(proto.Message): Alwayscompute#networkInterface for network interfaces. This field is a member of `oneof`_ ``_kind``. + mac_address (str): + Output only. [Output Only] MAC address assigned to this + network interface. + + This field is a member of `oneof`_ ``_mac_address``. name (str): [Output Only] The name of the network interface, which is generated by the server. For a VM, the network interface @@ -102397,6 +102868,11 @@ class StackType(proto.Enum): number=3292052, optional=True, ) + mac_address: str = proto.Field( + proto.STRING, + number=332540164, + optional=True, + ) name: str = proto.Field( proto.STRING, number=3373707, @@ -103985,6 +104461,12 @@ class NetworkProfileNetworkFeatures(proto.Message): supported. If empty, all address purposes are supported. Check the AddressPurposes enum for the list of possible values. + allow_address_creation (str): + Specifies whether address creation is + allowed. Check the AllowAddressCreation enum for + the list of possible values. + + This field is a member of `oneof`_ ``_allow_address_creation``. allow_alias_ip_ranges (str): Specifies whether alias IP ranges (and secondary address ranges) are allowed. @@ -104063,6 +104545,13 @@ class NetworkProfileNetworkFeatures(proto.Message): possible values. This field is a member of `oneof`_ ``_allow_multi_nic_in_same_network``. + allow_multi_nic_in_same_subnetwork (str): + Specifies whether multi-nic in the same + subnetwork is allowed. Check the + AllowMultiNicInSameSubnetwork enum for the list + of possible values. + + This field is a member of `oneof`_ ``_allow_multi_nic_in_same_subnetwork``. allow_multicast (str): Specifies whether multicast is allowed. Check the AllowMulticast enum for the list of @@ -104118,6 +104607,19 @@ class NetworkProfileNetworkFeatures(proto.Message): of possible values. This field is a member of `oneof`_ ``_allow_sub_interfaces``. + allow_subnetwork_creation (str): + Specifies whether subnetwork creation is + allowed. Check the AllowSubnetworkCreation enum + for the list of possible values. + + This field is a member of `oneof`_ ``_allow_subnetwork_creation``. + allow_vpc_firewall_rules (str): + Specifies whether VPC firewall rules can be + created under the network. Check the + AllowVpcFirewallRules enum for the list of + possible values. + + This field is a member of `oneof`_ ``_allow_vpc_firewall_rules``. allow_vpc_peering (str): Specifies whether VPC peering is allowed. Check the AllowVpcPeering enum for the list of @@ -104144,6 +104646,13 @@ class NetworkProfileNetworkFeatures(proto.Message): of possible values. This field is a member of `oneof`_ ``_multicast``. + predefined_network_internal_ipv6_range (str): + Specifies a predefined internal IPv6 range + for the network. + + This field is a member of `oneof`_ ``_predefined_network_internal_ipv6_range``. + predefined_subnetwork_ranges (MutableSequence[google.cloud.compute_v1beta.types.NetworkProfileNetworkFeaturesPredefinedSubnetworkRange]): + Predefined subnetwork ranges for the network. subnet_purposes (MutableSequence[str]): Specifies which subnetwork purposes are supported. Check the SubnetPurposes enum for the @@ -104219,6 +104728,22 @@ class AddressPurposes(proto.Enum): SHARED_LOADBALANCER_VIP = 294447572 VPC_PEERING = 400800170 + class AllowAddressCreation(proto.Enum): + r"""Specifies whether address creation is allowed. + + Values: + UNDEFINED_ALLOW_ADDRESS_CREATION (0): + A value indicating that the enum field is not + set. + ADDRESS_CREATION_ALLOWED (181903667): + No description available. + ADDRESS_CREATION_BLOCKED (534937975): + No description available. + """ + UNDEFINED_ALLOW_ADDRESS_CREATION = 0 + ADDRESS_CREATION_ALLOWED = 181903667 + ADDRESS_CREATION_BLOCKED = 534937975 + class AllowAliasIpRanges(proto.Enum): r"""Specifies whether alias IP ranges (and secondary address ranges) are allowed. @@ -104415,6 +104940,23 @@ class AllowMultiNicInSameNetwork(proto.Enum): MULTI_NIC_IN_SAME_NETWORK_ALLOWED = 457555419 MULTI_NIC_IN_SAME_NETWORK_BLOCKED = 273718815 + class AllowMultiNicInSameSubnetwork(proto.Enum): + r"""Specifies whether multi-nic in the same subnetwork is + allowed. + + Values: + UNDEFINED_ALLOW_MULTI_NIC_IN_SAME_SUBNETWORK (0): + A value indicating that the enum field is not + set. + MULTI_NIC_IN_SAME_SUBNETWORK_ALLOWED (288044595): + No description available. + MULTI_NIC_IN_SAME_SUBNETWORK_BLOCKED (104207991): + No description available. + """ + UNDEFINED_ALLOW_MULTI_NIC_IN_SAME_SUBNETWORK = 0 + MULTI_NIC_IN_SAME_SUBNETWORK_ALLOWED = 288044595 + MULTI_NIC_IN_SAME_SUBNETWORK_BLOCKED = 104207991 + class AllowMulticast(proto.Enum): r"""Specifies whether multicast is allowed. @@ -104559,6 +105101,39 @@ class AllowSubInterfaces(proto.Enum): SUBINTERFACES_ALLOWED = 158685891 SUBINTERFACES_BLOCKED = 511720199 + class AllowSubnetworkCreation(proto.Enum): + r"""Specifies whether subnetwork creation is allowed. + + Values: + UNDEFINED_ALLOW_SUBNETWORK_CREATION (0): + A value indicating that the enum field is not + set. + SUBNETWORK_CREATION_ALLOWED (158580825): + No description available. + SUBNETWORK_CREATION_BLOCKED (511615133): + No description available. + """ + UNDEFINED_ALLOW_SUBNETWORK_CREATION = 0 + SUBNETWORK_CREATION_ALLOWED = 158580825 + SUBNETWORK_CREATION_BLOCKED = 511615133 + + class AllowVpcFirewallRules(proto.Enum): + r"""Specifies whether VPC firewall rules can be created under the + network. + + Values: + UNDEFINED_ALLOW_VPC_FIREWALL_RULES (0): + A value indicating that the enum field is not + set. + VPC_FIREWALL_RULES_ALLOWED (489586007): + No description available. + VPC_FIREWALL_RULES_BLOCKED (305749403): + No description available. + """ + UNDEFINED_ALLOW_VPC_FIREWALL_RULES = 0 + VPC_FIREWALL_RULES_ALLOWED = 489586007 + VPC_FIREWALL_RULES_BLOCKED = 305749403 + class AllowVpcPeering(proto.Enum): r"""Specifies whether VPC peering is allowed. @@ -104769,6 +105344,11 @@ class Unicast(proto.Enum): proto.STRING, number=433024768, ) + allow_address_creation: str = proto.Field( + proto.STRING, + number=450941184, + optional=True, + ) allow_alias_ip_ranges: str = proto.Field( proto.STRING, number=457984201, @@ -104829,6 +105409,11 @@ class Unicast(proto.Enum): number=88251004, optional=True, ) + allow_multi_nic_in_same_subnetwork: str = proto.Field( + proto.STRING, + number=278087904, + optional=True, + ) allow_multicast: str = proto.Field( proto.STRING, number=11002498, @@ -104874,6 +105459,16 @@ class Unicast(proto.Enum): number=247208303, optional=True, ) + allow_subnetwork_creation: str = proto.Field( + proto.STRING, + number=459328026, + optional=True, + ) + allow_vpc_firewall_rules: str = proto.Field( + proto.STRING, + number=509076420, + optional=True, + ) allow_vpc_peering: str = proto.Field( proto.STRING, number=115402228, @@ -104897,6 +105492,18 @@ class Unicast(proto.Enum): number=404098040, optional=True, ) + predefined_network_internal_ipv6_range: str = proto.Field( + proto.STRING, + number=527810909, + optional=True, + ) + predefined_subnetwork_ranges: MutableSequence[ + "NetworkProfileNetworkFeaturesPredefinedSubnetworkRange" + ] = proto.RepeatedField( + proto.MESSAGE, + number=408740430, + message="NetworkProfileNetworkFeaturesPredefinedSubnetworkRange", + ) subnet_purposes: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=301338039, @@ -104920,6 +105527,35 @@ class Unicast(proto.Enum): ) +class NetworkProfileNetworkFeaturesPredefinedSubnetworkRange(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + ipv6_range (str): + The IPv6 range of the predefined subnetwork. + + This field is a member of `oneof`_ ``_ipv6_range``. + name_prefix (str): + The naming prefix of the predefined + subnetwork. + + This field is a member of `oneof`_ ``_name_prefix``. + """ + + ipv6_range: str = proto.Field( + proto.STRING, + number=50053349, + optional=True, + ) + name_prefix: str = proto.Field( + proto.STRING, + number=236409542, + optional=True, + ) + + class NetworkProfileProfileType(proto.Message): r""" @@ -104978,10 +105614,14 @@ class RdmaSubtype(proto.Enum): RDMA over Falcon. ROCE (2520927): RDMA over Converged Ethernet (RoCE). + ROCE_METAL (421218823): + RDMA over Converged Ethernet (RoCE) for Bare + Metal. """ UNDEFINED_RDMA_SUBTYPE = 0 FALCON = 455787729 ROCE = 2520927 + ROCE_METAL = 421218823 class UllSubtype(proto.Enum): r""" @@ -144389,6 +145029,12 @@ class StoragePool(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + params (google.cloud.compute_v1beta.types.StoragePoolParams): + Input only. Additional params passed with the + request, but not persisted as part of resource + payload. + + This field is a member of `oneof`_ ``_params``. performance_provisioning_type (str): Provisioning type of the performance-related parameters of the pool, such as throughput and @@ -144573,6 +145219,12 @@ class State(proto.Enum): number=3373707, optional=True, ) + params: "StoragePoolParams" = proto.Field( + proto.MESSAGE, + number=78313862, + optional=True, + message="StoragePoolParams", + ) performance_provisioning_type: str = proto.Field( proto.STRING, number=468553469, @@ -145082,6 +145734,28 @@ def raw_page(self): ) +class StoragePoolParams(proto.Message): + r"""Additional storage pool params. + + Attributes: + resource_manager_tags (MutableMapping[str, str]): + Input only. Resource manager tags to be bound to the storage + pool. Tag keys and values have the same definition as + resource manager tags. Keys and values can be either in + numeric format, such as ``tagKeys/{tag_key_id}`` and + ``tagValues/456`` or in namespaced format such as + ``{org_id|project_id}/{tag_key_short_name}`` and + ``{tag_value_short_name}``. The field is ignored (both PUT & + PATCH) when empty. + """ + + resource_manager_tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=377671164, + ) + + class StoragePoolResourceStatus(proto.Message): r"""[Output Only] Contains output only fields. @@ -158807,6 +159481,14 @@ class VpnTunnel(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + capacity_tier (str): + Capacity tier of the VPN tunnel. This is used + for IPsec over Interconnect tunnels to indicate + different bandwidth limits. Check the + CapacityTier enum for the list of possible + values. + + This field is a member of `oneof`_ ``_capacity_tier``. 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. @@ -159011,6 +159693,25 @@ class VpnTunnel(proto.Message): This field is a member of `oneof`_ ``_vpn_gateway_interface``. """ + class CapacityTier(proto.Enum): + r"""Capacity tier of the VPN tunnel. This is used for IPsec over + Interconnect tunnels to indicate different bandwidth limits. + + Values: + UNDEFINED_CAPACITY_TIER (0): + A value indicating that the enum field is not + set. + DEFAULT (115302945): + DEFAULT: A VPN tunnel which can support up to + 3 Gbps. + HIGH (2217378): + HIGH: A VPN tunnel which can support up to 6 + Gbps. + """ + UNDEFINED_CAPACITY_TIER = 0 + DEFAULT = 115302945 + HIGH = 2217378 + class Status(proto.Enum): r"""[Output Only] The status of the VPN tunnel, which can be one of the following: @@ -159103,6 +159804,11 @@ class Status(proto.Enum): STOPPED = 444276141 WAITING_FOR_FULL_CONFIG = 41640522 + capacity_tier: str = proto.Field( + proto.STRING, + number=418241095, + optional=True, + ) cipher_suite: "VpnTunnelCipherSuite" = proto.Field( proto.MESSAGE, number=443788228, diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_multi_mig_members_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_multi_mig_members_get_sync.py new file mode 100644 index 000000000000..e2669e47bfca --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_multi_mig_members_get_sync.py @@ -0,0 +1,56 @@ +# -*- 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_RegionMultiMigMembers_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.RegionMultiMigMembersClient() + + # Initialize request argument(s) + request = compute_v1beta.GetRegionMultiMigMemberRequest( + multi_mig="multi_mig_value", + multi_mig_member="multi_mig_member_value", + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_RegionMultiMigMembers_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_multi_mig_members_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_multi_mig_members_list_sync.py new file mode 100644 index 000000000000..eb3c6efef0da --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_region_multi_mig_members_list_sync.py @@ -0,0 +1,56 @@ +# -*- 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_RegionMultiMigMembers_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.RegionMultiMigMembersClient() + + # Initialize request argument(s) + request = compute_v1beta.ListRegionMultiMigMembersRequest( + multi_mig="multi_mig_value", + project="project_value", + region="region_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1beta_generated_RegionMultiMigMembers_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 c3e4b0dc1d8f..b7a783fdc8b9 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 @@ -56951,6 +56951,186 @@ ], "title": "compute_v1beta_generated_region_instant_snapshots_test_iam_permissions_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionMultiMigMembersClient", + "shortName": "RegionMultiMigMembersClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionMultiMigMembersClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigMembers.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "shortName": "RegionMultiMigMembers" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetRegionMultiMigMemberRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "multi_mig", + "type": "str" + }, + { + "name": "multi_mig_member", + "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.MultiMigMember", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_region_multi_mig_members_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionMultiMigMembers_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_region_multi_mig_members_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionMultiMigMembersClient", + "shortName": "RegionMultiMigMembersClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionMultiMigMembersClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigMembers.List", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionMultiMigMembers", + "shortName": "RegionMultiMigMembers" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListRegionMultiMigMembersRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "multi_mig", + "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.region_multi_mig_members.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_region_multi_mig_members_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionMultiMigMembers_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_region_multi_mig_members_list_sync.py" + }, { "canonical": true, "clientMethod": { 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 4ed33e6df248..3cf62472ef7b 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 @@ -4126,6 +4126,7 @@ def test_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", 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 009de34b56cd..ed9538e1ca27 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 @@ -23267,6 +23267,7 @@ def test_add_network_interface_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", @@ -24324,6 +24325,7 @@ def test_bulk_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", @@ -26654,6 +26656,7 @@ def test_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", @@ -33567,6 +33570,7 @@ def test_update_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", @@ -34444,6 +34448,7 @@ def test_update_network_interface_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_licenses.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_licenses.py index 3e1ab0f1bf9b..8a7d8902a126 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_licenses.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_licenses.py @@ -4034,6 +4034,7 @@ def test_insert_rest_call_success(request_type): "multi_tenant_only": True, "name": "name_value", "os_license": True, + "params": {"resource_manager_tags": {}}, "removable_from_disk": True, "required_coattached_licenses": [ "required_coattached_licenses_value1", @@ -4873,6 +4874,7 @@ def test_update_rest_call_success(request_type): "multi_tenant_only": True, "name": "name_value", "os_license": True, + "params": {"resource_manager_tags": {}}, "removable_from_disk": True, "required_coattached_licenses": [ "required_coattached_licenses_value1", 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 4fee2f3c04ab..7707ef6f3f85 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 @@ -4106,6 +4106,7 @@ def test_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_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 489e558c2a90..3d2d900597ab 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 @@ -3082,6 +3082,7 @@ def test_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", 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 50664629ac98..62a5f43aab55 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 @@ -1823,6 +1823,7 @@ def test_bulk_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_address": "ipv6_address_value", "kind": "kind_value", + "mac_address": "mac_address_value", "name": "name_value", "network": "network_value", "network_attachment": "network_attachment_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_multi_mig_members.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_multi_mig_members.py new file mode 100644 index 000000000000..46ac736eb9a5 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_multi_mig_members.py @@ -0,0 +1,2444 @@ +# -*- 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.region_multi_mig_members import ( + RegionMultiMigMembersClient, + 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 RegionMultiMigMembersClient._get_default_mtls_endpoint(None) is None + assert ( + RegionMultiMigMembersClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionMultiMigMembersClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegionMultiMigMembersClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionMultiMigMembersClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegionMultiMigMembersClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +def test__read_environment_variables(): + assert RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionMultiMigMembersClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with pytest.raises(ValueError) as excinfo: + RegionMultiMigMembersClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionMultiMigMembersClient._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 RegionMultiMigMembersClient._read_environment_variables() == ( + False, + "auto", + "foo.com", + ) + + +def test_use_client_cert_effective(): + # Test case 1: Test when `should_use_client_cert` returns True. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=True + ): + assert RegionMultiMigMembersClient._use_client_cert_effective() is True + + # Test case 2: Test when `should_use_client_cert` returns False. + # We mock the `should_use_client_cert` function to simulate a scenario where + # the google-auth library supports automatic mTLS and determines that a + # client certificate should NOT be used. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch( + "google.auth.transport.mtls.should_use_client_cert", return_value=False + ): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + # Test case 3: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "true". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert RegionMultiMigMembersClient._use_client_cert_effective() is True + + # Test case 4: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"} + ): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + # Test case 5: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "True". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "True"}): + assert RegionMultiMigMembersClient._use_client_cert_effective() is True + + # Test case 6: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "False". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "False"} + ): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + # Test case 7: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "TRUE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "TRUE"}): + assert RegionMultiMigMembersClient._use_client_cert_effective() is True + + # Test case 8: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to "FALSE". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "FALSE"} + ): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + # Test case 9: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not set. + # In this case, the method should return False, which is the default value. + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, clear=True): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + # Test case 10: Test when `should_use_client_cert` is unavailable and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should raise a ValueError as the environment variable must be either + # "true" or "false". + if not hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + with pytest.raises(ValueError): + RegionMultiMigMembersClient._use_client_cert_effective() + + # Test case 11: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is set to an invalid value. + # The method should return False as the environment variable is set to an invalid value. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "unsupported"} + ): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + # Test case 12: Test when `should_use_client_cert` is available and the + # `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is unset. Also, + # the GOOGLE_API_CONFIG environment variable is unset. + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": ""}): + with mock.patch.dict(os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": ""}): + assert RegionMultiMigMembersClient._use_client_cert_effective() is False + + +def test__get_client_cert_source(): + mock_provided_cert_source = mock.Mock() + mock_default_cert_source = mock.Mock() + + assert RegionMultiMigMembersClient._get_client_cert_source(None, False) is None + assert ( + RegionMultiMigMembersClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + RegionMultiMigMembersClient._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 ( + RegionMultiMigMembersClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + RegionMultiMigMembersClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + RegionMultiMigMembersClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionMultiMigMembersClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = RegionMultiMigMembersClient._DEFAULT_UNIVERSE + default_endpoint = RegionMultiMigMembersClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionMultiMigMembersClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == RegionMultiMigMembersClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == RegionMultiMigMembersClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == RegionMultiMigMembersClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + RegionMultiMigMembersClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + RegionMultiMigMembersClient._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 ( + RegionMultiMigMembersClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + RegionMultiMigMembersClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + RegionMultiMigMembersClient._get_universe_domain(None, None) + == RegionMultiMigMembersClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + RegionMultiMigMembersClient._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 = RegionMultiMigMembersClient(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 = RegionMultiMigMembersClient(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", + [ + (RegionMultiMigMembersClient, "rest"), + ], +) +def test_region_multi_mig_members_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.RegionMultiMigMembersRestTransport, "rest"), + ], +) +def test_region_multi_mig_members_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", + [ + (RegionMultiMigMembersClient, "rest"), + ], +) +def test_region_multi_mig_members_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_region_multi_mig_members_client_get_transport_class(): + transport = RegionMultiMigMembersClient.get_transport_class() + available_transports = [ + transports.RegionMultiMigMembersRestTransport, + ] + assert transport in available_transports + + transport = RegionMultiMigMembersClient.get_transport_class("rest") + assert transport == transports.RegionMultiMigMembersRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegionMultiMigMembersClient, + transports.RegionMultiMigMembersRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + RegionMultiMigMembersClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionMultiMigMembersClient), +) +def test_region_multi_mig_members_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(RegionMultiMigMembersClient, "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(RegionMultiMigMembersClient, "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 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", + [ + ( + RegionMultiMigMembersClient, + transports.RegionMultiMigMembersRestTransport, + "rest", + "true", + ), + ( + RegionMultiMigMembersClient, + transports.RegionMultiMigMembersRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + RegionMultiMigMembersClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionMultiMigMembersClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_region_multi_mig_members_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", [RegionMultiMigMembersClient]) +@mock.patch.object( + RegionMultiMigMembersClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegionMultiMigMembersClient), +) +def test_region_multi_mig_members_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_CLIENT_CERTIFICATE is "Unsupported". + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + 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 cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", None) + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + 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 expected_cert_source + + # Test cases for mTLS enablement when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset(empty). + test_cases = [ + ( + # With workloads present in config, mTLS is enabled. + { + "version": 1, + "cert_configs": { + "workload": { + "cert_path": "path/to/cert/file", + "key_path": "path/to/key/file", + } + }, + }, + mock_client_cert_source, + ), + ( + # With workloads not present in config, mTLS is disabled. + { + "version": 1, + "cert_configs": {}, + }, + None, + ), + ] + if hasattr(google.auth.transport.mtls, "should_use_client_cert"): + for config_data, expected_cert_source in test_cases: + env = os.environ.copy() + env.pop("GOOGLE_API_USE_CLIENT_CERTIFICATE", "") + with mock.patch.dict(os.environ, env, clear=True): + config_filename = "mock_certificate_config.json" + config_file_content = json.dumps(config_data) + m = mock.mock_open(read_data=config_file_content) + with mock.patch("builtins.open", m): + with mock.patch.dict( + os.environ, {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename} + ): + 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 expected_cert_source + + # 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`" + ) + + +@pytest.mark.parametrize("client_class", [RegionMultiMigMembersClient]) +@mock.patch.object( + RegionMultiMigMembersClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(RegionMultiMigMembersClient), +) +def test_region_multi_mig_members_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = RegionMultiMigMembersClient._DEFAULT_UNIVERSE + default_endpoint = RegionMultiMigMembersClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = RegionMultiMigMembersClient._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", + [ + ( + RegionMultiMigMembersClient, + transports.RegionMultiMigMembersRestTransport, + "rest", + ), + ], +) +def test_region_multi_mig_members_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", + [ + ( + RegionMultiMigMembersClient, + transports.RegionMultiMigMembersRestTransport, + "rest", + None, + ), + ], +) +def test_region_multi_mig_members_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 = RegionMultiMigMembersClient( + 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.GetRegionMultiMigMemberRequest): + transport_class = transports.RegionMultiMigMembersRestTransport + + request_init = {} + request_init["multi_mig"] = "" + request_init["multi_mig_member"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["multiMig"] = "multi_mig_value" + jsonified_request["multiMigMember"] = "multi_mig_member_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "multiMig" in jsonified_request + assert jsonified_request["multiMig"] == "multi_mig_value" + assert "multiMigMember" in jsonified_request + assert jsonified_request["multiMigMember"] == "multi_mig_member_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.MultiMigMember() + # 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.MultiMigMember.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.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "multiMig", + "multiMigMember", + "project", + "region", + ) + ) + ) + + +def test_get_rest_flattened(): + client = RegionMultiMigMembersClient( + 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.MultiMigMember() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "multi_mig": "sample3", + "multi_mig_member": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + multi_mig="multi_mig_value", + multi_mig_member="multi_mig_member_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.MultiMigMember.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}/regions/{region}/multiMigs/{multi_mig}/multiMigMembers/{multi_mig_member}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RegionMultiMigMembersClient( + 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.GetRegionMultiMigMemberRequest(), + project="project_value", + region="region_value", + multi_mig="multi_mig_value", + multi_mig_member="multi_mig_member_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 = RegionMultiMigMembersClient( + 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.ListRegionMultiMigMembersRequest, +): + transport_class = transports.RegionMultiMigMembersRestTransport + + request_init = {} + request_init["multi_mig"] = "" + request_init["project"] = "" + request_init["region"] = "" + 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["multiMig"] = "multi_mig_value" + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_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 "multiMig" in jsonified_request + assert jsonified_request["multiMig"] == "multi_mig_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.MultiMigMemberList() + # 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.MultiMigMemberList.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.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "multiMig", + "project", + "region", + ) + ) + ) + + +def test_list_rest_flattened(): + client = RegionMultiMigMembersClient( + 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.MultiMigMemberList() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "multi_mig": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + multi_mig="multi_mig_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.MultiMigMemberList.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}/regions/{region}/multiMigs/{multi_mig}/multiMigMembers" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RegionMultiMigMembersClient( + 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.ListRegionMultiMigMembersRequest(), + project="project_value", + region="region_value", + multi_mig="multi_mig_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RegionMultiMigMembersClient( + 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.MultiMigMemberList( + items=[ + compute.MultiMigMember(), + compute.MultiMigMember(), + compute.MultiMigMember(), + ], + next_page_token="abc", + ), + compute.MultiMigMemberList( + items=[], + next_page_token="def", + ), + compute.MultiMigMemberList( + items=[ + compute.MultiMigMember(), + ], + next_page_token="ghi", + ), + compute.MultiMigMemberList( + items=[ + compute.MultiMigMember(), + compute.MultiMigMember(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.MultiMigMemberList.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", + "region": "sample2", + "multi_mig": "sample3", + } + + pager = client.list(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.MultiMigMember) 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.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionMultiMigMembersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RegionMultiMigMembersClient( + 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 = RegionMultiMigMembersClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegionMultiMigMembersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RegionMultiMigMembersClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegionMultiMigMembersRestTransport, + ], +) +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 = RegionMultiMigMembersClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetRegionMultiMigMemberRequest): + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "multi_mig": "sample3", + "multi_mig_member": "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.GetRegionMultiMigMemberRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "region": "sample2", + "multi_mig": "sample3", + "multi_mig_member": "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.MultiMigMember( + creation_timestamp="creation_timestamp_value", + id=205, + kind="kind_value", + name="name_value", + region="region_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.MultiMigMember.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.MultiMigMember) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.region == "region_value" + assert response.self_link == "self_link_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionMultiMigMembersRestInterceptor(), + ) + client = RegionMultiMigMembersClient(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.RegionMultiMigMembersRestInterceptor, "post_get" + ) as post, mock.patch.object( + transports.RegionMultiMigMembersRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionMultiMigMembersRestInterceptor, "pre_get" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRegionMultiMigMemberRequest.pb( + compute.GetRegionMultiMigMemberRequest() + ) + 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.MultiMigMember.to_json(compute.MultiMigMember()) + req.return_value.content = return_value + + request = compute.GetRegionMultiMigMemberRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.MultiMigMember() + post_with_metadata.return_value = compute.MultiMigMember(), 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.ListRegionMultiMigMembersRequest): + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "multi_mig": "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.ListRegionMultiMigMembersRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "multi_mig": "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.MultiMigMemberList( + 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.MultiMigMemberList.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.RegionMultiMigMembersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.RegionMultiMigMembersRestInterceptor(), + ) + client = RegionMultiMigMembersClient(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.RegionMultiMigMembersRestInterceptor, "post_list" + ) as post, mock.patch.object( + transports.RegionMultiMigMembersRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, mock.patch.object( + transports.RegionMultiMigMembersRestInterceptor, "pre_list" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListRegionMultiMigMembersRequest.pb( + compute.ListRegionMultiMigMembersRequest() + ) + 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.MultiMigMemberList.to_json(compute.MultiMigMemberList()) + req.return_value.content = return_value + + request = compute.ListRegionMultiMigMembersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.MultiMigMemberList() + post_with_metadata.return_value = compute.MultiMigMemberList(), 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 = RegionMultiMigMembersClient( + 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 = RegionMultiMigMembersClient( + 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.GetRegionMultiMigMemberRequest() + + 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 = RegionMultiMigMembersClient( + 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.ListRegionMultiMigMembersRequest() + + assert args[0] == request_msg + + +def test_region_multi_mig_members_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.RegionMultiMigMembersTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_region_multi_mig_members_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.region_multi_mig_members.transports.RegionMultiMigMembersTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegionMultiMigMembersTransport( + 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_region_multi_mig_members_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.region_multi_mig_members.transports.RegionMultiMigMembersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionMultiMigMembersTransport( + 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_region_multi_mig_members_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.region_multi_mig_members.transports.RegionMultiMigMembersTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.RegionMultiMigMembersTransport() + adc.assert_called_once() + + +def test_region_multi_mig_members_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) + RegionMultiMigMembersClient() + 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_region_multi_mig_members_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.RegionMultiMigMembersRestTransport( + 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_region_multi_mig_members_host_no_port(transport_name): + client = RegionMultiMigMembersClient( + 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_region_multi_mig_members_host_with_port(transport_name): + client = RegionMultiMigMembersClient( + 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_region_multi_mig_members_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = RegionMultiMigMembersClient( + credentials=creds1, + transport=transport_name, + ) + client2 = RegionMultiMigMembersClient( + 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 = RegionMultiMigMembersClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegionMultiMigMembersClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegionMultiMigMembersClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = RegionMultiMigMembersClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegionMultiMigMembersClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegionMultiMigMembersClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = RegionMultiMigMembersClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegionMultiMigMembersClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegionMultiMigMembersClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = RegionMultiMigMembersClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegionMultiMigMembersClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegionMultiMigMembersClient.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 = RegionMultiMigMembersClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegionMultiMigMembersClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegionMultiMigMembersClient.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.RegionMultiMigMembersTransport, "_prep_wrapped_messages" + ) as prep: + client = RegionMultiMigMembersClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegionMultiMigMembersTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegionMultiMigMembersClient.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 = RegionMultiMigMembersClient( + 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 = RegionMultiMigMembersClient( + 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", + [ + (RegionMultiMigMembersClient, transports.RegionMultiMigMembersRestTransport), + ], +) +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_region_multi_migs.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_multi_migs.py index 3030b9d5d02f..34e5d9e6b0f7 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_multi_migs.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_multi_migs.py @@ -2937,7 +2937,8 @@ def test_insert_rest_call_success(request_type): "timestamp": "timestamp_value", }, } - ] + ], + "members_count": 1395, }, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_storage_pools.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_storage_pools.py index 54b9975e9bf8..4c609fbad541 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_storage_pools.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_storage_pools.py @@ -4797,6 +4797,7 @@ def test_insert_rest_call_success(request_type): "label_fingerprint": "label_fingerprint_value", "labels": {}, "name": "name_value", + "params": {"resource_manager_tags": {}}, "performance_provisioning_type": "performance_provisioning_type_value", "pool_provisioned_capacity_gb": 2976, "pool_provisioned_iops": 2277, @@ -5801,6 +5802,7 @@ def test_update_rest_call_success(request_type): "label_fingerprint": "label_fingerprint_value", "labels": {}, "name": "name_value", + "params": {"resource_manager_tags": {}}, "performance_provisioning_type": "performance_provisioning_type_value", "pool_provisioned_capacity_gb": 2976, "pool_provisioned_iops": 2277, 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 48bd5771bc61..e73f4847c189 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 @@ -2167,11 +2167,7 @@ def test_insert_rest_flattened(): mock_args = dict( project="project_value", region="region_value", - vpn_tunnel_resource=compute.VpnTunnel( - cipher_suite=compute.VpnTunnelCipherSuite( - phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) - ) - ), + vpn_tunnel_resource=compute.VpnTunnel(capacity_tier="capacity_tier_value"), ) mock_args.update(sample_request) @@ -2211,11 +2207,7 @@ def test_insert_rest_flattened_error(transport: str = "rest"): compute.InsertVpnTunnelRequest(), project="project_value", region="region_value", - vpn_tunnel_resource=compute.VpnTunnel( - cipher_suite=compute.VpnTunnelCipherSuite( - phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) - ) - ), + vpn_tunnel_resource=compute.VpnTunnel(capacity_tier="capacity_tier_value"), ) @@ -2375,11 +2367,7 @@ def test_insert_unary_rest_flattened(): mock_args = dict( project="project_value", region="region_value", - vpn_tunnel_resource=compute.VpnTunnel( - cipher_suite=compute.VpnTunnelCipherSuite( - phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) - ) - ), + vpn_tunnel_resource=compute.VpnTunnel(capacity_tier="capacity_tier_value"), ) mock_args.update(sample_request) @@ -2419,11 +2407,7 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): compute.InsertVpnTunnelRequest(), project="project_value", region="region_value", - vpn_tunnel_resource=compute.VpnTunnel( - cipher_suite=compute.VpnTunnelCipherSuite( - phase1=compute.VpnTunnelPhase1Algorithms(dh=["dh_value"]) - ) - ), + vpn_tunnel_resource=compute.VpnTunnel(capacity_tier="capacity_tier_value"), ) @@ -3772,6 +3756,7 @@ def test_get_rest_call_success(request_type): with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.VpnTunnel( + capacity_tier="capacity_tier_value", creation_timestamp="creation_timestamp_value", description="description_value", detailed_status="detailed_status_value", @@ -3811,6 +3796,7 @@ def test_get_rest_call_success(request_type): # Establish that the response is the type that we expect. assert isinstance(response, compute.VpnTunnel) + assert response.capacity_tier == "capacity_tier_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.detailed_status == "detailed_status_value" @@ -3934,6 +3920,7 @@ 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"] = { + "capacity_tier": "capacity_tier_value", "cipher_suite": { "phase1": { "dh": ["dh_value1", "dh_value2"],