diff --git a/librarian.yaml b/librarian.yaml index 4dab50824783..a178058f8558 100644 --- a/librarian.yaml +++ b/librarian.yaml @@ -16,8 +16,8 @@ version: v0.26.0 repo: googleapis/google-cloud-python sources: googleapis: - commit: 99f54e6513f09d8df1707a6c553b0a3c6ef9b5fb - sha256: 7cee15fe1ae76a16aaf70425c4380a3a0fcbfeb4ea8e30c934c43f5cd54b9657 + commit: fe04226e3d76435acbfd3ffb51f6771740e1fb5b + sha256: e99c641a9c5525394de43c762b9db50c3ada1f219d6dbdba594ae992fbe1d838 default: output: packages tag_format: '{name}-v{version}' diff --git a/packages/google-apps-chat/google/apps/chat/__init__.py b/packages/google-apps-chat/google/apps/chat/__init__.py index c170d7dd3ff7..4fe234a1d2e2 100644 --- a/packages/google-apps-chat/google/apps/chat/__init__.py +++ b/packages/google-apps-chat/google/apps/chat/__init__.py @@ -43,6 +43,7 @@ UploadAttachmentRequest, UploadAttachmentResponse, ) +from google.apps.chat_v1.types.audience import Audience from google.apps.chat_v1.types.availability import ( Availability, CustomStatus, @@ -199,6 +200,7 @@ "GetAttachmentRequest", "UploadAttachmentRequest", "UploadAttachmentResponse", + "Audience", "Availability", "CustomStatus", "DoNotDisturbMetadata", diff --git a/packages/google-apps-chat/google/apps/chat_v1/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/__init__.py index 1999c88497ba..4e039ddbb597 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/__init__.py @@ -45,6 +45,7 @@ UploadAttachmentRequest, UploadAttachmentResponse, ) +from .types.audience import Audience from .types.availability import ( Availability, CustomStatus, @@ -271,6 +272,7 @@ def _get_version(dependency_name): "AttachedGif", "Attachment", "AttachmentDataRef", + "Audience", "Availability", "CalendarEventLinkData", "CardWithId", diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py index 31f9eac566e1..45776c9412c1 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/async_client.py @@ -2535,6 +2535,27 @@ async def sample_update_space(): ``access_settings.audience`` is not supported with ``useAdminAccess``. + ``access_settings.access_permission_settings``: Updates + the `access permission + settings `__ + of who can discover and join the space where + ``spaceType`` field is ``SPACE``. Principals allowed to + join the space must also be allowed to discover it. To + update access permission settings for a space, the + authenticating user must be a space manager or assistant + manager and omit all other field masks in the request. + You can't update this field if the space is in `import + mode `__. + To learn more, see `Make a space discoverable to + specific + users `__. + ``access_settings.access_permission_settings`` is not + supported with ``useAdminAccess``. The supported field + masks include: + + - ``access_settings.access_permission_settings.discoverSpaceSetting`` + - ``access_settings.access_permission_settings.joinSpaceSetting`` + ``permission_settings``: Supports changing the `permission settings `__ diff --git a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py index 0c31dcee4e6a..ab5b5b7816da 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py +++ b/packages/google-apps-chat/google/apps/chat_v1/services/chat_service/client.py @@ -3161,6 +3161,27 @@ def sample_update_space(): ``access_settings.audience`` is not supported with ``useAdminAccess``. + ``access_settings.access_permission_settings``: Updates + the `access permission + settings `__ + of who can discover and join the space where + ``spaceType`` field is ``SPACE``. Principals allowed to + join the space must also be allowed to discover it. To + update access permission settings for a space, the + authenticating user must be a space manager or assistant + manager and omit all other field masks in the request. + You can't update this field if the space is in `import + mode `__. + To learn more, see `Make a space discoverable to + specific + users `__. + ``access_settings.access_permission_settings`` is not + supported with ``useAdminAccess``. The supported field + masks include: + + - ``access_settings.access_permission_settings.discoverSpaceSetting`` + - ``access_settings.access_permission_settings.joinSpaceSetting`` + ``permission_settings``: Supports changing the `permission settings `__ diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py index 7789b20893be..3510013cb86e 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/__init__.py @@ -36,6 +36,9 @@ UploadAttachmentRequest, UploadAttachmentResponse, ) +from .audience import ( + Audience, +) from .availability import ( Availability, CustomStatus, @@ -208,6 +211,7 @@ "GetAttachmentRequest", "UploadAttachmentRequest", "UploadAttachmentResponse", + "Audience", "Availability", "CustomStatus", "DoNotDisturbMetadata", diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/audience.py b/packages/google-apps-chat/google/apps/chat_v1/types/audience.py new file mode 100644 index 000000000000..65aa5147e080 --- /dev/null +++ b/packages/google-apps-chat/google/apps/chat_v1/types/audience.py @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.chat.v1", + manifest={ + "Audience", + }, +) + + +class Audience(proto.Message): + r"""A target audience in Google Chat. A target audience represents a + group of users within a Google Workspace organization, defined by an + administrator. Target audiences are used to configure access and + visibility settings for resources, such as making a space + discoverable to a specific group of users. + + For more details, see `Target + audiences `__ and `Make + a space discoverable to a target + audience `__. + + Attributes: + name (str): + The resource name of the `target + audience `__ + who can discover or join the space. For details, see `Make a + space discoverable to a target + audience `__. + Format: ``audiences/{audience}`` + + To use the default target audience for the Google Workspace + organization, set to ``audiences/default``. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-apps-chat/google/apps/chat_v1/types/space.py b/packages/google-apps-chat/google/apps/chat_v1/types/space.py index 30f2a0230be3..8ec09eba3d06 100644 --- a/packages/google-apps-chat/google/apps/chat_v1/types/space.py +++ b/packages/google-apps-chat/google/apps/chat_v1/types/space.py @@ -21,6 +21,7 @@ import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore +from google.apps.chat_v1.types import audience as gc_audience from google.apps.chat_v1.types import history_state __protobuf__ = proto.module( @@ -428,6 +429,11 @@ class AccessSettings(proto.Message): Setting the target audience requires `user authentication `__. + access_permission_settings (google.apps.chat_v1.types.Space.AccessPermissionSettings): + Optional. Access permission settings for the space. + + To set the target audience when creating a space, specify + the ``accessSettings.audience`` field in your request. """ class AccessState(proto.Enum): @@ -467,6 +473,68 @@ class AccessState(proto.Enum): proto.STRING, number=3, ) + access_permission_settings: "Space.AccessPermissionSettings" = proto.Field( + proto.MESSAGE, + number=5, + message="Space.AccessPermissionSettings", + ) + + class AccessPermissionSettings(proto.Message): + r"""Access permission settings for a space. + + Attributes: + discover_space_setting (google.apps.chat_v1.types.Space.AccessPermissionSetting): + Optional. Access permission setting for + discovering the space. + join_space_setting (google.apps.chat_v1.types.Space.AccessPermissionSetting): + Optional. Access permission setting for + joining the space. + """ + + discover_space_setting: "Space.AccessPermissionSetting" = proto.Field( + proto.MESSAGE, + number=1, + message="Space.AccessPermissionSetting", + ) + join_space_setting: "Space.AccessPermissionSetting" = proto.Field( + proto.MESSAGE, + number=2, + message="Space.AccessPermissionSetting", + ) + + class AccessPermissionSetting(proto.Message): + r"""An access permission setting. + + Attributes: + principals (MutableSequence[google.apps.chat_v1.types.Space.Principal]): + Optional. Unordered list. Allowed principals + for this permission. + """ + + principals: MutableSequence["Space.Principal"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Space.Principal", + ) + + class Principal(proto.Message): + r"""A principal representing an entity granted access. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + audience (google.apps.chat_v1.types.Audience): + An audience. + + This field is a member of `oneof`_ ``principal_type``. + """ + + audience: gc_audience.Audience = proto.Field( + proto.MESSAGE, + number=1, + oneof="principal_type", + message=gc_audience.Audience, + ) class PermissionSettings(proto.Message): r"""`Permission @@ -1059,6 +1127,26 @@ class UpdateSpaceRequest(proto.Message): ``access_settings.audience`` is not supported with ``useAdminAccess``. + ``access_settings.access_permission_settings``: Updates the + `access permission + settings `__ + of who can discover and join the space where ``spaceType`` + field is ``SPACE``. Principals allowed to join the space + must also be allowed to discover it. To update access + permission settings for a space, the authenticating user + must be a space manager or assistant manager and omit all + other field masks in the request. You can't update this + field if the space is in `import + mode `__. + To learn more, see `Make a space discoverable to specific + users `__. + ``access_settings.access_permission_settings`` is not + supported with ``useAdminAccess``. The supported field masks + include: + + - ``access_settings.access_permission_settings.discoverSpaceSetting`` + - ``access_settings.access_permission_settings.joinSpaceSetting`` + ``permission_settings``: Supports changing the `permission settings `__ of a space. When updating permission settings, you can only diff --git a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py index 37182bee9718..23946ead969a 100644 --- a/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py +++ b/packages/google-apps-chat/tests/unit/gapic/chat_v1/test_chat_service.py @@ -69,6 +69,7 @@ action_status, annotation, attachment, + audience, availability, contextual_addon, deletion_metadata, @@ -29848,7 +29849,16 @@ def test_create_message_rest_call_success(request_type): "joined_direct_human_user_count": 3185, "joined_group_count": 1933, }, - "access_settings": {"access_state": 1, "audience": "audience_value"}, + "access_settings": { + "access_state": 1, + "audience": "audience_value", + "access_permission_settings": { + "discover_space_setting": { + "principals": [{"audience": {"name": "name_value"}}] + }, + "join_space_setting": {}, + }, + }, "customer": "customer_value", "space_uri": "space_uri_value", "predefined_permission_settings": 1, @@ -31071,7 +31081,16 @@ def test_update_message_rest_call_success(request_type): "joined_direct_human_user_count": 3185, "joined_group_count": 1933, }, - "access_settings": {"access_state": 1, "audience": "audience_value"}, + "access_settings": { + "access_state": 1, + "audience": "audience_value", + "access_permission_settings": { + "discover_space_setting": { + "principals": [{"audience": {"name": "name_value"}}] + }, + "join_space_setting": {}, + }, + }, "customer": "customer_value", "space_uri": "space_uri_value", "predefined_permission_settings": 1, @@ -32168,7 +32187,16 @@ def test_create_space_rest_call_success(request_type): "joined_direct_human_user_count": 3185, "joined_group_count": 1933, }, - "access_settings": {"access_state": 1, "audience": "audience_value"}, + "access_settings": { + "access_state": 1, + "audience": "audience_value", + "access_permission_settings": { + "discover_space_setting": { + "principals": [{"audience": {"name": "name_value"}}] + }, + "join_space_setting": {}, + }, + }, "customer": "customer_value", "space_uri": "space_uri_value", "predefined_permission_settings": 1, @@ -32585,7 +32613,16 @@ def test_update_space_rest_call_success(request_type): "joined_direct_human_user_count": 3185, "joined_group_count": 1933, }, - "access_settings": {"access_state": 1, "audience": "audience_value"}, + "access_settings": { + "access_state": 1, + "audience": "audience_value", + "access_permission_settings": { + "discover_space_setting": { + "principals": [{"audience": {"name": "name_value"}}] + }, + "join_space_setting": {}, + }, + }, "customer": "customer_value", "space_uri": "space_uri_value", "predefined_permission_settings": 1, diff --git a/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py b/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py index 9cbc6dab43bd..21ef676028d3 100644 --- a/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py +++ b/packages/google-cloud-batch/google/cloud/batch_v1alpha/types/job.py @@ -615,6 +615,10 @@ class AllocationPolicy(proto.Message): The tags identify valid sources or targets for network firewalls. Each tag must be 1-63 characters long, and comply with `RFC1035 `__. + instance_flexibility_policy (google.cloud.batch_v1alpha.types.AllocationPolicy.InstanceFlexibilityPolicy): + Optional. The instance flexibility policy for the job. This + configuration overrides the ``instances`` configuration. + Only allowed in job level. Not allowed in task group level. """ class ProvisioningModel(proto.Enum): @@ -1033,6 +1037,8 @@ class InstancePolicyOrTemplate(proto.Message): class NetworkInterface(proto.Message): r"""A network interface. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: network (str): The URL of an existing network resource. You can specify the @@ -1063,8 +1069,32 @@ class NetworkInterface(proto.Message): and https://cloud.google.com/nat/docs/gce-example#create-nat for more information. + nic_type (google.cloud.batch_v1alpha.types.AllocationPolicy.NetworkInterface.NicType): + Optional. The NIC type of the network + interface. + + This field is a member of `oneof`_ ``_nic_type``. """ + class NicType(proto.Enum): + r"""Compute Engine VM instance NIC type. + + Values: + NIC_TYPE_UNSPECIFIED (0): + No type specified. + GVNIC (1): + GVNIC + IRDMA (2): + IRDMA + MRDMA (3): + MRDMA + """ + + NIC_TYPE_UNSPECIFIED = 0 + GVNIC = 1 + IRDMA = 2 + MRDMA = 3 + network: str = proto.Field( proto.STRING, number=1, @@ -1077,6 +1107,12 @@ class NetworkInterface(proto.Message): proto.BOOL, number=3, ) + nic_type: "AllocationPolicy.NetworkInterface.NicType" = proto.Field( + proto.ENUM, + number=7, + optional=True, + enum="AllocationPolicy.NetworkInterface.NicType", + ) class NetworkPolicy(proto.Message): r"""NetworkPolicy describes VM instance network configurations. @@ -1124,6 +1160,71 @@ class PlacementPolicy(proto.Message): number=2, ) + class InstanceFlexibilityPolicy(proto.Message): + r"""Allows creating VMs from multiple types of machines. Instance + flexibility configuration overrides instances configuration. + + Attributes: + instance_selections (MutableMapping[str, google.cloud.batch_v1alpha.types.AllocationPolicy.InstanceSelection]): + Required. Named instance selections configuring properties + that the group will use when creating new VMs. The map key + is a user-specified name for the instance selection. The key + must be 1-63 characters long, and comply with + `RFC1035 `__. + Specifically, the key must consist of lowercase letters, + numbers, and hyphens. The first character must be a + lowercase letter, and the last character must be a lowercase + letter or number. The maximum number of instance selections + is 50. Exceeding this limit results in a validation error + with code ``INVALID_ARGUMENT``. + """ + + instance_selections: MutableMapping[ + str, "AllocationPolicy.InstanceSelection" + ] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=1, + message="AllocationPolicy.InstanceSelection", + ) + + class InstanceSelection(proto.Message): + r"""Defines an instance selection for a given instance + flexibility policy. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + machine_types (MutableSequence[str]): + Required. The Compute Engine machine type IDs. Only the + machine type ID is supported, such as ``n1-standard-16``. + Full or partial URLs are not accepted. The total maximum + number of machine types across all instance selections is + 200. Exceeding this limit results in a validation error with + code ``INVALID_ARGUMENT``. + rank (int): + Optional. Indicates the preference of this + instance selection. Lower number means higher + preference. First try is to create a VM based on + the machine-type with lowest rank and fallback + to next rank based on availability. Machine + types and instance selections with the same rank + have the same preference. + + This field is a member of `oneof`_ ``_rank``. + """ + + machine_types: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + rank: int = proto.Field( + proto.INT32, + number=2, + optional=True, + ) + location: LocationPolicy = proto.Field( proto.MESSAGE, number=1, @@ -1176,6 +1277,11 @@ class PlacementPolicy(proto.Message): proto.STRING, number=11, ) + instance_flexibility_policy: InstanceFlexibilityPolicy = proto.Field( + proto.MESSAGE, + number=12, + message=InstanceFlexibilityPolicy, + ) class TaskGroup(proto.Message): diff --git a/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py b/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py index b452f770aacc..eb05fcce1476 100644 --- a/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py +++ b/packages/google-cloud-batch/tests/unit/gapic/batch_v1alpha/test_batch_service.py @@ -9896,6 +9896,7 @@ def test_create_job_rest_call_success(request_type): "network": "network_value", "subnetwork": "subnetwork_value", "no_external_ip_address": True, + "nic_type": 1, } ] }, @@ -9904,6 +9905,7 @@ def test_create_job_rest_call_success(request_type): "max_distance": 1264, }, "tags": ["tags_value1", "tags_value2"], + "instance_flexibility_policy": {"instance_selections": {}}, }, "labels": {}, "task_environments": {}, @@ -10667,6 +10669,7 @@ def test_update_job_rest_call_success(request_type): "network": "network_value", "subnetwork": "subnetwork_value", "no_external_ip_address": True, + "nic_type": 1, } ] }, @@ -10675,6 +10678,7 @@ def test_update_job_rest_call_success(request_type): "max_distance": 1264, }, "tags": ["tags_value1", "tags_value2"], + "instance_flexibility_policy": {"instance_selections": {}}, }, "labels": {}, "task_environments": {}, diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/hosts.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/hosts.rst new file mode 100644 index 000000000000..39221c48ffd9 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/hosts.rst @@ -0,0 +1,10 @@ +Hosts +----------------------- + +.. automodule:: google.cloud.compute_v1beta.services.hosts + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.hosts.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/image_views.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/image_views.rst new file mode 100644 index 000000000000..898825be39ba --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/image_views.rst @@ -0,0 +1,6 @@ +ImageViews +---------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.image_views + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/organization_rollout_plans.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/organization_rollout_plans.rst new file mode 100644 index 000000000000..6dc953c7c014 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/organization_rollout_plans.rst @@ -0,0 +1,10 @@ +OrganizationRolloutPlans +------------------------------------------ + +.. automodule:: google.cloud.compute_v1beta.services.organization_rollout_plans + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.organization_rollout_plans.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/organization_rollouts.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/organization_rollouts.rst new file mode 100644 index 000000000000..7528474a6e56 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/organization_rollouts.rst @@ -0,0 +1,10 @@ +OrganizationRollouts +-------------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.organization_rollouts + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.organization_rollouts.pagers + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/project_views.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/project_views.rst new file mode 100644 index 000000000000..6165b77c73e2 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/project_views.rst @@ -0,0 +1,6 @@ +ProjectViews +------------------------------ + +.. automodule:: google.cloud.compute_v1beta.services.project_views + :members: + :inherited-members: diff --git a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/reliability_risks.rst b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/reliability_risks.rst new file mode 100644 index 000000000000..ea30cfded1bc --- /dev/null +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/reliability_risks.rst @@ -0,0 +1,10 @@ +ReliabilityRisks +---------------------------------- + +.. automodule:: google.cloud.compute_v1beta.services.reliability_risks + :members: + :inherited-members: + +.. automodule:: google.cloud.compute_v1beta.services.reliability_risks.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 db8a5f2957e3..5885cb33ce6d 100644 --- a/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst +++ b/packages/google-cloud-compute-v1beta/docs/compute_v1beta/services_.rst @@ -26,8 +26,10 @@ Services for Google Cloud Compute v1beta API global_public_delegated_prefixes global_vm_extension_policies health_checks + hosts image_family_views images + image_views instance_group_manager_resize_requests instance_group_managers instance_groups @@ -55,10 +57,13 @@ Services for Google Cloud Compute v1beta API node_groups node_templates node_types + organization_rollout_plans + organization_rollouts organization_security_policies packet_mirrorings preview_features projects + project_views public_advertised_prefixes public_delegated_prefixes region_autoscalers @@ -98,6 +103,7 @@ Services for Google Cloud Compute v1beta API region_target_tcp_proxies region_url_maps region_zones + reliability_risks reservation_blocks reservations reservation_slots 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 6d9e0eafb450..d0e3b88e1e07 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 @@ -48,7 +48,9 @@ ) from .services.global_vm_extension_policies import GlobalVmExtensionPoliciesClient from .services.health_checks import HealthChecksClient +from .services.hosts import HostsClient from .services.image_family_views import ImageFamilyViewsClient +from .services.image_views import ImageViewsClient from .services.images import ImagesClient from .services.instance_group_manager_resize_requests import ( InstanceGroupManagerResizeRequestsClient, @@ -79,9 +81,12 @@ from .services.node_groups import NodeGroupsClient from .services.node_templates import NodeTemplatesClient from .services.node_types import NodeTypesClient +from .services.organization_rollout_plans import OrganizationRolloutPlansClient +from .services.organization_rollouts import OrganizationRolloutsClient from .services.organization_security_policies import OrganizationSecurityPoliciesClient from .services.packet_mirrorings import PacketMirroringsClient from .services.preview_features import PreviewFeaturesClient +from .services.project_views import ProjectViewsClient from .services.projects import ProjectsClient from .services.public_advertised_prefixes import PublicAdvertisedPrefixesClient from .services.public_delegated_prefixes import PublicDelegatedPrefixesClient @@ -128,6 +133,7 @@ from .services.region_url_maps import RegionUrlMapsClient from .services.region_zones import RegionZonesClient from .services.regions import RegionsClient +from .services.reliability_risks import ReliabilityRisksClient from .services.reservation_blocks import ReservationBlocksClient from .services.reservation_slots import ReservationSlotsClient from .services.reservation_sub_blocks import ReservationSubBlocksClient @@ -207,6 +213,8 @@ AddTrafficClassificationRuleRegionNetworkPolicyRequest, AdoptInstancesRegionInstanceGroupManagerRequest, AdvancedMachineFeatures, + AdvanceOrganizationRolloutRequest, + AdvanceRolloutRequest, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, AggregatedListAutoscalersRequest, @@ -336,6 +344,7 @@ BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy, BackendServiceLocalityLoadBalancingPolicyConfigPolicy, BackendServiceLogConfig, + BackendServiceLogConfigLoggingHttpHeader, BackendServiceNetworkPassThroughLbTrafficPolicy, BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity, BackendServiceOrchestrationInfo, @@ -376,6 +385,7 @@ CalendarModeRecommendation, CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, + CancelOrganizationRolloutRequest, CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, @@ -436,6 +446,7 @@ CustomErrorResponsePolicyCustomErrorResponseRule, Data, Date, + DateTime, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -484,6 +495,8 @@ DeleteNodeGroupRequest, DeleteNodesNodeGroupRequest, DeleteNodeTemplateRequest, + DeleteOrganizationRolloutPlanRequest, + DeleteOrganizationRolloutRequest, DeleteOrganizationSecurityPolicyRequest, DeletePacketMirroringRequest, DeletePerInstanceConfigsInstanceGroupManagerRequest, @@ -687,6 +700,7 @@ GetHealthRegionCompositeHealthCheckRequest, GetHealthRegionHealthSourceRequest, GetHealthTargetPoolRequest, + GetHostRequest, GetIamPolicyBackendBucketRequest, GetIamPolicyBackendServiceRequest, GetIamPolicyDiskRequest, @@ -723,6 +737,7 @@ GetIamPolicySubnetworkRequest, GetImageFamilyViewRequest, GetImageRequest, + GetImageViewRequest, GetInstanceGroupManagerRequest, GetInstanceGroupManagerResizeRequestRequest, GetInstanceGroupRequest, @@ -756,6 +771,8 @@ GetNodeTypeRequest, GetOperationalStatusInterconnectAttachmentGroupRequest, GetOperationalStatusInterconnectGroupRequest, + GetOrganizationRolloutPlanRequest, + GetOrganizationRolloutRequest, GetOrganizationSecurityPolicyRequest, GetPacketMirroringRequest, GetPacketMirroringRuleFirewallPolicyRequest, @@ -763,6 +780,7 @@ GetPartnerMetadataInstanceRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -800,6 +818,7 @@ GetRegionTargetHttpsProxyRequest, GetRegionTargetTcpProxyRequest, GetRegionUrlMapRequest, + GetReliabilityRiskRequest, GetReservationBlockRequest, GetReservationRequest, GetReservationSlotRequest, @@ -842,6 +861,7 @@ GetTargetVpnGatewayRequest, GetTrafficClassificationRuleRegionNetworkPolicyRequest, GetUrlMapRequest, + GetVersionHostRequest, GetVersionOperationMetadata, GetVersionOperationMetadataSbomInfo, GetVersionReservationSlotRequest, @@ -903,7 +923,12 @@ HealthStatusForNetworkEndpoint, Help, HelpLink, + Host, + HostPhysicalTopology, HostRule, + HostsGetVersionRequest, + HostsListResponse, + HostStatus, HTTP2HealthCheck, HttpFaultAbort, HttpFaultDelay, @@ -923,7 +948,9 @@ Image, ImageFamilyView, ImageList, + ImageOptimizationPolicy, ImageParams, + ImageView, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -963,6 +990,7 @@ InsertNetworkRequest, InsertNodeGroupRequest, InsertNodeTemplateRequest, + InsertOrganizationRolloutPlanRequest, InsertOrganizationSecurityPolicyRequest, InsertPacketMirroringRequest, InsertPublicAdvertisedPrefixeRequest, @@ -1253,6 +1281,7 @@ ListGlobalPublicDelegatedPrefixesRequest, ListGlobalVmExtensionPoliciesRequest, ListHealthChecksRequest, + ListHostsRequest, ListImagesRequest, ListInstanceGroupManagerResizeRequestsRequest, ListInstanceGroupManagersRequest, @@ -1288,6 +1317,8 @@ ListNodesNodeGroupsRequest, ListNodeTemplatesRequest, ListNodeTypesRequest, + ListOrganizationRolloutPlansRequest, + ListOrganizationRolloutsRequest, ListOrganizationSecurityPoliciesRequest, ListPacketMirroringsRequest, ListPeeringRoutesNetworksRequest, @@ -1333,6 +1364,7 @@ ListRegionTargetTcpProxiesRequest, ListRegionUrlMapsRequest, ListRegionZonesRequest, + ListReliabilityRisksRequest, ListReservationBlocksRequest, ListReservationSlotsRequest, ListReservationsRequest, @@ -1511,6 +1543,7 @@ OperationAggregatedList, OperationList, OperationsScopedList, + OrganizationRolloutsListResponse, OrganizationSecurityPoliciesListAssociationsResponse, OutlierDetection, PacketIntervals, @@ -1598,12 +1631,16 @@ PatchWireGroupRequest, PathMatcher, PathRule, + PauseOrganizationRolloutRequest, + PauseRolloutRequest, PerformMaintenanceInstanceRequest, PerformMaintenanceNodeGroupRequest, PerformMaintenanceReservationBlockRequest, PerformMaintenanceReservationRequest, PerformMaintenanceReservationSubBlockRequest, PerInstanceConfig, + PeriodicPartialMaintenanceSchedule, + PersistentDiskResourceCommitment, Policy, PreconfiguredWafSet, PreservedState, @@ -1625,6 +1662,7 @@ ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, ProjectsSetManagedProtectionTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -1640,6 +1678,7 @@ RecreateInstancesInstanceGroupManagerRequest, RecreateInstancesRegionInstanceGroupManagerRequest, Reference, + RegexRewrite, Region, RegionAddressesMoveRequest, RegionAutoscalerList, @@ -1686,6 +1725,8 @@ RegionSnapshotUpdateKmsKeyRequest, RegionTargetHttpsProxiesSetSslCertificatesRequest, RegionUrlMapsValidateRequest, + ReliabilityRisk, + ReliabilityRisksListResponse, RemoveAssociationFirewallPolicyRequest, RemoveAssociationNetworkFirewallPolicyRequest, RemoveAssociationOrganizationSecurityPolicyRequest, @@ -1774,12 +1815,18 @@ ResourceStatus, ResourceStatusEffectiveInstanceMetadata, ResourceStatusPhysicalHostTopology, + ResourceStatusPhysicalHostTopologyAdditionalAttributes, ResourceStatusReservationConsumptionInfo, ResourceStatusScheduling, ResourceStatusShutdownDetails, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + ResumeOrganizationRolloutRequest, + ResumeRolloutRequest, + RiskDetails, + RiskDetailsGlobalDnsInsight, + RiskRecommendation, Rollout, RolloutPlan, RolloutPlansListResponse, @@ -2000,6 +2047,7 @@ SetUrlMapTargetHttpsProxyRequest, SetUsageExportBucketProjectRequest, ShareSettings, + ShareSettingsFolderConfig, ShareSettingsProjectConfig, ShieldedInstanceConfig, ShieldedInstanceIdentity, @@ -2223,6 +2271,7 @@ TestIamPermissionsVpnTunnelRequest, TestPermissionsRequest, TestPermissionsResponse, + TimeZone, Uint128, UpcomingMaintenance, UpdateAccessConfigInstanceRequest, @@ -2339,6 +2388,7 @@ XpnResourceId, Zone, ZoneList, + ZoneResourceStatus, ZoneSetLabelsRequest, ZoneSetNestedPolicyRequest, ZoneSetPolicyRequest, @@ -2474,6 +2524,8 @@ def _get_version(dependency_name): "AddressesClient", "AddressesScopedList", "AdoptInstancesRegionInstanceGroupManagerRequest", + "AdvanceOrganizationRolloutRequest", + "AdvanceRolloutRequest", "AdvancedMachineFeatures", "AdviceClient", "AggregatedListAcceleratorTypesRequest", @@ -2606,6 +2658,7 @@ def _get_version(dependency_name): "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -2647,6 +2700,7 @@ def _get_version(dependency_name): "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", + "CancelOrganizationRolloutRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", @@ -2708,6 +2762,7 @@ def _get_version(dependency_name): "CustomerEncryptionKeyProtectedDisk", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2756,6 +2811,8 @@ def _get_version(dependency_name): "DeleteNodeGroupRequest", "DeleteNodeTemplateRequest", "DeleteNodesNodeGroupRequest", + "DeleteOrganizationRolloutPlanRequest", + "DeleteOrganizationRolloutRequest", "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", @@ -2969,6 +3026,7 @@ def _get_version(dependency_name): "GetHealthRegionCompositeHealthCheckRequest", "GetHealthRegionHealthSourceRequest", "GetHealthTargetPoolRequest", + "GetHostRequest", "GetIamPolicyBackendBucketRequest", "GetIamPolicyBackendServiceRequest", "GetIamPolicyDiskRequest", @@ -3005,6 +3063,7 @@ def _get_version(dependency_name): "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", "GetImageRequest", + "GetImageViewRequest", "GetInstanceGroupManagerRequest", "GetInstanceGroupManagerResizeRequestRequest", "GetInstanceGroupRequest", @@ -3038,6 +3097,8 @@ def _get_version(dependency_name): "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationRolloutPlanRequest", + "GetOrganizationRolloutRequest", "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleFirewallPolicyRequest", @@ -3045,6 +3106,7 @@ def _get_version(dependency_name): "GetPartnerMetadataInstanceRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -3082,6 +3144,7 @@ def _get_version(dependency_name): "GetRegionTargetHttpsProxyRequest", "GetRegionTargetTcpProxyRequest", "GetRegionUrlMapRequest", + "GetReliabilityRiskRequest", "GetReservationBlockRequest", "GetReservationRequest", "GetReservationSlotRequest", @@ -3124,6 +3187,7 @@ def _get_version(dependency_name): "GetTargetVpnGatewayRequest", "GetTrafficClassificationRuleRegionNetworkPolicyRequest", "GetUrlMapRequest", + "GetVersionHostRequest", "GetVersionOperationMetadata", "GetVersionOperationMetadataSbomInfo", "GetVersionReservationSlotRequest", @@ -3194,7 +3258,13 @@ def _get_version(dependency_name): "HealthStatusForNetworkEndpoint", "Help", "HelpLink", + "Host", + "HostPhysicalTopology", "HostRule", + "HostStatus", + "HostsClient", + "HostsGetVersionRequest", + "HostsListResponse", "HttpFaultAbort", "HttpFaultDelay", "HttpFaultInjection", @@ -3212,7 +3282,10 @@ def _get_version(dependency_name): "ImageFamilyView", "ImageFamilyViewsClient", "ImageList", + "ImageOptimizationPolicy", "ImageParams", + "ImageView", + "ImageViewsClient", "ImagesClient", "InitialStateConfig", "InsertAddressRequest", @@ -3253,6 +3326,7 @@ def _get_version(dependency_name): "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationRolloutPlanRequest", "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", @@ -3559,6 +3633,7 @@ def _get_version(dependency_name): "ListGlobalPublicDelegatedPrefixesRequest", "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", + "ListHostsRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", "ListInstanceGroupManagersRequest", @@ -3594,6 +3669,8 @@ def _get_version(dependency_name): "ListNodeTemplatesRequest", "ListNodeTypesRequest", "ListNodesNodeGroupsRequest", + "ListOrganizationRolloutPlansRequest", + "ListOrganizationRolloutsRequest", "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", @@ -3639,6 +3716,7 @@ def _get_version(dependency_name): "ListRegionUrlMapsRequest", "ListRegionZonesRequest", "ListRegionsRequest", + "ListReliabilityRisksRequest", "ListReservationBlocksRequest", "ListReservationSlotsRequest", "ListReservationSubBlocksRequest", @@ -3828,6 +3906,9 @@ def _get_version(dependency_name): "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationRolloutPlansClient", + "OrganizationRolloutsClient", + "OrganizationRolloutsListResponse", "OrganizationSecurityPoliciesClient", "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", @@ -3917,12 +3998,16 @@ def _get_version(dependency_name): "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseOrganizationRolloutRequest", + "PauseRolloutRequest", "PerInstanceConfig", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", + "PeriodicPartialMaintenanceSchedule", + "PersistentDiskResourceCommitment", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -3938,6 +4023,8 @@ def _get_version(dependency_name): "PreviewFeaturesClient", "PreviewRouterRequest", "Project", + "ProjectView", + "ProjectViewsClient", "ProjectsClient", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", @@ -3963,6 +4050,7 @@ def _get_version(dependency_name): "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -4046,6 +4134,9 @@ def _get_version(dependency_name): "RegionUrlMapsValidateRequest", "RegionZonesClient", "RegionsClient", + "ReliabilityRisk", + "ReliabilityRisksClient", + "ReliabilityRisksListResponse", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", "RemoveAssociationOrganizationSecurityPolicyRequest", @@ -4139,12 +4230,18 @@ def _get_version(dependency_name): "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResourceStatusShutdownDetails", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeOrganizationRolloutRequest", + "ResumeRolloutRequest", + "RiskDetails", + "RiskDetailsGlobalDnsInsight", + "RiskRecommendation", "Rollout", "RolloutPlan", "RolloutPlanWave", @@ -4372,6 +4469,7 @@ def _get_version(dependency_name): "SetUrlMapTargetHttpsProxyRequest", "SetUsageExportBucketProjectRequest", "ShareSettings", + "ShareSettingsFolderConfig", "ShareSettingsProjectConfig", "ShieldedInstanceConfig", "ShieldedInstanceIdentity", @@ -4610,6 +4708,7 @@ def _get_version(dependency_name): "TestIamPermissionsVpnTunnelRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -4731,6 +4830,7 @@ def _get_version(dependency_name): "Zone", "ZoneList", "ZoneOperationsClient", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", 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 beb3e841fe38..9f180261dfa5 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 @@ -1127,6 +1127,30 @@ } } }, + "Hosts": { + "clients": { + "rest": { + "libraryClient": "HostsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "GetVersion": { + "methods": [ + "get_version" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "ImageFamilyViews": { "clients": { "rest": { @@ -1141,6 +1165,20 @@ } } }, + "ImageViews": { + "clients": { + "rest": { + "libraryClient": "ImageViewsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + } + } + } + } + }, "Images": { "clients": { "rest": { @@ -2828,6 +2866,79 @@ } } }, + "OrganizationRolloutPlans": { + "clients": { + "rest": { + "libraryClient": "OrganizationRolloutPlansClient", + "rpcs": { + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "Insert": { + "methods": [ + "insert" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, + "OrganizationRollouts": { + "clients": { + "rest": { + "libraryClient": "OrganizationRolloutsClient", + "rpcs": { + "Advance": { + "methods": [ + "advance" + ] + }, + "Cancel": { + "methods": [ + "cancel" + ] + }, + "Delete": { + "methods": [ + "delete" + ] + }, + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + }, + "Pause": { + "methods": [ + "pause" + ] + }, + "Resume": { + "methods": [ + "resume" + ] + } + } + } + } + }, "OrganizationSecurityPolicies": { "clients": { "rest": { @@ -2985,6 +3096,20 @@ } } }, + "ProjectViews": { + "clients": { + "rest": { + "libraryClient": "ProjectViewsClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + } + } + } + } + }, "Projects": { "clients": { "rest": { @@ -4845,6 +4970,25 @@ } } }, + "ReliabilityRisks": { + "clients": { + "rest": { + "libraryClient": "ReliabilityRisksClient", + "rpcs": { + "Get": { + "methods": [ + "get" + ] + }, + "List": { + "methods": [ + "list" + ] + } + } + } + } + }, "ReservationBlocks": { "clients": { "rest": { @@ -5114,6 +5258,11 @@ "rest": { "libraryClient": "RolloutsClient", "rpcs": { + "Advance": { + "methods": [ + "advance" + ] + }, "Cancel": { "methods": [ "cancel" @@ -5133,6 +5282,16 @@ "methods": [ "list" ] + }, + "Pause": { + "methods": [ + "pause" + ] + }, + "Resume": { + "methods": [ + "resume" + ] } } } diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/backend_services/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/backend_services/client.py index 0a280a9651e5..20abf844ea97 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/backend_services/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/backend_services/client.py @@ -2659,8 +2659,11 @@ def list_usable( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListUsablePager: - r"""Retrieves a list of all usable backend services in - the specified project. + r"""Retrieves a list of all usable backend services for + Application Load Balancers and Proxy Network Load + Balancers in the specified project. Backend services for + external and internal passthrough Network Load Balancers + are not included in the response. .. code-block:: python diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/__init__.py new file mode 100644 index 000000000000..d1c392c3a3a2 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 HostsClient + +__all__ = ("HostsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/client.py new file mode 100644 index 000000000000..d9afb7ab6040 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/client.py @@ -0,0 +1,1390 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 functools +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +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 extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.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__) + +import google.api_core.extended_operation as extended_operation # type: ignore + +from google.cloud.compute_v1beta.services.hosts import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, HostsTransport +from .transports.rest import HostsRestTransport + + +class HostsClientMeta(type): + """Metaclass for the Hosts 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[HostsTransport]] + _transport_registry["rest"] = HostsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[HostsTransport]: + """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 HostsClient(metaclass=HostsClientMeta): + """The Hosts API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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: + HostsClient: 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: + HostsClient: 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) -> HostsTransport: + """Returns the transport used by the client instance. + + Returns: + HostsTransport: 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 = HostsClient._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 = HostsClient._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 + ) -> str: + """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 = HostsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = HostsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = HostsClient._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 = HostsClient._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) -> str: + """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, HostsTransport, Callable[..., HostsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the hosts 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,HostsTransport,Callable[..., HostsTransport]]]): + 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 HostsTransport 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 = ( + HostsClient._read_environment_variables() + ) + self._client_cert_source = HostsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = HostsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, HostsTransport) + if transport_provided: + # transport is a HostsTransport 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(HostsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or HostsClient._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[HostsTransport], Callable[..., HostsTransport] + ] = ( + HostsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., HostsTransport], 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.HostsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "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.Hosts", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetHostRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + association: Optional[str] = None, + host: 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.Host: + r"""Retrieves information about the specified host. + + .. 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.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetHostRequest( + association="association_value", + host="host_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetHostRequest, dict]): + The request object. A request message for Hosts.Get. See + the method description for details. + project (str): + The project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request, formatted as RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + association (str): + The parent resource association for the Host. This field + specifies the hierarchical context (e.g., reservation, + block, sub-block) when accessing the host. For example, + reservations/reservation_name, + reservations/reservation_name/reservationBlocks/reservation_block_name + or + reservations/reservation_name/reservationBlocks/reservation_block_name/reservationSubBlocks/reservation_sub_block_name. + + This corresponds to the ``association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + host (str): + The name of the host, formatted as + RFC1035 or a resource ID number. + + This corresponds to the ``host`` 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.Host: + Represents a host 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, zone, association, host] + 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.GetHostRequest): + request = compute.GetHostRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if association is not None: + request.association = association + if host is not None: + request.host = host + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("association", request.association), + ("host", request.host), + ) + ), + ) + + # 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 get_version_unary( + self, + request: Optional[Union[compute.GetVersionHostRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + association: Optional[str] = None, + host: Optional[str] = None, + hosts_get_version_request_resource: Optional[ + compute.HostsGetVersionRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Allows customers to get SBOM versions of a host. + + .. 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_version(): + # Create a client + client = compute_v1beta.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetVersionHostRequest( + association="association_value", + host="host_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetVersionHostRequest, dict]): + The request object. A request message for + Hosts.GetVersion. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + association (str): + The parent resource association for + the Host. This field specifies the + hierarchical context (e.g., reservation, + block, sub-block) when accessing the + host. + + This corresponds to the ``association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + host (str): + The name of the host, formatted as + RFC1035 or a resource ID number. + + This corresponds to the ``host`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hosts_get_version_request_resource (google.cloud.compute_v1beta.types.HostsGetVersionRequest): + The body resource for this request + This corresponds to the ``hosts_get_version_request_resource`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + zone, + association, + host, + hosts_get_version_request_resource, + ] + 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.GetVersionHostRequest): + request = compute.GetVersionHostRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if association is not None: + request.association = association + if host is not None: + request.host = host + if hosts_get_version_request_resource is not None: + request.hosts_get_version_request_resource = ( + hosts_get_version_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("association", request.association), + ("host", request.host), + ) + ), + ) + + # 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 get_version( + self, + request: Optional[Union[compute.GetVersionHostRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + association: Optional[str] = None, + host: Optional[str] = None, + hosts_get_version_request_resource: Optional[ + compute.HostsGetVersionRequest + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Allows customers to get SBOM versions of a host. + + .. 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_version(): + # Create a client + client = compute_v1beta.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetVersionHostRequest( + association="association_value", + host="host_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetVersionHostRequest, dict]): + The request object. A request message for + Hosts.GetVersion. See the method + description for details. + project (str): + Project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + Name of the zone for this request. + Zone name should conform to RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + association (str): + The parent resource association for + the Host. This field specifies the + hierarchical context (e.g., reservation, + block, sub-block) when accessing the + host. + + This corresponds to the ``association`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + host (str): + The name of the host, formatted as + RFC1035 or a resource ID number. + + This corresponds to the ``host`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + hosts_get_version_request_resource (google.cloud.compute_v1beta.types.HostsGetVersionRequest): + The body resource for this request + This corresponds to the ``hosts_get_version_request_resource`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [ + project, + zone, + association, + host, + hosts_get_version_request_resource, + ] + 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.GetVersionHostRequest): + request = compute.GetVersionHostRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if association is not None: + request.association = association + if host is not None: + request.host = host + if hosts_get_version_request_resource is not None: + request.hosts_get_version_request_resource = ( + hosts_get_version_request_resource + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_version] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("association", request.association), + ("host", request.host), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._zone_operations_client + operation_request = compute.GetZoneOperationRequest() + operation_request.project = request.project + operation_request.zone = request.zone + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[Union[compute.ListHostsRequest, dict]] = None, + *, + project: Optional[str] = None, + zone: Optional[str] = None, + association: 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 hosts. + + .. 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.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.ListHostsRequest( + association="association_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ListHostsRequest, dict]): + The request object. A request message for Hosts.List. See + the method description for details. + project (str): + The project ID for this request. + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + zone (str): + The name of the zone for this + request, formatted as RFC1035. + + This corresponds to the ``zone`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + association (str): + The parent resource association for the Host. This field + specifies the hierarchical context (e.g., reservation, + block, sub-block) when accessing the host. For example, + reservations/reservation_name, + reservations/reservation_name/reservationBlocks/reservation_block_name + or + reservations/reservation_name/reservationBlocks/reservation_block_name/reservationSubBlocks/reservation_sub_block_name. + + This corresponds to the ``association`` 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.hosts.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, zone, association] + 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.ListHostsRequest): + request = compute.ListHostsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if zone is not None: + request.zone = zone + if association is not None: + request.association = association + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("project", request.project), + ("zone", request.zone), + ("association", request.association), + ) + ), + ) + + # 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) -> "HostsClient": + 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__ = ("HostsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/pagers.py new file mode 100644 index 000000000000..31115f2ed5a0 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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.HostsListResponse` 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.HostsListResponse` + 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.HostsListResponse], + request: compute.ListHostsRequest, + response: compute.HostsListResponse, + *, + 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.ListHostsRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.HostsListResponse): + 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.ListHostsRequest(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.HostsListResponse]: + 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.Host]: + 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/hosts/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/README.rst new file mode 100644 index 000000000000..efa83fd13649 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``HostsTransport`` is the ABC for all transports. + +- public child ``HostsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``HostsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseHostsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``HostsRestTransport`` 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/hosts/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/__init__.py new file mode 100644 index 000000000000..55d5c75ce0f8 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 HostsTransport +from .rest import HostsRestInterceptor, HostsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[HostsTransport]] +_transport_registry["rest"] = HostsRestTransport + +__all__ = ( + "HostsTransport", + "HostsRestTransport", + "HostsRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/base.py new file mode 100644 index 000000000000..f154cfa1f42b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/base.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Any, Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +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.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.services import zone_operations +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 HostsTransport(abc.ABC): + """Abstract transport class for Hosts.""" + + AUTH_SCOPES = ( + "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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + self._extended_operations_services: Dict[str, Any] = {} + + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.get_version: gapic_v1.method.wrap_method( + self.get_version, + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetHostRequest], Union[compute.Host, Awaitable[compute.Host]] + ]: + raise NotImplementedError() + + @property + def get_version( + self, + ) -> Callable[ + [compute.GetVersionHostRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListHostsRequest], + Union[compute.HostsListResponse, Awaitable[compute.HostsListResponse]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _zone_operations_client(self) -> zone_operations.ZoneOperationsClient: + ex_op_service = self._extended_operations_services.get("zone_operations") + if not ex_op_service: + ex_op_service = zone_operations.ZoneOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + self._extended_operations_services["zone_operations"] = ex_op_service + + return ex_op_service + + +__all__ = ("HostsTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/rest.py new file mode 100644 index 000000000000..612d9295bf2b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/rest.py @@ -0,0 +1,825 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +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 +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 _BaseHostsRestTransport + +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 HostsRestInterceptor: + """Interceptor for Hosts. + + 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 HostsRestTransport. + + .. code-block:: python + class MyCustomHostsInterceptor(HostsRestInterceptor): + 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_get_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_version(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 = HostsRestTransport(interceptor=MyCustomHostsInterceptor()) + client = HostsClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetHostRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetHostRequest, 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 Hosts server. + """ + return request, metadata + + def post_get(self, response: compute.Host) -> compute.Host: + """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 Hosts 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.Host, metadata: Sequence[Tuple[str, Union[str, bytes]]] + ) -> Tuple[compute.Host, 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 Hosts 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_get_version( + self, + request: compute.GetVersionHostRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetVersionHostRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the Hosts server. + """ + return request, metadata + + def post_get_version(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for get_version + + DEPRECATED. Please use the `post_get_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Hosts server but before + it is returned to user code. This `post_get_version` interceptor runs + before the `post_get_version_with_metadata` interceptor. + """ + return response + + def post_get_version_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Hosts server but before it is returned to user code. + + We recommend only using this `post_get_version_with_metadata` + interceptor in new development instead of the `post_get_version` interceptor. + When both interceptors are used, this `post_get_version_with_metadata` interceptor runs after the + `post_get_version` interceptor. The (possibly modified) response returned by + `post_get_version` will be passed to + `post_get_version_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListHostsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ListHostsRequest, 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 Hosts server. + """ + return request, metadata + + def post_list( + self, response: compute.HostsListResponse + ) -> compute.HostsListResponse: + """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 Hosts 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.HostsListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.HostsListResponse, 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 Hosts 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 HostsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: HostsRestInterceptor + + +class HostsRestTransport(_BaseHostsRestTransport): + """REST backend synchronous transport for Hosts. + + The Hosts 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[HostsRestInterceptor] = 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. + interceptor (Optional[HostsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 HostsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseHostsRestTransport._BaseGet, HostsRestStub): + def __hash__(self): + return hash("HostsRestTransport.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.GetHostRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Host: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetHostRequest): + The request object. A request message for Hosts.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.Host: + Represents a host resource. + """ + + http_options = _BaseHostsRestTransport._BaseGet._get_http_options() + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseHostsRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseHostsRestTransport._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.HostsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HostsRestTransport._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.Host() + pb_resp = compute.Host.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.Host.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.HostsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetVersion(_BaseHostsRestTransport._BaseGetVersion, HostsRestStub): + def __hash__(self): + return hash("HostsRestTransport.GetVersion") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: compute.GetVersionHostRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the get version method over HTTP. + + Args: + request (~.compute.GetVersionHostRequest): + The request object. A request message for + Hosts.GetVersion. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseHostsRestTransport._BaseGetVersion._get_http_options() + + request, metadata = self._interceptor.pre_get_version(request, metadata) + transcoded_request = ( + _BaseHostsRestTransport._BaseGetVersion._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseHostsRestTransport._BaseGetVersion._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseHostsRestTransport._BaseGetVersion._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.HostsClient.GetVersion", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "rpcName": "GetVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HostsRestTransport._GetVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_version(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_version_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.HostsClient.get_version", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "rpcName": "GetVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BaseHostsRestTransport._BaseList, HostsRestStub): + def __hash__(self): + return hash("HostsRestTransport.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.ListHostsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.HostsListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListHostsRequest): + The request object. A request message for Hosts.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.HostsListResponse: + + """ + + http_options = _BaseHostsRestTransport._BaseList._get_http_options() + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseHostsRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseHostsRestTransport._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.HostsClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = HostsRestTransport._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.HostsListResponse() + pb_resp = compute.HostsListResponse.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.HostsListResponse.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.HostsClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.Hosts", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get(self) -> Callable[[compute.GetHostRequest], compute.Host]: + # 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 get_version( + self, + ) -> Callable[[compute.GetVersionHostRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetVersion(self._session, self._host, self._interceptor) # type: ignore + + @property + def list(self) -> Callable[[compute.ListHostsRequest], compute.HostsListResponse]: + # 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__ = ("HostsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/rest_base.py new file mode 100644 index 000000000000..ef20d77ee7e9 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/hosts/transports/rest_base.py @@ -0,0 +1,239 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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, HostsTransport + + +class _BaseHostsRestTransport(HostsTransport): + """Base REST backend transport for Hosts. + + Note: This class is not meant to be used directly. Use its sync and + async sub-classes instead. + + This class defines the same methods as the primary client, so the + primary client can load the underlying transport implementation + and call it. + + It sends JSON representations of protocol buffers over HTTP/1.1 + """ + + def __init__( + self, + *, + host: str = "compute.googleapis.com", + credentials: Optional[Any] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + always_use_jwt_access: Optional[bool] = False, + url_scheme: str = "https", + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + Args: + host (Optional[str]): + The hostname to connect to (default: 'compute.googleapis.com'). + credentials (Optional[Any]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you are developing + your own client library. + always_use_jwt_access (Optional[bool]): Whether self signed JWT should + be used for service account credentials. + url_scheme: the protocol scheme for the API endpoint. Normally + "https", but for testing or local servers, + "http" can be specified. + """ + # Run the base constructor + maybe_url_match = re.match("^(?Phttp(?:s)?://)?(?P.*)$", host) + if maybe_url_match is None: + raise ValueError( + f"Unexpected hostname structure: {host}" + ) # pragma: NO COVER + + url_match_items = maybe_url_match.groupdict() + + host = f"{url_scheme}://{host}" if not url_match_items["scheme"] else host + + super().__init__( + host=host, + credentials=credentials, + client_info=client_info, + always_use_jwt_access=always_use_jwt_access, + api_audience=api_audience, + ) + + class _BaseGet: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/beta/projects/{project}/zones/{zone}/{association}/hosts/{host}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetHostRequest.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( + _BaseHostsRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseGetVersion: + 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": "post", + "uri": "/compute/beta/projects/{project}/zones/{zone}/{association}/hosts/{host}/getVersion", + "body": "hosts_get_version_request_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetVersionHostRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @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( + _BaseHostsRestTransport._BaseGetVersion._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseList: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/compute/beta/projects/{project}/zones/{zone}/{association}/hosts", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListHostsRequest.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( + _BaseHostsRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseHostsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/__init__.py new file mode 100644 index 000000000000..bd3a7be6596b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ImageViewsClient + +__all__ = ("ImageViewsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/client.py new file mode 100644 index 000000000000..ecd7a63dda7a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/client.py @@ -0,0 +1,859 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.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.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ImageViewsTransport +from .transports.rest import ImageViewsRestTransport + + +class ImageViewsClientMeta(type): + """Metaclass for the ImageViews 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[ImageViewsTransport]] + _transport_registry["rest"] = ImageViewsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ImageViewsTransport]: + """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 ImageViewsClient(metaclass=ImageViewsClientMeta): + """The ImageViews API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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: + ImageViewsClient: 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: + ImageViewsClient: 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) -> ImageViewsTransport: + """Returns the transport used by the client instance. + + Returns: + ImageViewsTransport: 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 = ImageViewsClient._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 = ImageViewsClient._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 + ) -> str: + """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 = ImageViewsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ImageViewsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ImageViewsClient._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 = ImageViewsClient._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) -> str: + """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, ImageViewsTransport, Callable[..., ImageViewsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the image views 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,ImageViewsTransport,Callable[..., ImageViewsTransport]]]): + 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 ImageViewsTransport 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 = ( + ImageViewsClient._read_environment_variables() + ) + self._client_cert_source = ImageViewsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ImageViewsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, ImageViewsTransport) + if transport_provided: + # transport is a ImageViewsTransport 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(ImageViewsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ImageViewsClient._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[ImageViewsTransport], Callable[..., ImageViewsTransport] + ] = ( + ImageViewsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ImageViewsTransport], 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.ImageViewsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.ImageViews", + "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.ImageViews", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetImageViewRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + resource_id: 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.ImageView: + r"""Returns the specified global ImageView resource, with + a regional context. + + .. 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.ImageViewsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetImageViewRequest( + project="project_value", + region="region_value", + resource_id="resource_id_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetImageViewRequest, dict]): + The request object. A request message for ImageViews.Get. + See the method description for details. + project (str): + Required. 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): + Required. Name of the region for this + request. + + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + resource_id (str): + Name of the image resource to return. + This corresponds to the ``resource_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.ImageView: + Represents a read-only view of a + global Image 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, resource_id] + 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.GetImageViewRequest): + request = compute.GetImageViewRequest(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 resource_id is not None: + request.resource_id = resource_id + + # 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), + ("resource_id", request.resource_id), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ImageViewsClient": + 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__ = ("ImageViewsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/README.rst new file mode 100644 index 000000000000..5c2f3bd36080 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``ImageViewsTransport`` is the ABC for all transports. + +- public child ``ImageViewsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``ImageViewsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseImageViewsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``ImageViewsRestTransport`` 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/image_views/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/__init__.py new file mode 100644 index 000000000000..d6f5bdd8cc20 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ImageViewsTransport +from .rest import ImageViewsRestInterceptor, ImageViewsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ImageViewsTransport]] +_transport_registry["rest"] = ImageViewsRestTransport + +__all__ = ( + "ImageViewsTransport", + "ImageViewsRestTransport", + "ImageViewsRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/base.py new file mode 100644 index 000000000000..578d07b8509c --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/base.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import google.auth # type: ignore +import google.protobuf +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.oauth2 import service_account # type: ignore + +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 ImageViewsTransport(abc.ABC): + """Abstract transport class for ImageViews.""" + + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetImageViewRequest], + Union[compute.ImageView, Awaitable[compute.ImageView]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ImageViewsTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/rest.py new file mode 100644 index 000000000000..6e29b98781c4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/rest.py @@ -0,0 +1,388 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +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 +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 _BaseImageViewsRestTransport + +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 ImageViewsRestInterceptor: + """Interceptor for ImageViews. + + 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 ImageViewsRestTransport. + + .. code-block:: python + class MyCustomImageViewsInterceptor(ImageViewsRestInterceptor): + 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 + + transport = ImageViewsRestTransport(interceptor=MyCustomImageViewsInterceptor()) + client = ImageViewsClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetImageViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetImageViewRequest, 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 ImageViews server. + """ + return request, metadata + + def post_get(self, response: compute.ImageView) -> compute.ImageView: + """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 ImageViews 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.ImageView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ImageView, 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 ImageViews 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 + + +@dataclasses.dataclass +class ImageViewsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ImageViewsRestInterceptor + + +class ImageViewsRestTransport(_BaseImageViewsRestTransport): + """REST backend synchronous transport for ImageViews. + + The ImageViews 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[ImageViewsRestInterceptor] = 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. + interceptor (Optional[ImageViewsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 ImageViewsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseImageViewsRestTransport._BaseGet, ImageViewsRestStub): + def __hash__(self): + return hash("ImageViewsRestTransport.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.GetImageViewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ImageView: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetImageViewRequest): + The request object. A request message for ImageViews.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.ImageView: + Represents a read-only view of a + global Image resource. + + """ + + http_options = _BaseImageViewsRestTransport._BaseGet._get_http_options() + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseImageViewsRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseImageViewsRestTransport._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.ImageViewsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ImageViews", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ImageViewsRestTransport._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.ImageView() + pb_resp = compute.ImageView.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.ImageView.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.ImageViewsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ImageViews", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get(self) -> Callable[[compute.GetImageViewRequest], compute.ImageView]: + # 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 kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ImageViewsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/rest_base.py new file mode 100644 index 000000000000..2301f233d988 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/image_views/transports/rest_base.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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, ImageViewsTransport + + +class _BaseImageViewsRestTransport(ImageViewsTransport): + """Base REST backend transport for ImageViews. + + 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}/imageViews/{resource_id}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetImageViewRequest.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( + _BaseImageViewsRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseImageViewsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/__init__.py new file mode 100644 index 000000000000..268bda352dfd --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 OrganizationRolloutPlansClient + +__all__ = ("OrganizationRolloutPlansClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/client.py new file mode 100644 index 000000000000..6f377d0b2499 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/client.py @@ -0,0 +1,1536 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 functools +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +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 extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.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__) + +import google.api_core.extended_operation as extended_operation # type: ignore + +from google.cloud.compute_v1beta.services.organization_rollout_plans import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, OrganizationRolloutPlansTransport +from .transports.rest import OrganizationRolloutPlansRestTransport + + +class OrganizationRolloutPlansClientMeta(type): + """Metaclass for the OrganizationRolloutPlans 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[OrganizationRolloutPlansTransport]] + _transport_registry["rest"] = OrganizationRolloutPlansRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[OrganizationRolloutPlansTransport]: + """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 OrganizationRolloutPlansClient(metaclass=OrganizationRolloutPlansClientMeta): + """The OrganizationRolloutPlans API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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: + OrganizationRolloutPlansClient: 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: + OrganizationRolloutPlansClient: 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) -> OrganizationRolloutPlansTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationRolloutPlansTransport: 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 = OrganizationRolloutPlansClient._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 = OrganizationRolloutPlansClient._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 + ) -> str: + """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 = OrganizationRolloutPlansClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = OrganizationRolloutPlansClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ( + OrganizationRolloutPlansClient._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 = OrganizationRolloutPlansClient._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) -> str: + """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, + OrganizationRolloutPlansTransport, + Callable[..., OrganizationRolloutPlansTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organization rollout plans 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,OrganizationRolloutPlansTransport,Callable[..., OrganizationRolloutPlansTransport]]]): + 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 OrganizationRolloutPlansTransport 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 = ( + OrganizationRolloutPlansClient._read_environment_variables() + ) + self._client_cert_source = ( + OrganizationRolloutPlansClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + ) + self._universe_domain = OrganizationRolloutPlansClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, OrganizationRolloutPlansTransport) + if transport_provided: + # transport is a OrganizationRolloutPlansTransport 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(OrganizationRolloutPlansTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or OrganizationRolloutPlansClient._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[OrganizationRolloutPlansTransport], + Callable[..., OrganizationRolloutPlansTransport], + ] = ( + OrganizationRolloutPlansClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OrganizationRolloutPlansTransport], 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.OrganizationRolloutPlansClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "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.OrganizationRolloutPlans", + "credentialsType": None, + }, + ) + + def delete_unary( + self, + request: Optional[ + Union[compute.DeleteOrganizationRolloutPlanRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout_plan: 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.Operation: + r"""Deletes an OrganizationRolloutPlan. + + .. 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_delete(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteOrganizationRolloutPlanRequest( + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteOrganizationRolloutPlanRequest, dict]): + The request object. A request message for + OrganizationRolloutPlans.Delete. See the + method description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan (str): + Name of the OrganizationRolloutPlan + resource to delete. + + This corresponds to the ``rollout_plan`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout_plan] + 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.DeleteOrganizationRolloutPlanRequest): + request = compute.DeleteOrganizationRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout_plan is not None: + request.rollout_plan = rollout_plan + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout_plan", request.rollout_plan), + ) + ), + ) + + # 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 delete( + self, + request: Optional[ + Union[compute.DeleteOrganizationRolloutPlanRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout_plan: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes an OrganizationRolloutPlan. + + .. 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_delete(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteOrganizationRolloutPlanRequest( + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteOrganizationRolloutPlanRequest, dict]): + The request object. A request message for + OrganizationRolloutPlans.Delete. See the + method description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan (str): + Name of the OrganizationRolloutPlan + resource to delete. + + This corresponds to the ``rollout_plan`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout_plan] + 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.DeleteOrganizationRolloutPlanRequest): + request = compute.DeleteOrganizationRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout_plan is not None: + request.rollout_plan = rollout_plan + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout_plan", request.rollout_plan), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[ + Union[compute.GetOrganizationRolloutPlanRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout_plan: 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.RolloutPlan: + r"""Gets details of a single organization-scoped + RolloutPlan. + + .. 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.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.GetOrganizationRolloutPlanRequest( + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetOrganizationRolloutPlanRequest, dict]): + The request object. A request message for + OrganizationRolloutPlans.Get. See the + method description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan (str): + Name of the persistent rollout plan + to return. + + This corresponds to the ``rollout_plan`` 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.RolloutPlan: + RolloutPlan resource. + + A RolloutPlan is the customer-defined + strategy to divide a large-scale change + into smaller increments, referred to as + "waves". Each wave targets a specific + portion of the overall affected area and + defines criteria that must be met before + progressing to the subsequent wave. + + """ + # 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 = [organization, rollout_plan] + 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.GetOrganizationRolloutPlanRequest): + request = compute.GetOrganizationRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout_plan is not None: + request.rollout_plan = rollout_plan + + # 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( + ( + ("organization", request.organization), + ("rollout_plan", request.rollout_plan), + ) + ), + ) + + # 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 insert_unary( + self, + request: Optional[ + Union[compute.InsertOrganizationRolloutPlanRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout_plan_resource: Optional[compute.RolloutPlan] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Creates a new RolloutPlan in a given organization and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_insert(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertOrganizationRolloutPlanRequest( + organization="organization_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.InsertOrganizationRolloutPlanRequest, dict]): + The request object. A request message for + OrganizationRolloutPlans.Insert. See the + method description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan_resource (google.cloud.compute_v1beta.types.RolloutPlan): + The body resource for this request + This corresponds to the ``rollout_plan_resource`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout_plan_resource] + 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.InsertOrganizationRolloutPlanRequest): + request = compute.InsertOrganizationRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout_plan_resource is not None: + request.rollout_plan_resource = rollout_plan_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization", request.organization),) + ), + ) + + # 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 insert( + self, + request: Optional[ + Union[compute.InsertOrganizationRolloutPlanRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout_plan_resource: Optional[compute.RolloutPlan] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates a new RolloutPlan in a given organization and + location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_insert(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertOrganizationRolloutPlanRequest( + organization="organization_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.InsertOrganizationRolloutPlanRequest, dict]): + The request object. A request message for + OrganizationRolloutPlans.Insert. See the + method description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout_plan_resource (google.cloud.compute_v1beta.types.RolloutPlan): + The body resource for this request + This corresponds to the ``rollout_plan_resource`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout_plan_resource] + 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.InsertOrganizationRolloutPlanRequest): + request = compute.InsertOrganizationRolloutPlanRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout_plan_resource is not None: + request.rollout_plan_resource = rollout_plan_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization", request.organization),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[ + Union[compute.ListOrganizationRolloutPlansRequest, dict] + ] = None, + *, + organization: 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"""Lists OrganizationRolloutPlans in a given + organization and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_list(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.ListOrganizationRolloutPlansRequest( + organization="organization_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.ListOrganizationRolloutPlansRequest, dict]): + The request object. A request message for + OrganizationRolloutPlans.List. See the + method description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` 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.organization_rollout_plans.pagers.ListPager: + Contains a list of RolloutPlan + resources. + 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 = [organization] + 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.ListOrganizationRolloutPlansRequest): + request = compute.ListOrganizationRolloutPlansRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + + # 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( + (("organization", request.organization),) + ), + ) + + # 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) -> "OrganizationRolloutPlansClient": + 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__ = ("OrganizationRolloutPlansClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/pagers.py new file mode 100644 index 000000000000..2d0ffedd7d03 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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.RolloutPlansListResponse` 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.RolloutPlansListResponse` + 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.RolloutPlansListResponse], + request: compute.ListOrganizationRolloutPlansRequest, + response: compute.RolloutPlansListResponse, + *, + 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.ListOrganizationRolloutPlansRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.RolloutPlansListResponse): + 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.ListOrganizationRolloutPlansRequest(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.RolloutPlansListResponse]: + 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.RolloutPlan]: + 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/organization_rollout_plans/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/README.rst new file mode 100644 index 000000000000..3e96943b49ee --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``OrganizationRolloutPlansTransport`` is the ABC for all transports. + +- public child ``OrganizationRolloutPlansGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``OrganizationRolloutPlansGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseOrganizationRolloutPlansRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``OrganizationRolloutPlansRestTransport`` 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/organization_rollout_plans/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/__init__.py new file mode 100644 index 000000000000..d0e1a9044b15 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 OrganizationRolloutPlansTransport +from .rest import ( + OrganizationRolloutPlansRestInterceptor, + OrganizationRolloutPlansRestTransport, +) + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationRolloutPlansTransport]] +_transport_registry["rest"] = OrganizationRolloutPlansRestTransport + +__all__ = ( + "OrganizationRolloutPlansTransport", + "OrganizationRolloutPlansRestTransport", + "OrganizationRolloutPlansRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/base.py new file mode 100644 index 000000000000..2fb874fc006f --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/base.py @@ -0,0 +1,265 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Any, Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +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.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.services import global_organization_operations +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 OrganizationRolloutPlansTransport(abc.ABC): + """Abstract transport class for OrganizationRolloutPlans.""" + + AUTH_SCOPES = ( + "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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + self._extended_operations_services: Dict[str, Any] = {} + + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=600.0, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.insert: gapic_v1.method.wrap_method( + self.insert, + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteOrganizationRolloutPlanRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetOrganizationRolloutPlanRequest], + Union[compute.RolloutPlan, Awaitable[compute.RolloutPlan]], + ]: + raise NotImplementedError() + + @property + def insert( + self, + ) -> Callable[ + [compute.InsertOrganizationRolloutPlanRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListOrganizationRolloutPlansRequest], + Union[ + compute.RolloutPlansListResponse, + Awaitable[compute.RolloutPlansListResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _global_organization_operations_client( + self, + ) -> global_organization_operations.GlobalOrganizationOperationsClient: + ex_op_service = self._extended_operations_services.get( + "global_organization_operations" + ) + if not ex_op_service: + ex_op_service = ( + global_organization_operations.GlobalOrganizationOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + ) + self._extended_operations_services["global_organization_operations"] = ( + ex_op_service + ) + + return ex_op_service + + +__all__ = ("OrganizationRolloutPlansTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/rest.py new file mode 100644 index 000000000000..1727a7304336 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/rest.py @@ -0,0 +1,1100 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +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 +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 _BaseOrganizationRolloutPlansRestTransport + +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 OrganizationRolloutPlansRestInterceptor: + """Interceptor for OrganizationRolloutPlans. + + 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 OrganizationRolloutPlansRestTransport. + + .. code-block:: python + class MyCustomOrganizationRolloutPlansInterceptor(OrganizationRolloutPlansRestInterceptor): + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + 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_insert(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_insert(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 = OrganizationRolloutPlansRestTransport(interceptor=MyCustomOrganizationRolloutPlansInterceptor()) + client = OrganizationRolloutPlansClient(transport=transport) + + + """ + + def pre_delete( + self, + request: compute.DeleteOrganizationRolloutPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteOrganizationRolloutPlanRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRolloutPlans server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + DEPRECATED. Please use the `post_delete_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRolloutPlans server but before + it is returned to user code. This `post_delete` interceptor runs + before the `post_delete_with_metadata` interceptor. + """ + return response + + def post_delete_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRolloutPlans server but before it is returned to user code. + + We recommend only using this `post_delete_with_metadata` + interceptor in new development instead of the `post_delete` interceptor. + When both interceptors are used, this `post_delete_with_metadata` interceptor runs after the + `post_delete` interceptor. The (possibly modified) response returned by + `post_delete` will be passed to + `post_delete_with_metadata`. + """ + return response, metadata + + def pre_get( + self, + request: compute.GetOrganizationRolloutPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetOrganizationRolloutPlanRequest, + 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 OrganizationRolloutPlans server. + """ + return request, metadata + + def post_get(self, response: compute.RolloutPlan) -> compute.RolloutPlan: + """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 OrganizationRolloutPlans 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.RolloutPlan, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.RolloutPlan, 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 OrganizationRolloutPlans 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_insert( + self, + request: compute.InsertOrganizationRolloutPlanRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.InsertOrganizationRolloutPlanRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for insert + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRolloutPlans server. + """ + return request, metadata + + def post_insert(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for insert + + DEPRECATED. Please use the `post_insert_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRolloutPlans server but before + it is returned to user code. This `post_insert` interceptor runs + before the `post_insert_with_metadata` interceptor. + """ + return response + + def post_insert_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for insert + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRolloutPlans server but before it is returned to user code. + + We recommend only using this `post_insert_with_metadata` + interceptor in new development instead of the `post_insert` interceptor. + When both interceptors are used, this `post_insert_with_metadata` interceptor runs after the + `post_insert` interceptor. The (possibly modified) response returned by + `post_insert` will be passed to + `post_insert_with_metadata`. + """ + return response, metadata + + def pre_list( + self, + request: compute.ListOrganizationRolloutPlansRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListOrganizationRolloutPlansRequest, + 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 OrganizationRolloutPlans server. + """ + return request, metadata + + def post_list( + self, response: compute.RolloutPlansListResponse + ) -> compute.RolloutPlansListResponse: + """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 OrganizationRolloutPlans 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.RolloutPlansListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RolloutPlansListResponse, 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 OrganizationRolloutPlans 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 OrganizationRolloutPlansRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OrganizationRolloutPlansRestInterceptor + + +class OrganizationRolloutPlansRestTransport(_BaseOrganizationRolloutPlansRestTransport): + """REST backend synchronous transport for OrganizationRolloutPlans. + + The OrganizationRolloutPlans 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[OrganizationRolloutPlansRestInterceptor] = 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. + interceptor (Optional[OrganizationRolloutPlansRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 OrganizationRolloutPlansRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Delete( + _BaseOrganizationRolloutPlansRestTransport._BaseDelete, + OrganizationRolloutPlansRestStub, + ): + def __hash__(self): + return hash("OrganizationRolloutPlansRestTransport.Delete") + + @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.DeleteOrganizationRolloutPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteOrganizationRolloutPlanRequest): + The request object. A request message for + OrganizationRolloutPlans.Delete. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseOrganizationRolloutPlansRestTransport._BaseDelete._get_http_options() + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = _BaseOrganizationRolloutPlansRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutPlansRestTransport._BaseDelete._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.OrganizationRolloutPlansClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutPlansRestTransport._Delete._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutPlansClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get( + _BaseOrganizationRolloutPlansRestTransport._BaseGet, + OrganizationRolloutPlansRestStub, + ): + def __hash__(self): + return hash("OrganizationRolloutPlansRestTransport.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.GetOrganizationRolloutPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RolloutPlan: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetOrganizationRolloutPlanRequest): + The request object. A request message for + OrganizationRolloutPlans.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.RolloutPlan: + RolloutPlan resource. + + A RolloutPlan is the customer-defined + strategy to divide a large-scale change + into smaller increments, referred to as + "waves". Each wave targets a specific + portion of the overall affected area and + defines criteria that must be met before + progressing to the subsequent wave. + + """ + + http_options = ( + _BaseOrganizationRolloutPlansRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = _BaseOrganizationRolloutPlansRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutPlansRestTransport._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.OrganizationRolloutPlansClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutPlansRestTransport._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.RolloutPlan() + pb_resp = compute.RolloutPlan.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.RolloutPlan.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.OrganizationRolloutPlansClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert( + _BaseOrganizationRolloutPlansRestTransport._BaseInsert, + OrganizationRolloutPlansRestStub, + ): + def __hash__(self): + return hash("OrganizationRolloutPlansRestTransport.Insert") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: compute.InsertOrganizationRolloutPlanRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertOrganizationRolloutPlanRequest): + The request object. A request message for + OrganizationRolloutPlans.Insert. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseOrganizationRolloutPlansRestTransport._BaseInsert._get_http_options() + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = _BaseOrganizationRolloutPlansRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + + body = _BaseOrganizationRolloutPlansRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutPlansRestTransport._BaseInsert._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.OrganizationRolloutPlansClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutPlansRestTransport._Insert._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutPlansClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseOrganizationRolloutPlansRestTransport._BaseList, + OrganizationRolloutPlansRestStub, + ): + def __hash__(self): + return hash("OrganizationRolloutPlansRestTransport.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.ListOrganizationRolloutPlansRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RolloutPlansListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListOrganizationRolloutPlansRequest): + The request object. A request message for + OrganizationRolloutPlans.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.RolloutPlansListResponse: + Contains a list of RolloutPlan + resources. + + """ + + http_options = ( + _BaseOrganizationRolloutPlansRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseOrganizationRolloutPlansRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutPlansRestTransport._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.OrganizationRolloutPlansClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutPlansRestTransport._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.RolloutPlansListResponse() + pb_resp = compute.RolloutPlansListResponse.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.RolloutPlansListResponse.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.OrganizationRolloutPlansClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def delete( + self, + ) -> Callable[[compute.DeleteOrganizationRolloutPlanRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get( + self, + ) -> Callable[[compute.GetOrganizationRolloutPlanRequest], compute.RolloutPlan]: + # 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 insert( + self, + ) -> Callable[[compute.InsertOrganizationRolloutPlanRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Insert(self._session, self._host, self._interceptor) # type: ignore + + @property + def list( + self, + ) -> Callable[ + [compute.ListOrganizationRolloutPlansRequest], compute.RolloutPlansListResponse + ]: + # 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__ = ("OrganizationRolloutPlansRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/rest_base.py new file mode 100644 index 000000000000..0fa2fe0cbefe --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollout_plans/transports/rest_base.py @@ -0,0 +1,285 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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, OrganizationRolloutPlansTransport + + +class _BaseOrganizationRolloutPlansRestTransport(OrganizationRolloutPlansTransport): + """Base REST backend transport for OrganizationRolloutPlans. + + 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 _BaseDelete: + 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": "delete", + "uri": "/compute/beta/{organization=organizations/*}/global/rolloutPlans/{rollout_plan}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteOrganizationRolloutPlanRequest.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( + _BaseOrganizationRolloutPlansRestTransport._BaseDelete._get_unset_required_fields( + query_params + ) + ) + + return query_params + + 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/{organization=organizations/*}/global/rolloutPlans/{rollout_plan}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetOrganizationRolloutPlanRequest.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( + _BaseOrganizationRolloutPlansRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseInsert: + 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": "post", + "uri": "/compute/beta/{organization=organizations/*}/global/rolloutPlans", + "body": "rollout_plan_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.InsertOrganizationRolloutPlanRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @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( + _BaseOrganizationRolloutPlansRestTransport._BaseInsert._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/{organization=organizations/*}/global/rolloutPlans", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListOrganizationRolloutPlansRequest.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( + _BaseOrganizationRolloutPlansRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseOrganizationRolloutPlansRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/__init__.py new file mode 100644 index 000000000000..f634acd3fbb8 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 OrganizationRolloutsClient + +__all__ = ("OrganizationRolloutsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/client.py new file mode 100644 index 000000000000..6a29501c2b90 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/client.py @@ -0,0 +1,2359 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 functools +import json +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +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 extended_operation, gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.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__) + +import google.api_core.extended_operation as extended_operation # type: ignore + +from google.cloud.compute_v1beta.services.organization_rollouts import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, OrganizationRolloutsTransport +from .transports.rest import OrganizationRolloutsRestTransport + + +class OrganizationRolloutsClientMeta(type): + """Metaclass for the OrganizationRollouts 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[OrganizationRolloutsTransport]] + _transport_registry["rest"] = OrganizationRolloutsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[OrganizationRolloutsTransport]: + """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 OrganizationRolloutsClient(metaclass=OrganizationRolloutsClientMeta): + """The OrganizationRollouts API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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: + OrganizationRolloutsClient: 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: + OrganizationRolloutsClient: 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) -> OrganizationRolloutsTransport: + """Returns the transport used by the client instance. + + Returns: + OrganizationRolloutsTransport: 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 = OrganizationRolloutsClient._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 = OrganizationRolloutsClient._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 + ) -> str: + """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 = OrganizationRolloutsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = OrganizationRolloutsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = OrganizationRolloutsClient._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 = OrganizationRolloutsClient._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) -> str: + """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, + OrganizationRolloutsTransport, + Callable[..., OrganizationRolloutsTransport], + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the organization rollouts 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,OrganizationRolloutsTransport,Callable[..., OrganizationRolloutsTransport]]]): + 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 OrganizationRolloutsTransport 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 = ( + OrganizationRolloutsClient._read_environment_variables() + ) + self._client_cert_source = OrganizationRolloutsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = OrganizationRolloutsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, OrganizationRolloutsTransport) + if transport_provided: + # transport is a OrganizationRolloutsTransport 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(OrganizationRolloutsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or OrganizationRolloutsClient._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[OrganizationRolloutsTransport], + Callable[..., OrganizationRolloutsTransport], + ] = ( + OrganizationRolloutsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., OrganizationRolloutsTransport], 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.OrganizationRolloutsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "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.OrganizationRollouts", + "credentialsType": None, + }, + ) + + def advance_unary( + self, + request: Optional[ + Union[compute.AdvanceOrganizationRolloutRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout: 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.Operation: + r"""Advances a Rollout to the next wave, or completes it + if no waves remain. + + .. 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_advance(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.AdvanceOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AdvanceOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Advance. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to advance. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.AdvanceOrganizationRolloutRequest): + request = compute.AdvanceOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # 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 advance( + self, + request: Optional[ + Union[compute.AdvanceOrganizationRolloutRequest, dict] + ] = None, + *, + organization: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Advances a Rollout to the next wave, or completes it + if no waves remain. + + .. 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_advance(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.AdvanceOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AdvanceOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Advance. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to advance. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.AdvanceOrganizationRolloutRequest): + request = compute.AdvanceOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def cancel_unary( + self, + request: Optional[Union[compute.CancelOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: 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.Operation: + r"""Cancels a Rollout. + + .. 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_cancel(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.CancelOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.cancel(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.CancelOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Cancel. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + cancel. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.CancelOrganizationRolloutRequest): + request = compute.CancelOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # 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 cancel( + self, + request: Optional[Union[compute.CancelOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Cancels a Rollout. + + .. 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_cancel(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.CancelOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.cancel(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.CancelOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Cancel. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + cancel. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.CancelOrganizationRolloutRequest): + request = compute.CancelOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.cancel] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def delete_unary( + self, + request: Optional[Union[compute.DeleteOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: 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.Operation: + r"""Deletes a Rollout. + + .. 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_delete(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Delete. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + delete. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.DeleteOrganizationRolloutRequest): + request = compute.DeleteOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # 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 delete( + self, + request: Optional[Union[compute.DeleteOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Deletes a Rollout. + + .. 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_delete(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.DeleteOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Delete. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the Rollout resource to + delete. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.DeleteOrganizationRolloutRequest): + request = compute.DeleteOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def get( + self, + request: Optional[Union[compute.GetOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: 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.Rollout: + r"""Gets details of a single organization-scoped Rollout. + + .. 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.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Get. See the method + description for details. + organization (str): + Organization ID for this request. + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Name of the persistent rollout to + return. + + This corresponds to the ``rollout`` 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.Rollout: + Rollout resource. + + A Rollout is a specific instance of a + RolloutPlan. It represents a single + execution of a strategy to roll out a + specific resource. It also provides APIs + to interact with the rollout. + + """ + # 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 = [organization, rollout] + 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.GetOrganizationRolloutRequest): + request = compute.GetOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # 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( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # 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.ListOrganizationRolloutsRequest, dict]] = None, + *, + organization: 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"""Lists Rollouts in a given organization and location. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import compute_v1beta + + def sample_list(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ListOrganizationRolloutsRequest( + organization="organization_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.ListOrganizationRolloutsRequest, dict]): + The request object. A request message for + OrganizationRollouts.List. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` 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.organization_rollouts.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 = [organization] + 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.ListOrganizationRolloutsRequest): + request = compute.ListOrganizationRolloutsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + + # 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( + (("organization", request.organization),) + ), + ) + + # 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 pause_unary( + self, + request: Optional[Union[compute.PauseOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: 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.Operation: + r"""Pauses a Rollout. + + .. 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_pause(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.PauseOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PauseOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Pause. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to pause. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.PauseOrganizationRolloutRequest): + request = compute.PauseOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # 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 pause( + self, + request: Optional[Union[compute.PauseOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Pauses a Rollout. + + .. 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_pause(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.PauseOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PauseOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Pause. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to pause. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.PauseOrganizationRolloutRequest): + request = compute.PauseOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def resume_unary( + self, + request: Optional[Union[compute.ResumeOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: 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.Operation: + r"""Resumes a Rollout. + + .. 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_resume(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ResumeOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ResumeOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Resume. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to resume. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.ResumeOrganizationRolloutRequest): + request = compute.ResumeOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # 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 resume( + self, + request: Optional[Union[compute.ResumeOrganizationRolloutRequest, dict]] = None, + *, + organization: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Resumes a Rollout. + + .. 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_resume(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ResumeOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ResumeOrganizationRolloutRequest, dict]): + The request object. A request message for + OrganizationRollouts.Resume. See the + method description for details. + organization (str): + Required. Organization ID for this + request. + + This corresponds to the ``organization`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to resume. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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 = [organization, rollout] + 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.ResumeOrganizationRolloutRequest): + request = compute.ResumeOrganizationRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if organization is not None: + request.organization = organization + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + ( + ("organization", request.organization), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_organization_operations_client + operation_request = compute.GetGlobalOrganizationOperationRequest() + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def __enter__(self) -> "OrganizationRolloutsClient": + 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__ = ("OrganizationRolloutsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/pagers.py new file mode 100644 index 000000000000..22855d839056 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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.OrganizationRolloutsListResponse` 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.OrganizationRolloutsListResponse` + 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.OrganizationRolloutsListResponse], + request: compute.ListOrganizationRolloutsRequest, + response: compute.OrganizationRolloutsListResponse, + *, + 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.ListOrganizationRolloutsRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.OrganizationRolloutsListResponse): + 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.ListOrganizationRolloutsRequest(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.OrganizationRolloutsListResponse]: + 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.Rollout]: + 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/organization_rollouts/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/README.rst new file mode 100644 index 000000000000..c3c5a1570428 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``OrganizationRolloutsTransport`` is the ABC for all transports. + +- public child ``OrganizationRolloutsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``OrganizationRolloutsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseOrganizationRolloutsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``OrganizationRolloutsRestTransport`` 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/organization_rollouts/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/__init__.py new file mode 100644 index 000000000000..e3cda7a1468d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 OrganizationRolloutsTransport +from .rest import OrganizationRolloutsRestInterceptor, OrganizationRolloutsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[OrganizationRolloutsTransport]] +_transport_registry["rest"] = OrganizationRolloutsRestTransport + +__all__ = ( + "OrganizationRolloutsTransport", + "OrganizationRolloutsRestTransport", + "OrganizationRolloutsRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/base.py new file mode 100644 index 000000000000..6fef43610438 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/base.py @@ -0,0 +1,307 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Any, Awaitable, Callable, Dict, Optional, Sequence, Union + +import google.api_core +import google.auth # type: ignore +import google.protobuf +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.oauth2 import service_account # type: ignore + +from google.cloud.compute_v1beta import gapic_version as package_version +from google.cloud.compute_v1beta.services import global_organization_operations +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 OrganizationRolloutsTransport(abc.ABC): + """Abstract transport class for OrganizationRollouts.""" + + AUTH_SCOPES = ( + "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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + self._extended_operations_services: Dict[str, Any] = {} + + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @property + def host(self): + return self._host + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.advance: gapic_v1.method.wrap_method( + self.advance, + default_timeout=600.0, + client_info=client_info, + ), + self.cancel: gapic_v1.method.wrap_method( + self.cancel, + default_timeout=600.0, + client_info=client_info, + ), + self.delete: gapic_v1.method.wrap_method( + self.delete, + default_timeout=600.0, + client_info=client_info, + ), + self.get: gapic_v1.method.wrap_method( + self.get, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.pause: gapic_v1.method.wrap_method( + self.pause, + default_timeout=600.0, + client_info=client_info, + ), + self.resume: gapic_v1.method.wrap_method( + self.resume, + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def advance( + self, + ) -> Callable[ + [compute.AdvanceOrganizationRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel( + self, + ) -> Callable[ + [compute.CancelOrganizationRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def delete( + self, + ) -> Callable[ + [compute.DeleteOrganizationRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetOrganizationRolloutRequest], + Union[compute.Rollout, Awaitable[compute.Rollout]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListOrganizationRolloutsRequest], + Union[ + compute.OrganizationRolloutsListResponse, + Awaitable[compute.OrganizationRolloutsListResponse], + ], + ]: + raise NotImplementedError() + + @property + def pause( + self, + ) -> Callable[ + [compute.PauseOrganizationRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def resume( + self, + ) -> Callable[ + [compute.ResumeOrganizationRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + @property + def _global_organization_operations_client( + self, + ) -> global_organization_operations.GlobalOrganizationOperationsClient: + ex_op_service = self._extended_operations_services.get( + "global_organization_operations" + ) + if not ex_op_service: + ex_op_service = ( + global_organization_operations.GlobalOrganizationOperationsClient( + credentials=self._credentials, + transport=self.kind, + ) + ) + self._extended_operations_services["global_organization_operations"] = ( + ex_op_service + ) + + return ex_op_service + + +__all__ = ("OrganizationRolloutsTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/rest.py new file mode 100644 index 000000000000..712bc3fbdbb4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/rest.py @@ -0,0 +1,1805 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +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 +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 _BaseOrganizationRolloutsRestTransport + +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 OrganizationRolloutsRestInterceptor: + """Interceptor for OrganizationRollouts. + + 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 OrganizationRolloutsRestTransport. + + .. code-block:: python + class MyCustomOrganizationRolloutsInterceptor(OrganizationRolloutsRestInterceptor): + def pre_advance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_advance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_cancel(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_cancel(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete(self, response): + logging.log(f"Received response: {response}") + return response + + 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 + + def pre_pause(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_pause(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resume(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resume(self, response): + logging.log(f"Received response: {response}") + return response + + transport = OrganizationRolloutsRestTransport(interceptor=MyCustomOrganizationRolloutsInterceptor()) + client = OrganizationRolloutsClient(transport=transport) + + + """ + + def pre_advance( + self, + request: compute.AdvanceOrganizationRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.AdvanceOrganizationRolloutRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for advance + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRollouts server. + """ + return request, metadata + + def post_advance(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for advance + + DEPRECATED. Please use the `post_advance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRollouts server but before + it is returned to user code. This `post_advance` interceptor runs + before the `post_advance_with_metadata` interceptor. + """ + return response + + def post_advance_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for advance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRollouts server but before it is returned to user code. + + We recommend only using this `post_advance_with_metadata` + interceptor in new development instead of the `post_advance` interceptor. + When both interceptors are used, this `post_advance_with_metadata` interceptor runs after the + `post_advance` interceptor. The (possibly modified) response returned by + `post_advance` will be passed to + `post_advance_with_metadata`. + """ + return response, metadata + + def pre_cancel( + self, + request: compute.CancelOrganizationRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.CancelOrganizationRolloutRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for cancel + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRollouts server. + """ + return request, metadata + + def post_cancel(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for cancel + + DEPRECATED. Please use the `post_cancel_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRollouts server but before + it is returned to user code. This `post_cancel` interceptor runs + before the `post_cancel_with_metadata` interceptor. + """ + return response + + def post_cancel_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for cancel + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRollouts server but before it is returned to user code. + + We recommend only using this `post_cancel_with_metadata` + interceptor in new development instead of the `post_cancel` interceptor. + When both interceptors are used, this `post_cancel_with_metadata` interceptor runs after the + `post_cancel` interceptor. The (possibly modified) response returned by + `post_cancel` will be passed to + `post_cancel_with_metadata`. + """ + return response, metadata + + def pre_delete( + self, + request: compute.DeleteOrganizationRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteOrganizationRolloutRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for delete + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRollouts server. + """ + return request, metadata + + def post_delete(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete + + DEPRECATED. Please use the `post_delete_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRollouts server but before + it is returned to user code. This `post_delete` interceptor runs + before the `post_delete_with_metadata` interceptor. + """ + return response + + def post_delete_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRollouts server but before it is returned to user code. + + We recommend only using this `post_delete_with_metadata` + interceptor in new development instead of the `post_delete` interceptor. + When both interceptors are used, this `post_delete_with_metadata` interceptor runs after the + `post_delete` interceptor. The (possibly modified) response returned by + `post_delete` will be passed to + `post_delete_with_metadata`. + """ + return response, metadata + + def pre_get( + self, + request: compute.GetOrganizationRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetOrganizationRolloutRequest, 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 OrganizationRollouts server. + """ + return request, metadata + + def post_get(self, response: compute.Rollout) -> compute.Rollout: + """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 OrganizationRollouts 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.Rollout, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Rollout, 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 OrganizationRollouts 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.ListOrganizationRolloutsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListOrganizationRolloutsRequest, 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 OrganizationRollouts server. + """ + return request, metadata + + def post_list( + self, response: compute.OrganizationRolloutsListResponse + ) -> compute.OrganizationRolloutsListResponse: + """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 OrganizationRollouts 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.OrganizationRolloutsListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.OrganizationRolloutsListResponse, + 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 OrganizationRollouts 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 + + def pre_pause( + self, + request: compute.PauseOrganizationRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PauseOrganizationRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for pause + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRollouts server. + """ + return request, metadata + + def post_pause(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for pause + + DEPRECATED. Please use the `post_pause_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRollouts server but before + it is returned to user code. This `post_pause` interceptor runs + before the `post_pause_with_metadata` interceptor. + """ + return response + + def post_pause_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for pause + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRollouts server but before it is returned to user code. + + We recommend only using this `post_pause_with_metadata` + interceptor in new development instead of the `post_pause` interceptor. + When both interceptors are used, this `post_pause_with_metadata` interceptor runs after the + `post_pause` interceptor. The (possibly modified) response returned by + `post_pause` will be passed to + `post_pause_with_metadata`. + """ + return response, metadata + + def pre_resume( + self, + request: compute.ResumeOrganizationRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ResumeOrganizationRolloutRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for resume + + Override in a subclass to manipulate the request or metadata + before they are sent to the OrganizationRollouts server. + """ + return request, metadata + + def post_resume(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for resume + + DEPRECATED. Please use the `post_resume_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the OrganizationRollouts server but before + it is returned to user code. This `post_resume` interceptor runs + before the `post_resume_with_metadata` interceptor. + """ + return response + + def post_resume_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for resume + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the OrganizationRollouts server but before it is returned to user code. + + We recommend only using this `post_resume_with_metadata` + interceptor in new development instead of the `post_resume` interceptor. + When both interceptors are used, this `post_resume_with_metadata` interceptor runs after the + `post_resume` interceptor. The (possibly modified) response returned by + `post_resume` will be passed to + `post_resume_with_metadata`. + """ + return response, metadata + + +@dataclasses.dataclass +class OrganizationRolloutsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: OrganizationRolloutsRestInterceptor + + +class OrganizationRolloutsRestTransport(_BaseOrganizationRolloutsRestTransport): + """REST backend synchronous transport for OrganizationRollouts. + + The OrganizationRollouts 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[OrganizationRolloutsRestInterceptor] = 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. + interceptor (Optional[OrganizationRolloutsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 OrganizationRolloutsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Advance( + _BaseOrganizationRolloutsRestTransport._BaseAdvance, + OrganizationRolloutsRestStub, + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.Advance") + + @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.AdvanceOrganizationRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the advance method over HTTP. + + Args: + request (~.compute.AdvanceOrganizationRolloutRequest): + The request object. A request message for + OrganizationRollouts.Advance. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BaseAdvance._get_http_options() + ) + + request, metadata = self._interceptor.pre_advance(request, metadata) + transcoded_request = _BaseOrganizationRolloutsRestTransport._BaseAdvance._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutsRestTransport._BaseAdvance._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.OrganizationRolloutsClient.Advance", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Advance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._Advance._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_advance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_advance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutsClient.advance", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Advance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Cancel( + _BaseOrganizationRolloutsRestTransport._BaseCancel, OrganizationRolloutsRestStub + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.Cancel") + + @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.CancelOrganizationRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the cancel method over HTTP. + + Args: + request (~.compute.CancelOrganizationRolloutRequest): + The request object. A request message for + OrganizationRollouts.Cancel. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BaseCancel._get_http_options() + ) + + request, metadata = self._interceptor.pre_cancel(request, metadata) + transcoded_request = _BaseOrganizationRolloutsRestTransport._BaseCancel._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutsRestTransport._BaseCancel._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.OrganizationRolloutsClient.Cancel", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Cancel", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._Cancel._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_cancel(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_cancel_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutsClient.cancel", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Cancel", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Delete( + _BaseOrganizationRolloutsRestTransport._BaseDelete, OrganizationRolloutsRestStub + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.Delete") + + @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.DeleteOrganizationRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the delete method over HTTP. + + Args: + request (~.compute.DeleteOrganizationRolloutRequest): + The request object. A request message for + OrganizationRollouts.Delete. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BaseDelete._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete(request, metadata) + transcoded_request = _BaseOrganizationRolloutsRestTransport._BaseDelete._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutsRestTransport._BaseDelete._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.OrganizationRolloutsClient.Delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Delete", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._Delete._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutsClient.delete", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Delete", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Get( + _BaseOrganizationRolloutsRestTransport._BaseGet, OrganizationRolloutsRestStub + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.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.GetOrganizationRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Rollout: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetOrganizationRolloutRequest): + The request object. A request message for + OrganizationRollouts.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.Rollout: + Rollout resource. + + A Rollout is a specific instance of a + RolloutPlan. It represents a single + execution of a strategy to roll out a + specific resource. It also provides APIs + to interact with the rollout. + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseOrganizationRolloutsRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseOrganizationRolloutsRestTransport._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.OrganizationRolloutsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._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.Rollout() + pb_resp = compute.Rollout.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.Rollout.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.OrganizationRolloutsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List( + _BaseOrganizationRolloutsRestTransport._BaseList, OrganizationRolloutsRestStub + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.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.ListOrganizationRolloutsRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.OrganizationRolloutsListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListOrganizationRolloutsRequest): + The request object. A request message for + OrganizationRollouts.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.OrganizationRolloutsListResponse: + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = _BaseOrganizationRolloutsRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseOrganizationRolloutsRestTransport._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.OrganizationRolloutsClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._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.OrganizationRolloutsListResponse() + pb_resp = compute.OrganizationRolloutsListResponse.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.OrganizationRolloutsListResponse.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.OrganizationRolloutsClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Pause( + _BaseOrganizationRolloutsRestTransport._BasePause, OrganizationRolloutsRestStub + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.Pause") + + @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.PauseOrganizationRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the pause method over HTTP. + + Args: + request (~.compute.PauseOrganizationRolloutRequest): + The request object. A request message for + OrganizationRollouts.Pause. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BasePause._get_http_options() + ) + + request, metadata = self._interceptor.pre_pause(request, metadata) + transcoded_request = _BaseOrganizationRolloutsRestTransport._BasePause._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutsRestTransport._BasePause._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.OrganizationRolloutsClient.Pause", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Pause", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._Pause._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_pause(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_pause_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutsClient.pause", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Pause", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Resume( + _BaseOrganizationRolloutsRestTransport._BaseResume, OrganizationRolloutsRestStub + ): + def __hash__(self): + return hash("OrganizationRolloutsRestTransport.Resume") + + @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.ResumeOrganizationRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the resume method over HTTP. + + Args: + request (~.compute.ResumeOrganizationRolloutRequest): + The request object. A request message for + OrganizationRollouts.Resume. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseOrganizationRolloutsRestTransport._BaseResume._get_http_options() + ) + + request, metadata = self._interceptor.pre_resume(request, metadata) + transcoded_request = _BaseOrganizationRolloutsRestTransport._BaseResume._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseOrganizationRolloutsRestTransport._BaseResume._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.OrganizationRolloutsClient.Resume", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Resume", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = OrganizationRolloutsRestTransport._Resume._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_resume(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_resume_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.OrganizationRolloutsClient.resume", + extra={ + "serviceName": "google.cloud.compute.v1beta.OrganizationRollouts", + "rpcName": "Resume", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def advance( + self, + ) -> Callable[[compute.AdvanceOrganizationRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Advance(self._session, self._host, self._interceptor) # type: ignore + + @property + def cancel( + self, + ) -> Callable[[compute.CancelOrganizationRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Cancel(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete( + self, + ) -> Callable[[compute.DeleteOrganizationRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Delete(self._session, self._host, self._interceptor) # type: ignore + + @property + def get(self) -> Callable[[compute.GetOrganizationRolloutRequest], compute.Rollout]: + # 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.ListOrganizationRolloutsRequest], + compute.OrganizationRolloutsListResponse, + ]: + # 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 pause( + self, + ) -> Callable[[compute.PauseOrganizationRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Pause(self._session, self._host, self._interceptor) # type: ignore + + @property + def resume( + self, + ) -> Callable[[compute.ResumeOrganizationRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Resume(self._session, self._host, self._interceptor) # type: ignore + + @property + def kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("OrganizationRolloutsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/rest_base.py new file mode 100644 index 000000000000..c52031f06219 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/organization_rollouts/transports/rest_base.py @@ -0,0 +1,413 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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, OrganizationRolloutsTransport + + +class _BaseOrganizationRolloutsRestTransport(OrganizationRolloutsTransport): + """Base REST backend transport for OrganizationRollouts. + + 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 _BaseAdvance: + 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": "post", + "uri": "/compute/beta/{organization=organizations/*}/global/rollouts/{rollout}/advance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AdvanceOrganizationRolloutRequest.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( + _BaseOrganizationRolloutsRestTransport._BaseAdvance._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseCancel: + 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": "patch", + "uri": "/compute/beta/{organization=organizations/*}/global/rollouts/{rollout}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.CancelOrganizationRolloutRequest.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( + _BaseOrganizationRolloutsRestTransport._BaseCancel._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseDelete: + 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": "delete", + "uri": "/compute/beta/{organization=organizations/*}/global/rollouts/{rollout}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteOrganizationRolloutRequest.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( + _BaseOrganizationRolloutsRestTransport._BaseDelete._get_unset_required_fields( + query_params + ) + ) + + return query_params + + 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/{organization=organizations/*}/global/rollouts/{rollout}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetOrganizationRolloutRequest.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( + _BaseOrganizationRolloutsRestTransport._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/{organization=organizations/*}/global/rollouts", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListOrganizationRolloutsRequest.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( + _BaseOrganizationRolloutsRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BasePause: + 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": "post", + "uri": "/compute/beta/{organization=organizations/*}/global/rollouts/{rollout}/pause", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PauseOrganizationRolloutRequest.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( + _BaseOrganizationRolloutsRestTransport._BasePause._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseResume: + 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": "post", + "uri": "/compute/beta/{organization=organizations/*}/global/rollouts/{rollout}/resume", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ResumeOrganizationRolloutRequest.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( + _BaseOrganizationRolloutsRestTransport._BaseResume._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseOrganizationRolloutsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/__init__.py new file mode 100644 index 000000000000..6be82c91e927 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ProjectViewsClient + +__all__ = ("ProjectViewsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/client.py new file mode 100644 index 000000000000..1936148f7f8d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/client.py @@ -0,0 +1,853 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.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.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ProjectViewsTransport +from .transports.rest import ProjectViewsRestTransport + + +class ProjectViewsClientMeta(type): + """Metaclass for the ProjectViews 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[ProjectViewsTransport]] + _transport_registry["rest"] = ProjectViewsRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ProjectViewsTransport]: + """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 ProjectViewsClient(metaclass=ProjectViewsClientMeta): + """The ProjectViews API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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: + ProjectViewsClient: 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: + ProjectViewsClient: 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) -> ProjectViewsTransport: + """Returns the transport used by the client instance. + + Returns: + ProjectViewsTransport: 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 = ProjectViewsClient._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 = ProjectViewsClient._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 + ) -> str: + """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 = ProjectViewsClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ProjectViewsClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ProjectViewsClient._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 = ProjectViewsClient._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) -> str: + """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, ProjectViewsTransport, Callable[..., ProjectViewsTransport]] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the project views 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,ProjectViewsTransport,Callable[..., ProjectViewsTransport]]]): + 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 ProjectViewsTransport 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 = ( + ProjectViewsClient._read_environment_variables() + ) + self._client_cert_source = ProjectViewsClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ProjectViewsClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, ProjectViewsTransport) + if transport_provided: + # transport is a ProjectViewsTransport 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(ProjectViewsTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = self._api_endpoint or ProjectViewsClient._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[ProjectViewsTransport], Callable[..., ProjectViewsTransport] + ] = ( + ProjectViewsClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ProjectViewsTransport], 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.ProjectViewsClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.ProjectViews", + "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.ProjectViews", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetProjectViewRequest, dict]] = None, + *, + project: Optional[str] = None, + region: 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.ProjectView: + r"""Returns the specified global ProjectViews resource, + with a regional context. + + .. 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.ProjectViewsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetProjectViewRequest( + 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.GetProjectViewRequest, dict]): + The request object. A request message for + ProjectViews.Get. See the method + description for details. + project (str): + Required. Project ID for this + request. This is part of the URL path. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + region (str): + Required. Name of the region for this + request. This is part of the URL path. + + This corresponds to the ``region`` 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.ProjectView: + Represents a ProjectView resource. + + A ProjectView resource contains + read-only project data which is + available globally. + + """ + # 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] + 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.GetProjectViewRequest): + request = compute.GetProjectViewRequest(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 + + # 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), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def __enter__(self) -> "ProjectViewsClient": + 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__ = ("ProjectViewsClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/README.rst new file mode 100644 index 000000000000..fb7baaad14ee --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``ProjectViewsTransport`` is the ABC for all transports. + +- public child ``ProjectViewsGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``ProjectViewsGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseProjectViewsRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``ProjectViewsRestTransport`` 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/project_views/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/__init__.py new file mode 100644 index 000000000000..9dcc22fc47ec --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ProjectViewsTransport +from .rest import ProjectViewsRestInterceptor, ProjectViewsRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ProjectViewsTransport]] +_transport_registry["rest"] = ProjectViewsRestTransport + +__all__ = ( + "ProjectViewsTransport", + "ProjectViewsRestTransport", + "ProjectViewsRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/base.py new file mode 100644 index 000000000000..868170d62ec9 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/base.py @@ -0,0 +1,189 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import google.auth # type: ignore +import google.protobuf +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.oauth2 import service_account # type: ignore + +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 ProjectViewsTransport(abc.ABC): + """Abstract transport class for ProjectViews.""" + + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetProjectViewRequest], + Union[compute.ProjectView, Awaitable[compute.ProjectView]], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ProjectViewsTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/rest.py new file mode 100644 index 000000000000..d01e5c3eba05 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/rest.py @@ -0,0 +1,394 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +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 +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 _BaseProjectViewsRestTransport + +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 ProjectViewsRestInterceptor: + """Interceptor for ProjectViews. + + 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 ProjectViewsRestTransport. + + .. code-block:: python + class MyCustomProjectViewsInterceptor(ProjectViewsRestInterceptor): + 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 + + transport = ProjectViewsRestTransport(interceptor=MyCustomProjectViewsInterceptor()) + client = ProjectViewsClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetProjectViewRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.GetProjectViewRequest, 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 ProjectViews server. + """ + return request, metadata + + def post_get(self, response: compute.ProjectView) -> compute.ProjectView: + """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 ProjectViews 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.ProjectView, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ProjectView, 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 ProjectViews 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 + + +@dataclasses.dataclass +class ProjectViewsRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ProjectViewsRestInterceptor + + +class ProjectViewsRestTransport(_BaseProjectViewsRestTransport): + """REST backend synchronous transport for ProjectViews. + + The ProjectViews 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[ProjectViewsRestInterceptor] = 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. + interceptor (Optional[ProjectViewsRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 ProjectViewsRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseProjectViewsRestTransport._BaseGet, ProjectViewsRestStub): + def __hash__(self): + return hash("ProjectViewsRestTransport.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.GetProjectViewRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ProjectView: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetProjectViewRequest): + The request object. A request message for + ProjectViews.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.ProjectView: + Represents a ProjectView resource. + + A ProjectView resource contains + read-only project data which is + available globally. + + """ + + http_options = _BaseProjectViewsRestTransport._BaseGet._get_http_options() + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseProjectViewsRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseProjectViewsRestTransport._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.ProjectViewsClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ProjectViews", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ProjectViewsRestTransport._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.ProjectView() + pb_resp = compute.ProjectView.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.ProjectView.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.ProjectViewsClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ProjectViews", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get(self) -> Callable[[compute.GetProjectViewRequest], compute.ProjectView]: + # 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 kind(self) -> str: + return "rest" + + def close(self): + self._session.close() + + +__all__ = ("ProjectViewsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/rest_base.py new file mode 100644 index 000000000000..4038e7d0894a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/project_views/transports/rest_base.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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, ProjectViewsTransport + + +class _BaseProjectViewsRestTransport(ProjectViewsTransport): + """Base REST backend transport for ProjectViews. + + 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}/projectViews", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetProjectViewRequest.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( + _BaseProjectViewsRestTransport._BaseGet._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseProjectViewsRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_backend_services/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_backend_services/client.py index 0b0f8223ea2e..d1c3c139da37 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_backend_services/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/region_backend_services/client.py @@ -1936,8 +1936,11 @@ def list_usable( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListUsablePager: - r"""Retrieves a list of all usable backend services in - the specified project in the given region. + r"""Retrieves a list of all usable backend services for + Application Load Balancers and Proxy Network Load + Balancers in the specified project in the given region. + Backend services for external and internal passthrough + Network Load Balancers are not included in the response. .. code-block:: python diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/__init__.py new file mode 100644 index 000000000000..b767cbf71e28 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/__init__.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ReliabilityRisksClient + +__all__ = ("ReliabilityRisksClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/client.py new file mode 100644 index 000000000000..258cd42bd235 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/client.py @@ -0,0 +1,977 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import logging as std_logging +import os +import re +import warnings +from collections import OrderedDict +from http import HTTPStatus +from typing import ( + Callable, + Dict, + Mapping, + MutableMapping, + MutableSequence, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import google.protobuf +from google.api_core import client_options as client_options_lib +from google.api_core import exceptions as core_exceptions +from google.api_core import gapic_v1 +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.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.reliability_risks import pagers +from google.cloud.compute_v1beta.types import compute + +from .transports.base import DEFAULT_CLIENT_INFO, ReliabilityRisksTransport +from .transports.rest import ReliabilityRisksRestTransport + + +class ReliabilityRisksClientMeta(type): + """Metaclass for the ReliabilityRisks 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[ReliabilityRisksTransport]] + _transport_registry["rest"] = ReliabilityRisksRestTransport + + def get_transport_class( + cls, + label: Optional[str] = None, + ) -> Type[ReliabilityRisksTransport]: + """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 ReliabilityRisksClient(metaclass=ReliabilityRisksClientMeta): + """The ReliabilityRisks API.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint) -> Optional[str]: + """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: + Optional[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) + if m is None: + # Could not parse api_endpoint; return as-is. + return 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: + ReliabilityRisksClient: 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: + ReliabilityRisksClient: 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) -> ReliabilityRisksTransport: + """Returns the transport used by the client instance. + + Returns: + ReliabilityRisksTransport: 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 = ReliabilityRisksClient._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 = ReliabilityRisksClient._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 + ) -> str: + """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 = ReliabilityRisksClient._DEFAULT_UNIVERSE + if universe_domain != _default_universe: + raise MutualTLSChannelError( + f"mTLS is not supported in any universe other than {_default_universe}." + ) + api_endpoint = ReliabilityRisksClient.DEFAULT_MTLS_ENDPOINT + else: + api_endpoint = ReliabilityRisksClient._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 = ReliabilityRisksClient._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) -> str: + """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, ReliabilityRisksTransport, Callable[..., ReliabilityRisksTransport] + ] + ] = None, + client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiates the reliability risks 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,ReliabilityRisksTransport,Callable[..., ReliabilityRisksTransport]]]): + 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 ReliabilityRisksTransport 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 = ( + ReliabilityRisksClient._read_environment_variables() + ) + self._client_cert_source = ReliabilityRisksClient._get_client_cert_source( + self._client_options.client_cert_source, self._use_client_cert + ) + self._universe_domain = ReliabilityRisksClient._get_universe_domain( + universe_domain_opt, self._universe_domain_env + ) + self._api_endpoint: str = "" # 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, ReliabilityRisksTransport) + if transport_provided: + # transport is a ReliabilityRisksTransport 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(ReliabilityRisksTransport, transport) + self._api_endpoint = self._transport.host + + self._api_endpoint = ( + self._api_endpoint + or ReliabilityRisksClient._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[ReliabilityRisksTransport], + Callable[..., ReliabilityRisksTransport], + ] = ( + ReliabilityRisksClient.get_transport_class(transport) + if isinstance(transport, str) or transport is None + else cast(Callable[..., ReliabilityRisksTransport], 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.ReliabilityRisksClient`.", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReliabilityRisks", + "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.ReliabilityRisks", + "credentialsType": None, + }, + ) + + def get( + self, + request: Optional[Union[compute.GetReliabilityRiskRequest, dict]] = None, + *, + project: Optional[str] = None, + reliability_risk: 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.ReliabilityRisk: + r"""Returns the specified ReliabilityRisk resource. + + .. 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.ReliabilityRisksClient() + + # Initialize request argument(s) + request = compute_v1beta.GetReliabilityRiskRequest( + project="project_value", + reliability_risk="reliability_risk_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.GetReliabilityRiskRequest, dict]): + The request object. A request message for + ReliabilityRisks.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. + reliability_risk (str): + Name of the ReliabilityRisk resource + to return. + + This corresponds to the ``reliability_risk`` 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.ReliabilityRisk: + Represents a ReliabilityRisk + 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, reliability_risk] + 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.GetReliabilityRiskRequest): + request = compute.GetReliabilityRiskRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if reliability_risk is not None: + request.reliability_risk = reliability_risk + + # 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), + ("reliability_risk", request.reliability_risk), + ) + ), + ) + + # 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.ListReliabilityRisksRequest, dict]] = None, + *, + project: 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 the list of reliabilityRisks available in + the specified project. + + .. 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.ReliabilityRisksClient() + + # Initialize request argument(s) + request = compute_v1beta.ListReliabilityRisksRequest( + project="project_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.ListReliabilityRisksRequest, dict]): + The request object. A request message for + ReliabilityRisks.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. + 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.reliability_risks.pagers.ListPager: + Response message for the List method + of ReliabilityRisksService. + 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] + 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.ListReliabilityRisksRequest): + request = compute.ListReliabilityRisksRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + + # 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),)), + ) + + # 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) -> "ReliabilityRisksClient": + 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__ = ("ReliabilityRisksClient",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/pagers.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/pagers.py new file mode 100644 index 000000000000..3255970d868e --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/pagers.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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.ReliabilityRisksListResponse` 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.ReliabilityRisksListResponse` + 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.ReliabilityRisksListResponse], + request: compute.ListReliabilityRisksRequest, + response: compute.ReliabilityRisksListResponse, + *, + 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.ListReliabilityRisksRequest): + The initial request object. + response (google.cloud.compute_v1beta.types.ReliabilityRisksListResponse): + 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.ListReliabilityRisksRequest(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.ReliabilityRisksListResponse]: + 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.ReliabilityRisk]: + 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/reliability_risks/transports/README.rst b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/README.rst new file mode 100644 index 000000000000..1b433543ea91 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/README.rst @@ -0,0 +1,10 @@ + +transport inheritance structure +_______________________________ + +``ReliabilityRisksTransport`` is the ABC for all transports. + +- public child ``ReliabilityRisksGrpcTransport`` for sync gRPC transport (defined in ``grpc.py``). +- public child ``ReliabilityRisksGrpcAsyncIOTransport`` for async gRPC transport (defined in ``grpc_asyncio.py``). +- private child ``_BaseReliabilityRisksRestTransport`` for base REST transport with inner classes ``_BaseMETHOD`` (defined in ``rest_base.py``). +- public child ``ReliabilityRisksRestTransport`` 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/reliability_risks/transports/__init__.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/__init__.py new file mode 100644 index 000000000000..a4d000da1765 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/__init__.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ReliabilityRisksTransport +from .rest import ReliabilityRisksRestInterceptor, ReliabilityRisksRestTransport + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[ReliabilityRisksTransport]] +_transport_registry["rest"] = ReliabilityRisksRestTransport + +__all__ = ( + "ReliabilityRisksTransport", + "ReliabilityRisksRestTransport", + "ReliabilityRisksRestInterceptor", +) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/base.py new file mode 100644 index 000000000000..ce9ea78d1674 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/base.py @@ -0,0 +1,216 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import google.auth # type: ignore +import google.protobuf +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.oauth2 import service_account # type: ignore + +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 ReliabilityRisksTransport(abc.ABC): + """Abstract transport class for ReliabilityRisks.""" + + 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. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + + # 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 + + self._wrapped_methods: Dict[Callable, Callable] = {} + + @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_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + self.list: gapic_v1.method.wrap_method( + self.list, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), + } + + def close(self): + """Closes resources associated with the transport. + + .. warning:: + Only call this method if the transport is NOT shared + with other clients - this may cause errors in other clients! + """ + raise NotImplementedError() + + @property + def get( + self, + ) -> Callable[ + [compute.GetReliabilityRiskRequest], + Union[compute.ReliabilityRisk, Awaitable[compute.ReliabilityRisk]], + ]: + raise NotImplementedError() + + @property + def list( + self, + ) -> Callable[ + [compute.ListReliabilityRisksRequest], + Union[ + compute.ReliabilityRisksListResponse, + Awaitable[compute.ReliabilityRisksListResponse], + ], + ]: + raise NotImplementedError() + + @property + def kind(self) -> str: + raise NotImplementedError() + + +__all__ = ("ReliabilityRisksTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/rest.py new file mode 100644 index 000000000000..8105b468f2cb --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/rest.py @@ -0,0 +1,615 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 +import warnings +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import google.protobuf +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 +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 _BaseReliabilityRisksRestTransport + +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 ReliabilityRisksRestInterceptor: + """Interceptor for ReliabilityRisks. + + 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 ReliabilityRisksRestTransport. + + .. code-block:: python + class MyCustomReliabilityRisksInterceptor(ReliabilityRisksRestInterceptor): + 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 = ReliabilityRisksRestTransport(interceptor=MyCustomReliabilityRisksInterceptor()) + client = ReliabilityRisksClient(transport=transport) + + + """ + + def pre_get( + self, + request: compute.GetReliabilityRiskRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetReliabilityRiskRequest, 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 ReliabilityRisks server. + """ + return request, metadata + + def post_get(self, response: compute.ReliabilityRisk) -> compute.ReliabilityRisk: + """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 ReliabilityRisks 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.ReliabilityRisk, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ReliabilityRisk, 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 ReliabilityRisks 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.ListReliabilityRisksRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListReliabilityRisksRequest, 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 ReliabilityRisks server. + """ + return request, metadata + + def post_list( + self, response: compute.ReliabilityRisksListResponse + ) -> compute.ReliabilityRisksListResponse: + """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 ReliabilityRisks 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.ReliabilityRisksListResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ReliabilityRisksListResponse, 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 ReliabilityRisks 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 ReliabilityRisksRestStub: + _session: AuthorizedSession + _host: str + _interceptor: ReliabilityRisksRestInterceptor + + +class ReliabilityRisksRestTransport(_BaseReliabilityRisksRestTransport): + """REST backend synchronous transport for ReliabilityRisks. + + The ReliabilityRisks 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[ReliabilityRisksRestInterceptor] = 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. + interceptor (Optional[ReliabilityRisksRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 ReliabilityRisksRestInterceptor() + self._prep_wrapped_messages(client_info) + + class _Get(_BaseReliabilityRisksRestTransport._BaseGet, ReliabilityRisksRestStub): + def __hash__(self): + return hash("ReliabilityRisksRestTransport.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.GetReliabilityRiskRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ReliabilityRisk: + r"""Call the get method over HTTP. + + Args: + request (~.compute.GetReliabilityRiskRequest): + The request object. A request message for + ReliabilityRisks.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.ReliabilityRisk: + Represents a ReliabilityRisk + resource. + + """ + + http_options = ( + _BaseReliabilityRisksRestTransport._BaseGet._get_http_options() + ) + + request, metadata = self._interceptor.pre_get(request, metadata) + transcoded_request = ( + _BaseReliabilityRisksRestTransport._BaseGet._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseReliabilityRisksRestTransport._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.ReliabilityRisksClient.Get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReliabilityRisks", + "rpcName": "Get", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReliabilityRisksRestTransport._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.ReliabilityRisk() + pb_resp = compute.ReliabilityRisk.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.ReliabilityRisk.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.ReliabilityRisksClient.get", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReliabilityRisks", + "rpcName": "Get", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BaseReliabilityRisksRestTransport._BaseList, ReliabilityRisksRestStub): + def __hash__(self): + return hash("ReliabilityRisksRestTransport.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.ListReliabilityRisksRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.ReliabilityRisksListResponse: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListReliabilityRisksRequest): + The request object. A request message for + ReliabilityRisks.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.ReliabilityRisksListResponse: + Response message for the List method + of ReliabilityRisksService. + + """ + + http_options = ( + _BaseReliabilityRisksRestTransport._BaseList._get_http_options() + ) + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseReliabilityRisksRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseReliabilityRisksRestTransport._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.ReliabilityRisksClient.List", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReliabilityRisks", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ReliabilityRisksRestTransport._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.ReliabilityRisksListResponse() + pb_resp = compute.ReliabilityRisksListResponse.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.ReliabilityRisksListResponse.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.ReliabilityRisksClient.list", + extra={ + "serviceName": "google.cloud.compute.v1beta.ReliabilityRisks", + "rpcName": "List", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def get( + self, + ) -> Callable[[compute.GetReliabilityRiskRequest], compute.ReliabilityRisk]: + # 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.ListReliabilityRisksRequest], compute.ReliabilityRisksListResponse + ]: + # 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__ = ("ReliabilityRisksRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/rest_base.py new file mode 100644 index 000000000000..d4b9509aef12 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/reliability_risks/transports/rest_base.py @@ -0,0 +1,183 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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, ReliabilityRisksTransport + + +class _BaseReliabilityRisksRestTransport(ReliabilityRisksTransport): + """Base REST backend transport for ReliabilityRisks. + + 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}/global/reliabilityRisks/{reliability_risk}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetReliabilityRiskRequest.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( + _BaseReliabilityRisksRestTransport._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}/global/reliabilityRisks", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListReliabilityRisksRequest.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( + _BaseReliabilityRisksRestTransport._BaseList._get_unset_required_fields( + query_params + ) + ) + + return query_params + + +__all__ = ("_BaseReliabilityRisksRestTransport",) diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/client.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/client.py index 4772f27b37b1..1c4a4bfbc643 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/client.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/client.py @@ -704,6 +704,282 @@ def __init__( }, ) + def advance_unary( + self, + request: Optional[Union[compute.AdvanceRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: 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.Operation: + r"""Advances a Rollout to the next wave, or completes it + if no waves remain. + + .. 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_advance(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.AdvanceRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AdvanceRolloutRequest, dict]): + The request object. A request message for + Rollouts.Advance. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to advance. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.AdvanceRolloutRequest): + request = compute.AdvanceRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advance] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # 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 advance( + self, + request: Optional[Union[compute.AdvanceRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Advances a Rollout to the next wave, or completes it + if no waves remain. + + .. 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_advance(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.AdvanceRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.AdvanceRolloutRequest, dict]): + The request object. A request message for + Rollouts.Advance. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to advance. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.AdvanceRolloutRequest): + request = compute.AdvanceRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advance] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def cancel_unary( self, request: Optional[Union[compute.CancelRolloutRequest, dict]] = None, @@ -1490,6 +1766,552 @@ def sample_list(): # Done; return the response. return response + def pause_unary( + self, + request: Optional[Union[compute.PauseRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: 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.Operation: + r"""Pauses a Rollout. + + .. 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_pause(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.PauseRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PauseRolloutRequest, dict]): + The request object. A request message for Rollouts.Pause. + See the method description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to pause. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.PauseRolloutRequest): + request = compute.PauseRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # 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 pause( + self, + request: Optional[Union[compute.PauseRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Pauses a Rollout. + + .. 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_pause(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.PauseRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.PauseRolloutRequest, dict]): + The request object. A request message for Rollouts.Pause. + See the method description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to pause. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.PauseRolloutRequest): + request = compute.PauseRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def resume_unary( + self, + request: Optional[Union[compute.ResumeRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: 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.Operation: + r"""Resumes a Rollout. + + .. 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_resume(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ResumeRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ResumeRolloutRequest, dict]): + The request object. A request message for + Rollouts.Resume. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to resume. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.ResumeRolloutRequest): + request = compute.ResumeRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # 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 resume( + self, + request: Optional[Union[compute.ResumeRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Resumes a Rollout. + + .. 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_resume(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ResumeRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1beta.types.ResumeRolloutRequest, dict]): + The request object. A request message for + Rollouts.Resume. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to resume. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.ResumeRolloutRequest): + request = compute.ResumeRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def __enter__(self) -> "RolloutsClient": return self diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/base.py index 8a50059a05e7..d6bbd905a7d7 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/base.py @@ -147,6 +147,11 @@ def host(self): def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { + self.advance: gapic_v1.method.wrap_method( + self.advance, + default_timeout=600.0, + client_info=client_info, + ), self.cancel: gapic_v1.method.wrap_method( self.cancel, default_timeout=600.0, @@ -187,6 +192,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.pause: gapic_v1.method.wrap_method( + self.pause, + default_timeout=600.0, + client_info=client_info, + ), + self.resume: gapic_v1.method.wrap_method( + self.resume, + default_timeout=600.0, + client_info=client_info, + ), } def close(self): @@ -198,6 +213,15 @@ def close(self): """ raise NotImplementedError() + @property + def advance( + self, + ) -> Callable[ + [compute.AdvanceRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def cancel( self, @@ -233,6 +257,24 @@ def list( ]: raise NotImplementedError() + @property + def pause( + self, + ) -> Callable[ + [compute.PauseRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def resume( + self, + ) -> Callable[ + [compute.ResumeRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest.py index ab2238657c29..690dac274bf3 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest.py @@ -72,6 +72,14 @@ class RolloutsRestInterceptor: .. code-block:: python class MyCustomRolloutsInterceptor(RolloutsRestInterceptor): + def pre_advance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_advance(self, response): + logging.log(f"Received response: {response}") + return response + def pre_cancel(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -104,12 +112,72 @@ def post_list(self, response): logging.log(f"Received response: {response}") return response + def pre_pause(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_pause(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resume(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resume(self, response): + logging.log(f"Received response: {response}") + return response + transport = RolloutsRestTransport(interceptor=MyCustomRolloutsInterceptor()) client = RolloutsClient(transport=transport) """ + def pre_advance( + self, + request: compute.AdvanceRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.AdvanceRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for advance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_advance(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for advance + + DEPRECATED. Please use the `post_advance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_advance` interceptor runs + before the `post_advance_with_metadata` interceptor. + """ + return response + + def post_advance_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for advance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_advance_with_metadata` + interceptor in new development instead of the `post_advance` interceptor. + When both interceptors are used, this `post_advance_with_metadata` interceptor runs after the + `post_advance` interceptor. The (possibly modified) response returned by + `post_advance` will be passed to + `post_advance_with_metadata`. + """ + return response, metadata + def pre_cancel( self, request: compute.CancelRolloutRequest, @@ -288,6 +356,94 @@ def post_list_with_metadata( """ return response, metadata + def pre_pause( + self, + request: compute.PauseRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.PauseRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for pause + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_pause(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for pause + + DEPRECATED. Please use the `post_pause_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_pause` interceptor runs + before the `post_pause_with_metadata` interceptor. + """ + return response + + def post_pause_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for pause + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_pause_with_metadata` + interceptor in new development instead of the `post_pause` interceptor. + When both interceptors are used, this `post_pause_with_metadata` interceptor runs after the + `post_pause` interceptor. The (possibly modified) response returned by + `post_pause` will be passed to + `post_pause_with_metadata`. + """ + return response, metadata + + def pre_resume( + self, + request: compute.ResumeRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ResumeRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for resume + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_resume(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for resume + + DEPRECATED. Please use the `post_resume_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_resume` interceptor runs + before the `post_resume_with_metadata` interceptor. + """ + return response + + def post_resume_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for resume + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_resume_with_metadata` + interceptor in new development instead of the `post_resume` interceptor. + When both interceptors are used, this `post_resume_with_metadata` interceptor runs after the + `post_resume` interceptor. The (possibly modified) response returned by + `post_resume` will be passed to + `post_resume_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class RolloutsRestStub: @@ -386,6 +542,180 @@ def __init__( self._interceptor = interceptor or RolloutsRestInterceptor() self._prep_wrapped_messages(client_info) + class _Advance(_BaseRolloutsRestTransport._BaseAdvance, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Advance") + + @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.AdvanceRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the advance method over HTTP. + + Args: + request (~.compute.AdvanceRolloutRequest): + The request object. A request message for + Rollouts.Advance. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BaseAdvance._get_http_options() + + request, metadata = self._interceptor.pre_advance(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseAdvance._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutsRestTransport._BaseAdvance._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.RolloutsClient.Advance", + extra={ + "serviceName": "google.cloud.compute.v1beta.Rollouts", + "rpcName": "Advance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Advance._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_advance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_advance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.RolloutsClient.advance", + extra={ + "serviceName": "google.cloud.compute.v1beta.Rollouts", + "rpcName": "Advance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Cancel(_BaseRolloutsRestTransport._BaseCancel, RolloutsRestStub): def __hash__(self): return hash("RolloutsRestTransport.Cancel") @@ -1023,6 +1353,357 @@ def __call__( ) return resp + class _Pause(_BaseRolloutsRestTransport._BasePause, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Pause") + + @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.PauseRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the pause method over HTTP. + + Args: + request (~.compute.PauseRolloutRequest): + The request object. A request message for Rollouts.Pause. + 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BasePause._get_http_options() + + request, metadata = self._interceptor.pre_pause(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BasePause._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseRolloutsRestTransport._BasePause._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.RolloutsClient.Pause", + extra={ + "serviceName": "google.cloud.compute.v1beta.Rollouts", + "rpcName": "Pause", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Pause._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_pause(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_pause_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.RolloutsClient.pause", + extra={ + "serviceName": "google.cloud.compute.v1beta.Rollouts", + "rpcName": "Pause", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Resume(_BaseRolloutsRestTransport._BaseResume, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Resume") + + @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.ResumeRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the resume method over HTTP. + + Args: + request (~.compute.ResumeRolloutRequest): + The request object. A request message for + Rollouts.Resume. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BaseResume._get_http_options() + + request, metadata = self._interceptor.pre_resume(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseResume._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutsRestTransport._BaseResume._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.RolloutsClient.Resume", + extra={ + "serviceName": "google.cloud.compute.v1beta.Rollouts", + "rpcName": "Resume", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Resume._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_resume(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_resume_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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.RolloutsClient.resume", + extra={ + "serviceName": "google.cloud.compute.v1beta.Rollouts", + "rpcName": "Resume", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def advance(self) -> Callable[[compute.AdvanceRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Advance(self._session, self._host, self._interceptor) # type: ignore + @property def cancel(self) -> Callable[[compute.CancelRolloutRequest], compute.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -1049,6 +1730,18 @@ def list( # In C++ this would require a dynamic_cast return self._List(self._session, self._host, self._interceptor) # type: ignore + @property + def pause(self) -> Callable[[compute.PauseRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Pause(self._session, self._host, self._interceptor) # type: ignore + + @property + def resume(self) -> Callable[[compute.ResumeRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Resume(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest_base.py b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest_base.py index 70c477e78d1d..326448319836 100644 --- a/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest_base.py +++ b/packages/google-cloud-compute-v1beta/google/cloud/compute_v1beta/services/rollouts/transports/rest_base.py @@ -87,6 +87,52 @@ def __init__( api_audience=api_audience, ) + class _BaseAdvance: + 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": "post", + "uri": "/compute/beta/projects/{project}/global/rollouts/{rollout}/advance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AdvanceRolloutRequest.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( + _BaseRolloutsRestTransport._BaseAdvance._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseCancel: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -271,5 +317,97 @@ def _get_query_params_json(transcoded_request): return query_params + class _BasePause: + 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": "post", + "uri": "/compute/beta/projects/{project}/global/rollouts/{rollout}/pause", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PauseRolloutRequest.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( + _BaseRolloutsRestTransport._BasePause._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseResume: + 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": "post", + "uri": "/compute/beta/projects/{project}/global/rollouts/{rollout}/resume", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ResumeRolloutRequest.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( + _BaseRolloutsRestTransport._BaseResume._get_unset_required_fields( + query_params + ) + ) + + return query_params + __all__ = ("_BaseRolloutsRestTransport",) 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 6b24984e3bd5..9a3f6ff65147 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 @@ -58,6 +58,8 @@ AddTrafficClassificationRuleRegionNetworkPolicyRequest, AdoptInstancesRegionInstanceGroupManagerRequest, AdvancedMachineFeatures, + AdvanceOrganizationRolloutRequest, + AdvanceRolloutRequest, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, AggregatedListAutoscalersRequest, @@ -187,6 +189,7 @@ BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy, BackendServiceLocalityLoadBalancingPolicyConfigPolicy, BackendServiceLogConfig, + BackendServiceLogConfigLoggingHttpHeader, BackendServiceNetworkPassThroughLbTrafficPolicy, BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity, BackendServiceOrchestrationInfo, @@ -227,6 +230,7 @@ CalendarModeRecommendation, CancelFutureReservationRequest, CancelInstanceGroupManagerResizeRequestRequest, + CancelOrganizationRolloutRequest, CancelRegionInstanceGroupManagerResizeRequestRequest, CancelRequestRemovePeeringNetworkRequest, CancelRolloutRequest, @@ -287,6 +291,7 @@ CustomErrorResponsePolicyCustomErrorResponseRule, Data, Date, + DateTime, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -335,6 +340,8 @@ DeleteNodeGroupRequest, DeleteNodesNodeGroupRequest, DeleteNodeTemplateRequest, + DeleteOrganizationRolloutPlanRequest, + DeleteOrganizationRolloutRequest, DeleteOrganizationSecurityPolicyRequest, DeletePacketMirroringRequest, DeletePerInstanceConfigsInstanceGroupManagerRequest, @@ -538,6 +545,7 @@ GetHealthRegionCompositeHealthCheckRequest, GetHealthRegionHealthSourceRequest, GetHealthTargetPoolRequest, + GetHostRequest, GetIamPolicyBackendBucketRequest, GetIamPolicyBackendServiceRequest, GetIamPolicyDiskRequest, @@ -574,6 +582,7 @@ GetIamPolicySubnetworkRequest, GetImageFamilyViewRequest, GetImageRequest, + GetImageViewRequest, GetInstanceGroupManagerRequest, GetInstanceGroupManagerResizeRequestRequest, GetInstanceGroupRequest, @@ -607,6 +616,8 @@ GetNodeTypeRequest, GetOperationalStatusInterconnectAttachmentGroupRequest, GetOperationalStatusInterconnectGroupRequest, + GetOrganizationRolloutPlanRequest, + GetOrganizationRolloutRequest, GetOrganizationSecurityPolicyRequest, GetPacketMirroringRequest, GetPacketMirroringRuleFirewallPolicyRequest, @@ -614,6 +625,7 @@ GetPartnerMetadataInstanceRequest, GetPreviewFeatureRequest, GetProjectRequest, + GetProjectViewRequest, GetPublicAdvertisedPrefixeRequest, GetPublicDelegatedPrefixeRequest, GetRegionAutoscalerRequest, @@ -651,6 +663,7 @@ GetRegionTargetHttpsProxyRequest, GetRegionTargetTcpProxyRequest, GetRegionUrlMapRequest, + GetReliabilityRiskRequest, GetReservationBlockRequest, GetReservationRequest, GetReservationSlotRequest, @@ -693,6 +706,7 @@ GetTargetVpnGatewayRequest, GetTrafficClassificationRuleRegionNetworkPolicyRequest, GetUrlMapRequest, + GetVersionHostRequest, GetVersionOperationMetadata, GetVersionOperationMetadataSbomInfo, GetVersionReservationSlotRequest, @@ -754,7 +768,12 @@ HealthStatusForNetworkEndpoint, Help, HelpLink, + Host, + HostPhysicalTopology, HostRule, + HostsGetVersionRequest, + HostsListResponse, + HostStatus, HTTP2HealthCheck, HttpFaultAbort, HttpFaultDelay, @@ -774,7 +793,9 @@ Image, ImageFamilyView, ImageList, + ImageOptimizationPolicy, ImageParams, + ImageView, InitialStateConfig, InsertAddressRequest, InsertAutoscalerRequest, @@ -814,6 +835,7 @@ InsertNetworkRequest, InsertNodeGroupRequest, InsertNodeTemplateRequest, + InsertOrganizationRolloutPlanRequest, InsertOrganizationSecurityPolicyRequest, InsertPacketMirroringRequest, InsertPublicAdvertisedPrefixeRequest, @@ -1104,6 +1126,7 @@ ListGlobalPublicDelegatedPrefixesRequest, ListGlobalVmExtensionPoliciesRequest, ListHealthChecksRequest, + ListHostsRequest, ListImagesRequest, ListInstanceGroupManagerResizeRequestsRequest, ListInstanceGroupManagersRequest, @@ -1139,6 +1162,8 @@ ListNodesNodeGroupsRequest, ListNodeTemplatesRequest, ListNodeTypesRequest, + ListOrganizationRolloutPlansRequest, + ListOrganizationRolloutsRequest, ListOrganizationSecurityPoliciesRequest, ListPacketMirroringsRequest, ListPeeringRoutesNetworksRequest, @@ -1184,6 +1209,7 @@ ListRegionTargetTcpProxiesRequest, ListRegionUrlMapsRequest, ListRegionZonesRequest, + ListReliabilityRisksRequest, ListReservationBlocksRequest, ListReservationSlotsRequest, ListReservationsRequest, @@ -1362,6 +1388,7 @@ OperationAggregatedList, OperationList, OperationsScopedList, + OrganizationRolloutsListResponse, OrganizationSecurityPoliciesListAssociationsResponse, OutlierDetection, PacketIntervals, @@ -1449,12 +1476,16 @@ PatchWireGroupRequest, PathMatcher, PathRule, + PauseOrganizationRolloutRequest, + PauseRolloutRequest, PerformMaintenanceInstanceRequest, PerformMaintenanceNodeGroupRequest, PerformMaintenanceReservationBlockRequest, PerformMaintenanceReservationRequest, PerformMaintenanceReservationSubBlockRequest, PerInstanceConfig, + PeriodicPartialMaintenanceSchedule, + PersistentDiskResourceCommitment, Policy, PreconfiguredWafSet, PreservedState, @@ -1476,6 +1507,7 @@ ProjectsSetCloudArmorTierRequest, ProjectsSetDefaultNetworkTierRequest, ProjectsSetManagedProtectionTierRequest, + ProjectView, PublicAdvertisedPrefix, PublicAdvertisedPrefixList, PublicAdvertisedPrefixPublicDelegatedPrefix, @@ -1491,6 +1523,7 @@ RecreateInstancesInstanceGroupManagerRequest, RecreateInstancesRegionInstanceGroupManagerRequest, Reference, + RegexRewrite, Region, RegionAddressesMoveRequest, RegionAutoscalerList, @@ -1537,6 +1570,8 @@ RegionSnapshotUpdateKmsKeyRequest, RegionTargetHttpsProxiesSetSslCertificatesRequest, RegionUrlMapsValidateRequest, + ReliabilityRisk, + ReliabilityRisksListResponse, RemoveAssociationFirewallPolicyRequest, RemoveAssociationNetworkFirewallPolicyRequest, RemoveAssociationOrganizationSecurityPolicyRequest, @@ -1625,12 +1660,18 @@ ResourceStatus, ResourceStatusEffectiveInstanceMetadata, ResourceStatusPhysicalHostTopology, + ResourceStatusPhysicalHostTopologyAdditionalAttributes, ResourceStatusReservationConsumptionInfo, ResourceStatusScheduling, ResourceStatusShutdownDetails, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + ResumeOrganizationRolloutRequest, + ResumeRolloutRequest, + RiskDetails, + RiskDetailsGlobalDnsInsight, + RiskRecommendation, Rollout, RolloutPlan, RolloutPlansListResponse, @@ -1851,6 +1892,7 @@ SetUrlMapTargetHttpsProxyRequest, SetUsageExportBucketProjectRequest, ShareSettings, + ShareSettingsFolderConfig, ShareSettingsProjectConfig, ShieldedInstanceConfig, ShieldedInstanceIdentity, @@ -2074,6 +2116,7 @@ TestIamPermissionsVpnTunnelRequest, TestPermissionsRequest, TestPermissionsResponse, + TimeZone, Uint128, UpcomingMaintenance, UpdateAccessConfigInstanceRequest, @@ -2190,6 +2233,7 @@ XpnResourceId, Zone, ZoneList, + ZoneResourceStatus, ZoneSetLabelsRequest, ZoneSetNestedPolicyRequest, ZoneSetPolicyRequest, @@ -2240,6 +2284,8 @@ "AddTrafficClassificationRuleRegionNetworkPolicyRequest", "AdoptInstancesRegionInstanceGroupManagerRequest", "AdvancedMachineFeatures", + "AdvanceOrganizationRolloutRequest", + "AdvanceRolloutRequest", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", @@ -2369,6 +2415,7 @@ "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -2409,6 +2456,7 @@ "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", + "CancelOrganizationRolloutRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", @@ -2469,6 +2517,7 @@ "CustomErrorResponsePolicyCustomErrorResponseRule", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2517,6 +2566,8 @@ "DeleteNodeGroupRequest", "DeleteNodesNodeGroupRequest", "DeleteNodeTemplateRequest", + "DeleteOrganizationRolloutPlanRequest", + "DeleteOrganizationRolloutRequest", "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", @@ -2720,6 +2771,7 @@ "GetHealthRegionCompositeHealthCheckRequest", "GetHealthRegionHealthSourceRequest", "GetHealthTargetPoolRequest", + "GetHostRequest", "GetIamPolicyBackendBucketRequest", "GetIamPolicyBackendServiceRequest", "GetIamPolicyDiskRequest", @@ -2756,6 +2808,7 @@ "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", "GetImageRequest", + "GetImageViewRequest", "GetInstanceGroupManagerRequest", "GetInstanceGroupManagerResizeRequestRequest", "GetInstanceGroupRequest", @@ -2789,6 +2842,8 @@ "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationRolloutPlanRequest", + "GetOrganizationRolloutRequest", "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleFirewallPolicyRequest", @@ -2796,6 +2851,7 @@ "GetPartnerMetadataInstanceRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -2833,6 +2889,7 @@ "GetRegionTargetHttpsProxyRequest", "GetRegionTargetTcpProxyRequest", "GetRegionUrlMapRequest", + "GetReliabilityRiskRequest", "GetReservationBlockRequest", "GetReservationRequest", "GetReservationSlotRequest", @@ -2875,6 +2932,7 @@ "GetTargetVpnGatewayRequest", "GetTrafficClassificationRuleRegionNetworkPolicyRequest", "GetUrlMapRequest", + "GetVersionHostRequest", "GetVersionOperationMetadata", "GetVersionOperationMetadataSbomInfo", "GetVersionReservationSlotRequest", @@ -2936,7 +2994,12 @@ "HealthStatusForNetworkEndpoint", "Help", "HelpLink", + "Host", + "HostPhysicalTopology", "HostRule", + "HostsGetVersionRequest", + "HostsListResponse", + "HostStatus", "HTTP2HealthCheck", "HttpFaultAbort", "HttpFaultDelay", @@ -2956,7 +3019,9 @@ "Image", "ImageFamilyView", "ImageList", + "ImageOptimizationPolicy", "ImageParams", + "ImageView", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -2996,6 +3061,7 @@ "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationRolloutPlanRequest", "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", @@ -3286,6 +3352,7 @@ "ListGlobalPublicDelegatedPrefixesRequest", "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", + "ListHostsRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", "ListInstanceGroupManagersRequest", @@ -3321,6 +3388,8 @@ "ListNodesNodeGroupsRequest", "ListNodeTemplatesRequest", "ListNodeTypesRequest", + "ListOrganizationRolloutPlansRequest", + "ListOrganizationRolloutsRequest", "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", @@ -3366,6 +3435,7 @@ "ListRegionTargetTcpProxiesRequest", "ListRegionUrlMapsRequest", "ListRegionZonesRequest", + "ListReliabilityRisksRequest", "ListReservationBlocksRequest", "ListReservationSlotsRequest", "ListReservationsRequest", @@ -3544,6 +3614,7 @@ "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationRolloutsListResponse", "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", "PacketIntervals", @@ -3631,12 +3702,16 @@ "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseOrganizationRolloutRequest", + "PauseRolloutRequest", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", "PerInstanceConfig", + "PeriodicPartialMaintenanceSchedule", + "PersistentDiskResourceCommitment", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -3658,6 +3733,7 @@ "ProjectsSetCloudArmorTierRequest", "ProjectsSetDefaultNetworkTierRequest", "ProjectsSetManagedProtectionTierRequest", + "ProjectView", "PublicAdvertisedPrefix", "PublicAdvertisedPrefixList", "PublicAdvertisedPrefixPublicDelegatedPrefix", @@ -3673,6 +3749,7 @@ "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -3719,6 +3796,8 @@ "RegionSnapshotUpdateKmsKeyRequest", "RegionTargetHttpsProxiesSetSslCertificatesRequest", "RegionUrlMapsValidateRequest", + "ReliabilityRisk", + "ReliabilityRisksListResponse", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", "RemoveAssociationOrganizationSecurityPolicyRequest", @@ -3807,12 +3886,18 @@ "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResourceStatusShutdownDetails", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeOrganizationRolloutRequest", + "ResumeRolloutRequest", + "RiskDetails", + "RiskDetailsGlobalDnsInsight", + "RiskRecommendation", "Rollout", "RolloutPlan", "RolloutPlansListResponse", @@ -4033,6 +4118,7 @@ "SetUrlMapTargetHttpsProxyRequest", "SetUsageExportBucketProjectRequest", "ShareSettings", + "ShareSettingsFolderConfig", "ShareSettingsProjectConfig", "ShieldedInstanceConfig", "ShieldedInstanceIdentity", @@ -4256,6 +4342,7 @@ "TestIamPermissionsVpnTunnelRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -4372,6 +4459,7 @@ "XpnResourceId", "Zone", "ZoneList", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", 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 ad9ee94e51c4..17f62f060d16 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 @@ -68,6 +68,8 @@ "AddressList", "AddressesScopedList", "AdoptInstancesRegionInstanceGroupManagerRequest", + "AdvanceOrganizationRolloutRequest", + "AdvanceRolloutRequest", "AdvancedMachineFeatures", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", @@ -197,6 +199,7 @@ "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -237,6 +240,7 @@ "CalendarModeRecommendation", "CancelFutureReservationRequest", "CancelInstanceGroupManagerResizeRequestRequest", + "CancelOrganizationRolloutRequest", "CancelRegionInstanceGroupManagerResizeRequestRequest", "CancelRequestRemovePeeringNetworkRequest", "CancelRolloutRequest", @@ -297,6 +301,7 @@ "CustomerEncryptionKeyProtectedDisk", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -345,6 +350,8 @@ "DeleteNodeGroupRequest", "DeleteNodeTemplateRequest", "DeleteNodesNodeGroupRequest", + "DeleteOrganizationRolloutPlanRequest", + "DeleteOrganizationRolloutRequest", "DeleteOrganizationSecurityPolicyRequest", "DeletePacketMirroringRequest", "DeletePerInstanceConfigsInstanceGroupManagerRequest", @@ -550,6 +557,7 @@ "GetHealthRegionCompositeHealthCheckRequest", "GetHealthRegionHealthSourceRequest", "GetHealthTargetPoolRequest", + "GetHostRequest", "GetIamPolicyBackendBucketRequest", "GetIamPolicyBackendServiceRequest", "GetIamPolicyDiskRequest", @@ -586,6 +594,7 @@ "GetIamPolicySubnetworkRequest", "GetImageFamilyViewRequest", "GetImageRequest", + "GetImageViewRequest", "GetInstanceGroupManagerRequest", "GetInstanceGroupManagerResizeRequestRequest", "GetInstanceGroupRequest", @@ -619,6 +628,8 @@ "GetNodeTypeRequest", "GetOperationalStatusInterconnectAttachmentGroupRequest", "GetOperationalStatusInterconnectGroupRequest", + "GetOrganizationRolloutPlanRequest", + "GetOrganizationRolloutRequest", "GetOrganizationSecurityPolicyRequest", "GetPacketMirroringRequest", "GetPacketMirroringRuleFirewallPolicyRequest", @@ -626,6 +637,7 @@ "GetPartnerMetadataInstanceRequest", "GetPreviewFeatureRequest", "GetProjectRequest", + "GetProjectViewRequest", "GetPublicAdvertisedPrefixeRequest", "GetPublicDelegatedPrefixeRequest", "GetRegionAutoscalerRequest", @@ -663,6 +675,7 @@ "GetRegionTargetHttpsProxyRequest", "GetRegionTargetTcpProxyRequest", "GetRegionUrlMapRequest", + "GetReliabilityRiskRequest", "GetReservationBlockRequest", "GetReservationRequest", "GetReservationSlotRequest", @@ -705,6 +718,7 @@ "GetTargetVpnGatewayRequest", "GetTrafficClassificationRuleRegionNetworkPolicyRequest", "GetUrlMapRequest", + "GetVersionHostRequest", "GetVersionOperationMetadata", "GetVersionOperationMetadataSbomInfo", "GetVersionReservationSlotRequest", @@ -767,7 +781,12 @@ "HealthStatusForNetworkEndpoint", "Help", "HelpLink", + "Host", + "HostPhysicalTopology", "HostRule", + "HostStatus", + "HostsGetVersionRequest", + "HostsListResponse", "HttpFaultAbort", "HttpFaultDelay", "HttpFaultInjection", @@ -784,7 +803,9 @@ "Image", "ImageFamilyView", "ImageList", + "ImageOptimizationPolicy", "ImageParams", + "ImageView", "InitialStateConfig", "InsertAddressRequest", "InsertAutoscalerRequest", @@ -824,6 +845,7 @@ "InsertNetworkRequest", "InsertNodeGroupRequest", "InsertNodeTemplateRequest", + "InsertOrganizationRolloutPlanRequest", "InsertOrganizationSecurityPolicyRequest", "InsertPacketMirroringRequest", "InsertPublicAdvertisedPrefixeRequest", @@ -1114,6 +1136,7 @@ "ListGlobalPublicDelegatedPrefixesRequest", "ListGlobalVmExtensionPoliciesRequest", "ListHealthChecksRequest", + "ListHostsRequest", "ListImagesRequest", "ListInstanceGroupManagerResizeRequestsRequest", "ListInstanceGroupManagersRequest", @@ -1149,6 +1172,8 @@ "ListNodeTemplatesRequest", "ListNodeTypesRequest", "ListNodesNodeGroupsRequest", + "ListOrganizationRolloutPlansRequest", + "ListOrganizationRolloutsRequest", "ListOrganizationSecurityPoliciesRequest", "ListPacketMirroringsRequest", "ListPeeringRoutesNetworksRequest", @@ -1194,6 +1219,7 @@ "ListRegionUrlMapsRequest", "ListRegionZonesRequest", "ListRegionsRequest", + "ListReliabilityRisksRequest", "ListReservationBlocksRequest", "ListReservationSlotsRequest", "ListReservationSubBlocksRequest", @@ -1372,6 +1398,7 @@ "OperationAggregatedList", "OperationList", "OperationsScopedList", + "OrganizationRolloutsListResponse", "OrganizationSecurityPoliciesListAssociationsResponse", "OutlierDetection", "PacketIntervals", @@ -1459,12 +1486,16 @@ "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseOrganizationRolloutRequest", + "PauseRolloutRequest", "PerInstanceConfig", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", + "PeriodicPartialMaintenanceSchedule", + "PersistentDiskResourceCommitment", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -1479,6 +1510,7 @@ "PreviewFeatureStatusReleaseStatus", "PreviewRouterRequest", "Project", + "ProjectView", "ProjectsDisableXpnResourceRequest", "ProjectsEnableXpnResourceRequest", "ProjectsGetXpnResources", @@ -1501,6 +1533,7 @@ "RecreateInstancesInstanceGroupManagerRequest", "RecreateInstancesRegionInstanceGroupManagerRequest", "Reference", + "RegexRewrite", "Region", "RegionAddressesMoveRequest", "RegionAutoscalerList", @@ -1547,6 +1580,8 @@ "RegionSnapshotUpdateKmsKeyRequest", "RegionTargetHttpsProxiesSetSslCertificatesRequest", "RegionUrlMapsValidateRequest", + "ReliabilityRisk", + "ReliabilityRisksListResponse", "RemoveAssociationFirewallPolicyRequest", "RemoveAssociationNetworkFirewallPolicyRequest", "RemoveAssociationOrganizationSecurityPolicyRequest", @@ -1635,12 +1670,18 @@ "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResourceStatusShutdownDetails", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeOrganizationRolloutRequest", + "ResumeRolloutRequest", + "RiskDetails", + "RiskDetailsGlobalDnsInsight", + "RiskRecommendation", "Rollout", "RolloutPlan", "RolloutPlanWave", @@ -1862,6 +1903,7 @@ "SetUrlMapTargetHttpsProxyRequest", "SetUsageExportBucketProjectRequest", "ShareSettings", + "ShareSettingsFolderConfig", "ShareSettingsProjectConfig", "ShieldedInstanceConfig", "ShieldedInstanceIdentity", @@ -2084,6 +2126,7 @@ "TestIamPermissionsVpnTunnelRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -2200,6 +2243,7 @@ "XpnResourceId", "Zone", "ZoneList", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", @@ -4818,27 +4862,39 @@ class Address(proto.Message): This field is a member of `oneof`_ ``_id``. ip_collection (str): - Reference to the source of external IPv4 - addresses, like a PublicDelegatedPrefix (PDP) - for BYOIP. The PDP must support enhanced IPv4 - allocations. + Reference to the source of IP addresses. - Use one of the following formats to specify a - PDP when reserving an external IPv4 address - using BYOIP. + It supports the following cases: - - Full resource URL, as - inhttps://www.googleapis.com/compute/v1/projects/projectId/regions/region/publicDelegatedPrefixes/pdp-name - - - Partial URL, as in + Case 1: PublicDelegatedPrefix (PDP) for + BYOIP external IPv4 addresses. The PDP must + support enhanced IPv4 allocations. - + Case 2: Internal Range for global internal + addresses. + + Use one of the following formats to specify the + resource: + For a Public Delegated Prefix: + + - + Full resource + URL:https://www.googleapis.com/compute/v1/projects/projectId/regions/region/publicDelegatedPrefixes/pdp + - Partial URL: - - + - projects/projectId/regions/region/publicDelegatedPrefixes/pdp-name - - + - regions/region/publicDelegatedPrefixes/pdp-name + For an Internal Range: + + - Full + URL:https://networkconnectivity.googleapis.com/v1/projects/project/locations/global/internalRanges/internal-range + - Partial + URL:projects/project/locations/global/internalRanges/internal-range + This field is a member of `oneof`_ ``_ip_collection``. ip_version (str): The IP version that will be used by this @@ -5153,6 +5209,11 @@ class Purpose(proto.Enum): A private network IP address that can be shared by multiple Internal Load Balancer forwarding rules. + SYSTEM_MANAGED (429787503): + A regional internal IP address that is + reserved and managed internally. It can not be + assigned to compute resources such as VM and + internal load balancer. VPC_PEERING (400800170): IP range for peer networks. """ @@ -5167,6 +5228,7 @@ class Purpose(proto.Enum): PRIVATE_SERVICE_CONNECT = 48134724 SERVERLESS = 270492508 SHARED_LOADBALANCER_VIP = 294447572 + SYSTEM_MANAGED = 429787503 VPC_PEERING = 400800170 class Status(proto.Enum): @@ -5553,6 +5615,128 @@ class AdoptInstancesRegionInstanceGroupManagerRequest(proto.Message): ) +class AdvanceOrganizationRolloutRequest(proto.Message): + r"""A request message for OrganizationRollouts.Advance. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + current_wave_number (int): + Required. Wave number of the current wave. + + This field is a member of `oneof`_ ``_current_wave_number``. + organization (str): + Required. Organization ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + advance. + """ + + current_wave_number: int = proto.Field( + proto.INT64, + number=178280841, + optional=True, + ) + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + +class AdvanceRolloutRequest(proto.Message): + r"""A request message for Rollouts.Advance. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + current_wave_number (int): + Required. Wave number of the current wave. + + This field is a member of `oneof`_ ``_current_wave_number``. + project (str): + Required. Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + advance. + """ + + current_wave_number: int = proto.Field( + proto.INT64, + number=178280841, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class AdvancedMachineFeatures(proto.Message): r"""Specifies options for controlling advanced machine features. Options that would traditionally be configured in a BIOS belong @@ -17561,30 +17745,6 @@ class AttachedDiskInitializeParams(proto.Message): This field is a member of `oneof`_ ``_disk_size_gb``. disk_type (str): - Specifies the disk type to use to create the - instance. If not specified, the default is - pd-standard, specified using the full URL. For - example: - - https://www.googleapis.com/compute/v1/projects/project/zones/zone/diskTypes/pd-standard - - For a full list of acceptable values, - seePersistent disk types. If you specify this - field when creating a VM, you can provide either - the full or partial URL. For example, the - following values are valid: - - - - - https://www.googleapis.com/compute/v1/projects/project/zones/zone/diskTypes/diskType - - - projects/project/zones/zone/diskTypes/diskType - - zones/zone/diskTypes/diskType - - If you specify this field when creating or - updating an instance template or all-instances - configuration, specify the type of the disk, not - the URL. For example: pd-standard. This field is a member of `oneof`_ ``_disk_type``. enable_confidential_compute (bool): @@ -18896,8 +19056,9 @@ class Mode(proto.Enum): Automatically create VMs according to the policy, but do not scale the MIG in. ONLY_UP (478095374): - Automatically create VMs according to the - policy, but do not scale the MIG in. + Automatically create VMs according to the policy, but do not + scale the MIG in. It's recommended to use ONLY_SCALE_OUT + instead of ONLY_UP. """ UNDEFINED_MODE = 0 @@ -23703,6 +23864,12 @@ class BackendServiceLogConfig(proto.Message): service. The default value is false. This field is a member of `oneof`_ ``_enable``. + logging_http_request_headers (MutableSequence[google.cloud.compute_v1beta.types.BackendServiceLogConfigLoggingHttpHeader]): + The list of request headers that will be + logged to Stackdriver. + logging_http_response_headers (MutableSequence[google.cloud.compute_v1beta.types.BackendServiceLogConfigLoggingHttpHeader]): + The list of response headers that will be + logged to Stackdriver. optional_fields (MutableSequence[str]): This field can only be specified if logging is enabled for this backend service and @@ -23761,6 +23928,20 @@ class OptionalMode(proto.Enum): number=311764355, optional=True, ) + logging_http_request_headers: MutableSequence[ + "BackendServiceLogConfigLoggingHttpHeader" + ] = proto.RepeatedField( + proto.MESSAGE, + number=430426367, + message="BackendServiceLogConfigLoggingHttpHeader", + ) + logging_http_response_headers: MutableSequence[ + "BackendServiceLogConfigLoggingHttpHeader" + ] = proto.RepeatedField( + proto.MESSAGE, + number=515407743, + message="BackendServiceLogConfigLoggingHttpHeader", + ) optional_fields: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=528589944, @@ -23777,6 +23958,25 @@ class OptionalMode(proto.Enum): ) +class BackendServiceLogConfigLoggingHttpHeader(proto.Message): + r"""Determines which HTTP headers will be logged to Stackdriver. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + header_name (str): + The name of the header to be logged. + + This field is a member of `oneof`_ ``_header_name``. + """ + + header_name: str = proto.Field( + proto.STRING, + number=110223613, + optional=True, + ) + + class BackendServiceNetworkPassThroughLbTrafficPolicy(proto.Message): r""" @@ -26424,25 +26624,16 @@ class CancelInstanceGroupManagerResizeRequestRequest(proto.Message): ) -class CancelRegionInstanceGroupManagerResizeRequestRequest(proto.Message): - r"""A request message for - RegionInstanceGroupManagerResizeRequests.Cancel. See the method - description for details. +class CancelOrganizationRolloutRequest(proto.Message): + r"""A request message for OrganizationRollouts.Cancel. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - instance_group_manager (str): - The name of the managed instance group. - Name should conform to RFC1035 or be a resource - ID. - project (str): - Project ID for this request. - region (str): - The name of the region - scoping this request. Name should conform to - RFC1035. + organization (str): + Required. Organization ID for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -26465,96 +26656,170 @@ class CancelRegionInstanceGroupManagerResizeRequestRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - resize_request (str): - The name of the resize request to cancel. - Name should conform to RFC1035 or be a resource - ID. + rollback (bool): + Optional. If true, then the ongoing rollout + must be rolled back. Else, just cancel the + rollout without taking any further actions. Note + that products must support at least one of these + options, however, it does not need to support + both. + + This field is a member of `oneof`_ ``_rollback``. + rollout (str): + Name of the Rollout resource to cancel. """ - instance_group_manager: str = proto.Field( - proto.STRING, - number=249363395, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( + organization: str = proto.Field( proto.STRING, - number=138946292, + number=105180467, ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - resize_request: str = proto.Field( - proto.STRING, - number=216941060, - ) - - -class CancelRequestRemovePeeringNetworkRequest(proto.Message): - r"""A request message for Networks.CancelRequestRemovePeering. - See the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - network (str): - Name of the network resource to remove - peering from. - networks_cancel_request_remove_peering_request_resource (google.cloud.compute_v1beta.types.NetworksCancelRequestRemovePeeringRequest): - The body resource for this request - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - """ - - network: str = proto.Field( - proto.STRING, - number=232872494, - ) - networks_cancel_request_remove_peering_request_resource: "NetworksCancelRequestRemovePeeringRequest" = proto.Field( - proto.MESSAGE, - number=177326909, - message="NetworksCancelRequestRemovePeeringRequest", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, + rollback: bool = proto.Field( + proto.BOOL, + number=277151460, + optional=True, ) - request_id: str = proto.Field( + rollout: str = proto.Field( proto.STRING, - number=37109963, - optional=True, + number=303366577, ) -class CancelRolloutRequest(proto.Message): - r"""A request message for Rollouts.Cancel. See the method +class CancelRegionInstanceGroupManagerResizeRequestRequest(proto.Message): + r"""A request message for + RegionInstanceGroupManagerResizeRequests.Cancel. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_group_manager (str): + The name of the managed instance group. + Name should conform to RFC1035 or be a resource + ID. + project (str): + Project ID for this request. + region (str): + The name of the region + scoping this request. Name should conform to + RFC1035. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + resize_request (str): + The name of the resize request to cancel. + Name should conform to RFC1035 or be a resource + ID. + """ + + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + resize_request: str = proto.Field( + proto.STRING, + number=216941060, + ) + + +class CancelRequestRemovePeeringNetworkRequest(proto.Message): + r"""A request message for Networks.CancelRequestRemovePeering. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network (str): + Name of the network resource to remove + peering from. + networks_cancel_request_remove_peering_request_resource (google.cloud.compute_v1beta.types.NetworksCancelRequestRemovePeeringRequest): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + network: str = proto.Field( + proto.STRING, + number=232872494, + ) + networks_cancel_request_remove_peering_request_resource: "NetworksCancelRequestRemovePeeringRequest" = proto.Field( + proto.MESSAGE, + number=177326909, + message="NetworksCancelRequestRemovePeeringRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class CancelRolloutRequest(proto.Message): + r"""A request message for Rollouts.Cancel. See the method description for details. @@ -27325,15 +27590,23 @@ class CapacityHistoryResponse(proto.Message): Attributes: location (str): + Output only. The location (region or zone) + for which the capacity history is returned. It + is returned as a URL - For + example,https://www.googleapis.com/compute/v1/projects/project/zones/zone. This field is a member of `oneof`_ ``_location``. machine_type (str): + The machine type for which the capacity + history is returned. This field is a member of `oneof`_ ``_machine_type``. preemption_history (MutableSequence[google.cloud.compute_v1beta.types.CapacityHistoryResponsePreemptionRecord]): - + The preemption history for the requested + machine type and location. price_history (MutableSequence[google.cloud.compute_v1beta.types.CapacityHistoryResponsePriceRecord]): - + The price history for the requested machine + type and location. """ location: str = proto.Field( @@ -27363,15 +27636,21 @@ class CapacityHistoryResponse(proto.Message): class CapacityHistoryResponsePreemptionRecord(proto.Message): - r""" + r"""A record of Spot VM preemption history. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: interval (google.cloud.compute_v1beta.types.Interval): + The time interval for this preemption record. This field is a member of `oneof`_ ``_interval``. preemption_rate (float): + The preemption rate during the interval, + representing the fraction of Spot VMs that were + preempted. Range: 0.0 to 1.0. Preemption rate is + calculated as (total preempted Spots) / (total + Spots that stopped running). This field is a member of `oneof`_ ``_preemption_rate``. """ @@ -27390,15 +27669,17 @@ class CapacityHistoryResponsePreemptionRecord(proto.Message): class CapacityHistoryResponsePriceRecord(proto.Message): - r""" + r"""A record of price history. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: interval (google.cloud.compute_v1beta.types.Interval): + The time interval for this price record. This field is a member of `oneof`_ ``_interval``. list_price (google.cloud.compute_v1beta.types.Money): + The Spot VM list price during the interval. This field is a member of `oneof`_ ``_list_price``. """ @@ -27803,6 +28084,10 @@ class Commitment(proto.Message): payload. This field is a member of `oneof`_ ``_params``. + persistent_disk_resources (MutableSequence[google.cloud.compute_v1beta.types.PersistentDiskResourceCommitment]): + Optional. Used when category is PERSISTENT_DISK. Each entry + in the list represents a commitment to a specific Persistent + Disk product type and dimension. plan (str): The minimum time duration that you commit to purchasing resources. The plan that you choose determines the preset @@ -27919,12 +28204,15 @@ class Category(proto.Enum): No description available. MACHINE (469553191): No description available. + PERSISTENT_DISK (468535877): + No description available. """ UNDEFINED_CATEGORY = 0 CATEGORY_UNSPECIFIED = 509189462 LICENSE = 347869217 MACHINE = 469553191 + PERSISTENT_DISK = 468535877 class Plan(proto.Enum): r"""The minimum time duration that you commit to purchasing resources. @@ -28205,6 +28493,13 @@ class Type(proto.Enum): optional=True, message="CommitmentParams", ) + persistent_disk_resources: MutableSequence["PersistentDiskResourceCommitment"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=409937067, + message="PersistentDiskResourceCommitment", + ) + ) plan: str = proto.Field( proto.STRING, number=3443497, @@ -28974,6 +29269,8 @@ class ConfidentialInstanceType(proto.Enum): UNDEFINED_CONFIDENTIAL_INSTANCE_TYPE (0): A value indicating that the enum field is not set. + CCA (66529): + Arm Confidential Compute Architecture. CONFIDENTIAL_INSTANCE_TYPE_UNSPECIFIED (115021829): No type specified. Do not use this value. SEV (81988): @@ -28986,6 +29283,7 @@ class ConfidentialInstanceType(proto.Enum): """ UNDEFINED_CONFIDENTIAL_INSTANCE_TYPE = 0 + CCA = 66529 CONFIDENTIAL_INSTANCE_TYPE_UNSPECIFIED = 115021829 SEV = 81988 SEV_SNP = 21753562 @@ -30176,142 +30474,155 @@ class Date(proto.Message): ) -class DeleteAccessConfigInstanceRequest(proto.Message): - r"""A request message for Instances.DeleteAccessConfig. See the - method description for details. +class DateTime(proto.Message): + r"""Represents civil time (or occasionally physical time). + This type can represent a civil time in one of a few possible ways: - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + - When utc_offset is set and time_zone is unset: a civil time on a + calendar day with a particular offset from UTC. + - When time_zone is set and utc_offset is unset: a civil time on a + calendar day in a particular time zone. + - When neither time_zone nor utc_offset is set: a civil time on a + calendar day in local time. - Attributes: - access_config (str): - The name of the access config to delete. - instance (str): - The instance name for this request. - network_interface (str): - The name of the network interface. - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + The date is relative to the Proleptic Gregorian Calendar. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + If year, month, or day are 0, the DateTime is considered not to have + a specific year, month, or day respectively. - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + This type may also be used to represent a physical time if all the + date and time fields are set and either case of the ``time_offset`` + oneof is set. Consider using ``Timestamp`` message for physical time + instead. If your use case also would like to store the user's + timezone, that can be done in another field. - This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of the zone for this request. - """ + This type is more flexible than some applications may want. Make + sure to document and validate your application's limitations. - access_config: str = proto.Field( - proto.STRING, - number=72856189, - ) - instance: str = proto.Field( - proto.STRING, - number=18257045, - ) - network_interface: str = proto.Field( - proto.STRING, - number=365387880, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields -class DeleteAddressRequest(proto.Message): - r"""A request message for Addresses.Delete. See the method - description for details. + Attributes: + day (int): + Optional. Day of month. Must be from 1 to 31 + and valid for the year and month, or 0 if + specifying a datetime without a day. + This field is a member of `oneof`_ ``_day``. + hours (int): + Optional. Hours of day in 24 hour format. + Should be from 0 to 23, defaults to 0 + (midnight). An API may choose to allow the value + "24:00:00" for scenarios like business closing + time. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + This field is a member of `oneof`_ ``_hours``. + minutes (int): + Optional. Minutes of hour of day. Must be + from 0 to 59, defaults to 0. - Attributes: - address (str): - Name of the address resource to delete. - project (str): - Project ID for this request. - region (str): - Name of the region for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + This field is a member of `oneof`_ ``_minutes``. + month (int): + Optional. Month of year. Must be from 1 to + 12, or 0 if specifying a datetime without a + month. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + This field is a member of `oneof`_ ``_month``. + nanos (int): + Optional. Fractions of seconds in + nanoseconds. Must be from 0 to 999,999,999, + defaults to 0. - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + This field is a member of `oneof`_ ``_nanos``. + seconds (int): + Optional. Seconds of minutes of the time. + Must normally be from 0 to 59, defaults to 0. An + API may allow the value 60 if it allows + leap-seconds. - This field is a member of `oneof`_ ``_request_id``. + This field is a member of `oneof`_ ``_seconds``. + time_zone (google.cloud.compute_v1beta.types.TimeZone): + Time zone. + + This field is a member of `oneof`_ ``_time_zone``. + utc_offset (str): + UTC offset. Must be whole seconds, between + -18 hours and +18 hours. For example, a UTC + offset of -4:00 would be represented as { + seconds: -14400 }. + + This field is a member of `oneof`_ ``_utc_offset``. + year (int): + Optional. Year of date. Must be from 1 to + 9999, or 0 if specifying a datetime without a + year. + + This field is a member of `oneof`_ ``_year``. """ - address: str = proto.Field( - proto.STRING, - number=462920692, + day: int = proto.Field( + proto.INT32, + number=99228, + optional=True, ) - project: str = proto.Field( - proto.STRING, - number=227560217, + hours: int = proto.Field( + proto.INT32, + number=99469071, + optional=True, ) - region: str = proto.Field( - proto.STRING, - number=138946292, + minutes: int = proto.Field( + proto.INT32, + number=528030943, + optional=True, ) - request_id: str = proto.Field( + month: int = proto.Field( + proto.INT32, + number=104080000, + optional=True, + ) + nanos: int = proto.Field( + proto.INT32, + number=104586303, + optional=True, + ) + seconds: int = proto.Field( + proto.INT32, + number=359484031, + optional=True, + ) + time_zone: "TimeZone" = proto.Field( + proto.MESSAGE, + number=36848094, + optional=True, + message="TimeZone", + ) + utc_offset: str = proto.Field( proto.STRING, - number=37109963, + number=89045902, + optional=True, + ) + year: int = proto.Field( + proto.INT32, + number=3704893, optional=True, ) -class DeleteAutoscalerRequest(proto.Message): - r"""A request message for Autoscalers.Delete. See the method - description for details. +class DeleteAccessConfigInstanceRequest(proto.Message): + r"""A request message for Instances.DeleteAccessConfig. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - autoscaler (str): - Name of the autoscaler to delete. + access_config (str): + The name of the access config to delete. + instance (str): + The instance name for this request. + network_interface (str): + The name of the network interface. project (str): Project ID for this request. request_id (str): @@ -30337,12 +30648,20 @@ class DeleteAutoscalerRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. zone (str): - Name of the zone for this request. + The name of the zone for this request. """ - autoscaler: str = proto.Field( + access_config: str = proto.Field( proto.STRING, - number=517258967, + number=72856189, + ) + instance: str = proto.Field( + proto.STRING, + number=18257045, + ) + network_interface: str = proto.Field( + proto.STRING, + number=365387880, ) project: str = proto.Field( proto.STRING, @@ -30359,18 +30678,20 @@ class DeleteAutoscalerRequest(proto.Message): ) -class DeleteBackendBucketRequest(proto.Message): - r"""A request message for BackendBuckets.Delete. See the method +class DeleteAddressRequest(proto.Message): + r"""A request message for Addresses.Delete. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - backend_bucket (str): - Name of the BackendBucket resource to delete. + address (str): + Name of the address resource to delete. project (str): Project ID for this request. + region (str): + Name of the region for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -30395,14 +30716,18 @@ class DeleteBackendBucketRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - backend_bucket: str = proto.Field( + address: str = proto.Field( proto.STRING, - number=91714037, + number=462920692, ) project: str = proto.Field( proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) request_id: str = proto.Field( proto.STRING, number=37109963, @@ -30410,17 +30735,16 @@ class DeleteBackendBucketRequest(proto.Message): ) -class DeleteBackendServiceRequest(proto.Message): - r"""A request message for BackendServices.Delete. See the method +class DeleteAutoscalerRequest(proto.Message): + r"""A request message for Autoscalers.Delete. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - backend_service (str): - Name of the BackendService resource to - delete. + autoscaler (str): + Name of the autoscaler to delete. project (str): Project ID for this request. request_id (str): @@ -30445,11 +30769,13 @@ class DeleteBackendServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. + zone (str): + Name of the zone for this request. """ - backend_service: str = proto.Field( + autoscaler: str = proto.Field( proto.STRING, - number=306946058, + number=517258967, ) project: str = proto.Field( proto.STRING, @@ -30460,66 +30786,22 @@ class DeleteBackendServiceRequest(proto.Message): number=37109963, optional=True, ) - - -class DeleteCrossSiteNetworkRequest(proto.Message): - r"""A request message for CrossSiteNetworks.Delete. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - cross_site_network (str): - Name of the cross-site network to delete. - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. Specify a - unique request ID so that if you must retry your request, - the server will know to ignore the request if it has already - been completed. - - For example, consider a situation where you make an initial - request and the request times out. If you make the request - again with the same request ID, the server can check if - original operation with the same request ID was received, - and if so, will ignore the second request. This prevents - clients from accidentally creating duplicate commitments. - - The request ID must be a valid UUID with the exception that - zero UUID is not supported - (00000000-0000-0000-0000-000000000000). end_interface: - MixerMutationRequestBuilder - - This field is a member of `oneof`_ ``_request_id``. - """ - - cross_site_network: str = proto.Field( - proto.STRING, - number=108192469, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=37109963, - optional=True, + number=3744684, ) -class DeleteDiskRequest(proto.Message): - r"""A request message for Disks.Delete. See the method +class DeleteBackendBucketRequest(proto.Message): + r"""A request message for BackendBuckets.Delete. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - disk (str): - Name of the persistent disk to delete. + backend_bucket (str): + Name of the BackendBucket resource to delete. project (str): Project ID for this request. request_id (str): @@ -30544,13 +30826,11 @@ class DeleteDiskRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of the zone for this request. """ - disk: str = proto.Field( + backend_bucket: str = proto.Field( proto.STRING, - number=3083677, + number=91714037, ) project: str = proto.Field( proto.STRING, @@ -30561,22 +30841,19 @@ class DeleteDiskRequest(proto.Message): number=37109963, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class DeleteExternalVpnGatewayRequest(proto.Message): - r"""A request message for ExternalVpnGateways.Delete. See the - method description for details. +class DeleteBackendServiceRequest(proto.Message): + r"""A request message for BackendServices.Delete. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - external_vpn_gateway (str): - Name of the externalVpnGateways to delete. + backend_service (str): + Name of the BackendService resource to + delete. project (str): Project ID for this request. request_id (str): @@ -30603,9 +30880,9 @@ class DeleteExternalVpnGatewayRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - external_vpn_gateway: str = proto.Field( + backend_service: str = proto.Field( proto.STRING, - number=109898629, + number=306946058, ) project: str = proto.Field( proto.STRING, @@ -30618,43 +30895,46 @@ class DeleteExternalVpnGatewayRequest(proto.Message): ) -class DeleteFirewallPolicyRequest(proto.Message): - r"""A request message for FirewallPolicies.Delete. See the method - description for details. +class DeleteCrossSiteNetworkRequest(proto.Message): + r"""A request message for CrossSiteNetworks.Delete. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - firewall_policy (str): - Name of the firewall policy to delete. + cross_site_network (str): + Name of the cross-site network to delete. + project (str): + Project ID for this request. request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + An optional request ID to identify requests. Specify a + unique request ID so that if you must retry your request, + the server will know to ignore the request if it has already + been completed. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + For example, consider a situation where you make an initial + request and the request times out. If you make the request + again with the same request ID, the server can check if + original operation with the same request ID was received, + and if so, will ignore the second request. This prevents + clients from accidentally creating duplicate commitments. - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + The request ID must be a valid UUID with the exception that + zero UUID is not supported + (00000000-0000-0000-0000-000000000000). end_interface: + MixerMutationRequestBuilder This field is a member of `oneof`_ ``_request_id``. """ - firewall_policy: str = proto.Field( + cross_site_network: str = proto.Field( proto.STRING, - number=498173265, + number=108192469, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, ) request_id: str = proto.Field( proto.STRING, @@ -30663,16 +30943,16 @@ class DeleteFirewallPolicyRequest(proto.Message): ) -class DeleteFirewallRequest(proto.Message): - r"""A request message for Firewalls.Delete. See the method +class DeleteDiskRequest(proto.Message): + r"""A request message for Disks.Delete. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - firewall (str): - Name of the firewall rule to delete. + disk (str): + Name of the persistent disk to delete. project (str): Project ID for this request. request_id (str): @@ -30697,11 +30977,13 @@ class DeleteFirewallRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. + zone (str): + The name of the zone for this request. """ - firewall: str = proto.Field( + disk: str = proto.Field( proto.STRING, - number=511016192, + number=3083677, ) project: str = proto.Field( proto.STRING, @@ -30712,23 +30994,24 @@ class DeleteFirewallRequest(proto.Message): number=37109963, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class DeleteForwardingRuleRequest(proto.Message): - r"""A request message for ForwardingRules.Delete. See the method - description for details. +class DeleteExternalVpnGatewayRequest(proto.Message): + r"""A request message for ExternalVpnGateways.Delete. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - forwarding_rule (str): - Name of the ForwardingRule resource to - delete. + external_vpn_gateway (str): + Name of the externalVpnGateways to delete. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -30753,18 +31036,14 @@ class DeleteForwardingRuleRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - forwarding_rule: str = proto.Field( + external_vpn_gateway: str = proto.Field( proto.STRING, - number=269964030, + number=109898629, ) project: str = proto.Field( proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) request_id: str = proto.Field( proto.STRING, number=37109963, @@ -30772,19 +31051,16 @@ class DeleteForwardingRuleRequest(proto.Message): ) -class DeleteFutureReservationRequest(proto.Message): - r"""A request message for FutureReservations.Delete. See the - method description for details. +class DeleteFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.Delete. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - future_reservation (str): - Name of the future reservation to retrieve. - Name should conform to RFC1035. - project (str): - Project ID for this request. + firewall_policy (str): + Name of the firewall policy to delete. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -30807,40 +31083,29 @@ class DeleteFutureReservationRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - zone (str): - Name of the zone for this request. Name - should conform to RFC1035. """ - future_reservation: str = proto.Field( - proto.STRING, - number=56206160, - ) - project: str = proto.Field( + firewall_policy: str = proto.Field( proto.STRING, - number=227560217, + number=498173265, ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class DeleteGlobalAddressRequest(proto.Message): - r"""A request message for GlobalAddresses.Delete. See the method +class DeleteFirewallRequest(proto.Message): + r"""A request message for Firewalls.Delete. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - address (str): - Name of the address resource to delete. + firewall (str): + Name of the firewall rule to delete. project (str): Project ID for this request. request_id (str): @@ -30867,9 +31132,9 @@ class DeleteGlobalAddressRequest(proto.Message): This field is a member of `oneof`_ ``_request_id``. """ - address: str = proto.Field( + firewall: str = proto.Field( proto.STRING, - number=462920692, + number=511016192, ) project: str = proto.Field( proto.STRING, @@ -30882,9 +31147,177 @@ class DeleteGlobalAddressRequest(proto.Message): ) -class DeleteGlobalForwardingRuleRequest(proto.Message): - r"""A request message for GlobalForwardingRules.Delete. See the - method description for details. +class DeleteForwardingRuleRequest(proto.Message): + r"""A request message for ForwardingRules.Delete. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + forwarding_rule (str): + Name of the ForwardingRule resource to + delete. + project (str): + Project ID for this request. + region (str): + Name of the region scoping this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + forwarding_rule: str = proto.Field( + proto.STRING, + number=269964030, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class DeleteFutureReservationRequest(proto.Message): + r"""A request message for FutureReservations.Delete. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + future_reservation (str): + Name of the future reservation to retrieve. + Name should conform to RFC1035. + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + Name of the zone for this request. Name + should conform to RFC1035. + """ + + future_reservation: str = proto.Field( + proto.STRING, + number=56206160, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class DeleteGlobalAddressRequest(proto.Message): + r"""A request message for GlobalAddresses.Delete. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + address (str): + Name of the address resource to delete. + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + address: str = proto.Field( + proto.STRING, + number=462920692, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class DeleteGlobalForwardingRuleRequest(proto.Message): + r"""A request message for GlobalForwardingRules.Delete. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -32745,6 +33178,109 @@ class DeleteNodesNodeGroupRequest(proto.Message): ) +class DeleteOrganizationRolloutPlanRequest(proto.Message): + r"""A request message for OrganizationRolloutPlans.Delete. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + organization (str): + Organization ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout_plan (str): + Name of the OrganizationRolloutPlan resource + to delete. + """ + + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout_plan: str = proto.Field( + proto.STRING, + number=459057399, + ) + + +class DeleteOrganizationRolloutRequest(proto.Message): + r"""A request message for OrganizationRollouts.Delete. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + organization (str): + Required. Organization ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Name of the Rollout resource to delete. + """ + + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class DeleteOrganizationSecurityPolicyRequest(proto.Message): r"""A request message for OrganizationSecurityPolicies.Delete. See the method description for details. @@ -37326,6 +37862,42 @@ class Disk(proto.Message): that was used. This field is a member of `oneof`_ ``_source_instant_snapshot_id``. + source_machine_image (str): + The machine image to create the disk from. + You can provide this as a partial or full URL to + the resource. For example, the following are + valid values: + + + - + https://www.googleapis.com/compute/v1/projects/project/global/machineImages/machineImage + - + projects/project/global/machineImages/machineImage + - global/machineImages/machineImage + + This field is a member of `oneof`_ ``_source_machine_image``. + source_machine_image_disk_device_name (str): + The device name of a disk within a given machine image. The + source_machine_image must be specified. + + This field is a member of `oneof`_ ``_source_machine_image_disk_device_name``. + source_machine_image_encryption_key (google.cloud.compute_v1beta.types.CustomerEncryptionKey): + Thecustomer-supplied + encryption key of the source machine image. + Required if the source machine image is + protected by a customer-supplied encryption key. + + This field is a member of `oneof`_ ``_source_machine_image_encryption_key``. + source_machine_image_id (str): + Output only. [Output Only] The unique ID of the machine + image used to create this disk. This value identifies the + exact machine image that was used to create this persistent + disk. For example, if you created the persistent disk from a + machine image that was later deleted and recreated under the + same name, the source machine image ID would identify the + exact version of the machine image that was used. + + This field is a member of `oneof`_ ``_source_machine_image_id``. source_snapshot (str): The source snapshot used to create this disk. You can provide this as a partial or full URL to @@ -37787,6 +38359,27 @@ class StorageType(proto.Enum): number=287582708, optional=True, ) + source_machine_image: str = proto.Field( + proto.STRING, + number=21769791, + optional=True, + ) + source_machine_image_disk_device_name: str = proto.Field( + proto.STRING, + number=68623666, + optional=True, + ) + source_machine_image_encryption_key: "CustomerEncryptionKey" = proto.Field( + proto.MESSAGE, + number=192839075, + optional=True, + message="CustomerEncryptionKey", + ) + source_machine_image_id: str = proto.Field( + proto.STRING, + number=3876635, + optional=True, + ) source_snapshot: str = proto.Field( proto.STRING, number=126061928, @@ -41168,9 +41761,11 @@ class FirewallPolicyRule(proto.Message): action (str): The Action to perform when the client connection triggers the rule. Valid actions for firewall rules are: "allow", - "deny", "apply_security_profile_group" and "goto_next". - Valid actions for packet mirroring rules are: "mirror", - "do_not_mirror" and "goto_next". + "deny", "apply_security_profile_group" and "goto_next" ( + "apply_security_profile_group" can be specified only for + global network firewall policies or hierarchical firewall + policies). Valid actions for packet mirroring rules are: + "mirror", "do_not_mirror" and "goto_next". This field is a member of `oneof`_ ``_action``. description (str): @@ -41231,12 +41826,14 @@ class FirewallPolicyRule(proto.Message): This field is a member of `oneof`_ ``_rule_tuple_count``. security_profile_group (str): - A fully-qualified URL of a SecurityProfile resource + A fully-qualified URL of a SecurityProfileGroup resource instance. Example: https://networksecurity.googleapis.com/v1/projects/{project}/locations/{location}/securityProfileGroups/my-security-profile-group Must be specified if action is one of 'apply_security_profile_group' or 'mirror'. Cannot be - specified for other actions. + specified for other actions. Can be specified only for + global network firewall policies or hierarchical firewall + policies. This field is a member of `oneof`_ ``_security_profile_group``. target_forwarding_rules (MutableSequence[str]): @@ -46478,143 +47075,52 @@ class GetHealthTargetPoolRequest(proto.Message): ) -class GetIamPolicyBackendBucketRequest(proto.Message): - r"""A request message for BackendBuckets.GetIamPolicy. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class GetIamPolicyBackendServiceRequest(proto.Message): - r"""A request message for BackendServices.GetIamPolicy. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields +class GetHostRequest(proto.Message): + r"""A request message for Hosts.Get. See the method description + for details. Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. + association (str): + The parent resource association for the Host. This field + specifies the hierarchical context (e.g., reservation, + block, sub-block) when accessing the host. For example, + reservations/reservation_name, + reservations/reservation_name/reservationBlocks/reservation_block_name + or + reservations/reservation_name/reservationBlocks/reservation_block_name/reservationSubBlocks/reservation_sub_block_name. + host (str): + The name of the host, formatted as RFC1035 or + a resource ID number. project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. + The project ID for this request. + zone (str): + The name of the zone for this request, + formatted as RFC1035. """ - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( + association: str = proto.Field( proto.STRING, - number=227560217, + number=449371265, ) - resource: str = proto.Field( + host: str = proto.Field( proto.STRING, - number=195806222, - ) - - -class GetIamPolicyDiskRequest(proto.Message): - r"""A request message for Disks.GetIamPolicy. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - zone (str): - The name of the zone for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, + number=3208616, ) project: str = proto.Field( proto.STRING, number=227560217, ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) zone: str = proto.Field( proto.STRING, number=3744684, ) -class GetIamPolicyFirewallPolicyRequest(proto.Message): - r"""A request message for FirewallPolicies.GetIamPolicy. See the +class GetIamPolicyBackendBucketRequest(proto.Message): + r"""A request message for BackendBuckets.GetIamPolicy. See the method description for details. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class GetIamPolicyImageRequest(proto.Message): - r"""A request message for Images.GetIamPolicy. See the method - description for details. - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: @@ -46643,47 +47149,8 @@ class GetIamPolicyImageRequest(proto.Message): ) -class GetIamPolicyInstanceRequest(proto.Message): - r"""A request message for Instances.GetIamPolicy. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - zone (str): - The name of the zone for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - - -class GetIamPolicyInstanceTemplateRequest(proto.Message): - r"""A request message for InstanceTemplates.GetIamPolicy. See the +class GetIamPolicyBackendServiceRequest(proto.Message): + r"""A request message for BackendServices.GetIamPolicy. See the method description for details. @@ -46715,9 +47182,9 @@ class GetIamPolicyInstanceTemplateRequest(proto.Message): ) -class GetIamPolicyInstantSnapshotGroupRequest(proto.Message): - r"""A request message for InstantSnapshotGroups.GetIamPolicy. See - the method description for details. +class GetIamPolicyDiskRequest(proto.Message): + r"""A request message for Disks.GetIamPolicy. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -46754,8 +47221,8 @@ class GetIamPolicyInstantSnapshotGroupRequest(proto.Message): ) -class GetIamPolicyInstantSnapshotRequest(proto.Message): - r"""A request message for InstantSnapshots.GetIamPolicy. See the +class GetIamPolicyFirewallPolicyRequest(proto.Message): + r"""A request message for FirewallPolicies.GetIamPolicy. See the method description for details. @@ -46766,12 +47233,8 @@ class GetIamPolicyInstantSnapshotRequest(proto.Message): Requested IAM Policy version. This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. resource (str): Name or id of the resource for this request. - zone (str): - The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -46779,23 +47242,14 @@ class GetIamPolicyInstantSnapshotRequest(proto.Message): number=499220029, optional=True, ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class GetIamPolicyInterconnectAttachmentGroupRequest(proto.Message): - r"""A request message for - InterconnectAttachmentGroups.GetIamPolicy. See the method +class GetIamPolicyImageRequest(proto.Message): + r"""A request message for Images.GetIamPolicy. See the method description for details. @@ -46827,42 +47281,9 @@ class GetIamPolicyInterconnectAttachmentGroupRequest(proto.Message): ) -class GetIamPolicyInterconnectGroupRequest(proto.Message): - r"""A request message for InterconnectGroups.GetIamPolicy. See - the method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - - -class GetIamPolicyLicenseCodeRequest(proto.Message): - r"""A request message for LicenseCodes.GetIamPolicy. See the - method description for details. +class GetIamPolicyInstanceRequest(proto.Message): + r"""A request message for Instances.GetIamPolicy. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -46876,6 +47297,8 @@ class GetIamPolicyLicenseCodeRequest(proto.Message): Project ID for this request. resource (str): Name or id of the resource for this request. + zone (str): + The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -46891,43 +47314,14 @@ class GetIamPolicyLicenseCodeRequest(proto.Message): proto.STRING, number=195806222, ) - - -class GetIamPolicyLicenseRequest(proto.Message): - r"""A request message for Licenses.GetIamPolicy. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - resource: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=195806222, + number=3744684, ) -class GetIamPolicyMachineImageRequest(proto.Message): - r"""A request message for MachineImages.GetIamPolicy. See the +class GetIamPolicyInstanceTemplateRequest(proto.Message): + r"""A request message for InstanceTemplates.GetIamPolicy. See the method description for details. @@ -46959,8 +47353,8 @@ class GetIamPolicyMachineImageRequest(proto.Message): ) -class GetIamPolicyNetworkAttachmentRequest(proto.Message): - r"""A request message for NetworkAttachments.GetIamPolicy. See +class GetIamPolicyInstantSnapshotGroupRequest(proto.Message): + r"""A request message for InstantSnapshotGroups.GetIamPolicy. See the method description for details. @@ -46973,10 +47367,10 @@ class GetIamPolicyNetworkAttachmentRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. + zone (str): + The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -46988,19 +47382,19 @@ class GetIamPolicyNetworkAttachmentRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class GetIamPolicyNetworkFirewallPolicyRequest(proto.Message): - r"""A request message for NetworkFirewallPolicies.GetIamPolicy. - See the method description for details. +class GetIamPolicyInstantSnapshotRequest(proto.Message): + r"""A request message for InstantSnapshots.GetIamPolicy. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47014,6 +47408,8 @@ class GetIamPolicyNetworkFirewallPolicyRequest(proto.Message): Project ID for this request. resource (str): Name or id of the resource for this request. + zone (str): + The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -47029,10 +47425,15 @@ class GetIamPolicyNetworkFirewallPolicyRequest(proto.Message): proto.STRING, number=195806222, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class GetIamPolicyNodeGroupRequest(proto.Message): - r"""A request message for NodeGroups.GetIamPolicy. See the method +class GetIamPolicyInterconnectAttachmentGroupRequest(proto.Message): + r"""A request message for + InterconnectAttachmentGroups.GetIamPolicy. See the method description for details. @@ -47047,8 +47448,6 @@ class GetIamPolicyNodeGroupRequest(proto.Message): Project ID for this request. resource (str): Name or id of the resource for this request. - zone (str): - The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -47064,15 +47463,11 @@ class GetIamPolicyNodeGroupRequest(proto.Message): proto.STRING, number=195806222, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class GetIamPolicyNodeTemplateRequest(proto.Message): - r"""A request message for NodeTemplates.GetIamPolicy. See the - method description for details. +class GetIamPolicyInterconnectGroupRequest(proto.Message): + r"""A request message for InterconnectGroups.GetIamPolicy. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47084,8 +47479,6 @@ class GetIamPolicyNodeTemplateRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -47099,19 +47492,15 @@ class GetIamPolicyNodeTemplateRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionBackendBucketRequest(proto.Message): - r"""A request message for RegionBackendBuckets.GetIamPolicy. See - the method description for details. +class GetIamPolicyLicenseCodeRequest(proto.Message): + r"""A request message for LicenseCodes.GetIamPolicy. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47123,8 +47512,6 @@ class GetIamPolicyRegionBackendBucketRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -47138,19 +47525,15 @@ class GetIamPolicyRegionBackendBucketRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionBackendServiceRequest(proto.Message): - r"""A request message for RegionBackendServices.GetIamPolicy. See - the method description for details. +class GetIamPolicyLicenseRequest(proto.Message): + r"""A request message for Licenses.GetIamPolicy. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47162,8 +47545,6 @@ class GetIamPolicyRegionBackendServiceRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -47177,18 +47558,14 @@ class GetIamPolicyRegionBackendServiceRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionDiskRequest(proto.Message): - r"""A request message for RegionDisks.GetIamPolicy. See the +class GetIamPolicyMachineImageRequest(proto.Message): + r"""A request message for MachineImages.GetIamPolicy. See the method description for details. @@ -47201,8 +47578,6 @@ class GetIamPolicyRegionDiskRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -47216,20 +47591,15 @@ class GetIamPolicyRegionDiskRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionInstantSnapshotGroupRequest(proto.Message): - r"""A request message for - RegionInstantSnapshotGroups.GetIamPolicy. See the method - description for details. +class GetIamPolicyNetworkAttachmentRequest(proto.Message): + r"""A request message for NetworkAttachments.GetIamPolicy. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47266,8 +47636,8 @@ class GetIamPolicyRegionInstantSnapshotGroupRequest(proto.Message): ) -class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): - r"""A request message for RegionInstantSnapshots.GetIamPolicy. +class GetIamPolicyNetworkFirewallPolicyRequest(proto.Message): + r"""A request message for NetworkFirewallPolicies.GetIamPolicy. See the method description for details. @@ -47280,8 +47650,6 @@ class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. """ @@ -47295,19 +47663,14 @@ class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) -class GetIamPolicyRegionNetworkFirewallPolicyRequest(proto.Message): - r"""A request message for - RegionNetworkFirewallPolicies.GetIamPolicy. See the method +class GetIamPolicyNodeGroupRequest(proto.Message): + r"""A request message for NodeGroups.GetIamPolicy. See the method description for details. @@ -47320,10 +47683,10 @@ class GetIamPolicyRegionNetworkFirewallPolicyRequest(proto.Message): This field is a member of `oneof`_ ``_options_requested_policy_version``. project (str): Project ID for this request. - region (str): - The name of the region for this request. resource (str): Name or id of the resource for this request. + zone (str): + The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -47335,18 +47698,18 @@ class GetIamPolicyRegionNetworkFirewallPolicyRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) resource: str = proto.Field( proto.STRING, number=195806222, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class GetIamPolicyRegionSnapshotRequest(proto.Message): - r"""A request message for RegionSnapshots.GetIamPolicy. See the +class GetIamPolicyNodeTemplateRequest(proto.Message): + r"""A request message for NodeTemplates.GetIamPolicy. See the method description for details. @@ -47384,9 +47747,9 @@ class GetIamPolicyRegionSnapshotRequest(proto.Message): ) -class GetIamPolicyReservationBlockRequest(proto.Message): - r"""A request message for ReservationBlocks.GetIamPolicy. See the - method description for details. +class GetIamPolicyRegionBackendBucketRequest(proto.Message): + r"""A request message for RegionBackendBuckets.GetIamPolicy. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47396,15 +47759,12 @@ class GetIamPolicyReservationBlockRequest(proto.Message): Requested IAM Policy version. This field is a member of `oneof`_ ``_options_requested_policy_version``. - parent_resource (str): - Name or id of parent resource of the resource - for this request. project (str): Project ID for this request. + region (str): + The name of the region for this request. resource (str): Name or id of the resource for this request. - zone (str): - The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -47412,65 +47772,22 @@ class GetIamPolicyReservationBlockRequest(proto.Message): number=499220029, optional=True, ) - parent_resource: str = proto.Field( - proto.STRING, - number=18091011, - ) project: str = proto.Field( proto.STRING, number=227560217, ) - resource: str = proto.Field( - proto.STRING, - number=195806222, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - - -class GetIamPolicyReservationRequest(proto.Message): - r"""A request message for Reservations.GetIamPolicy. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - options_requested_policy_version (int): - Requested IAM Policy version. - - This field is a member of `oneof`_ ``_options_requested_policy_version``. - project (str): - Project ID for this request. - resource (str): - Name or id of the resource for this request. - zone (str): - The name of the zone for this request. - """ - - options_requested_policy_version: int = proto.Field( - proto.INT32, - number=499220029, - optional=True, - ) - project: str = proto.Field( + region: str = proto.Field( proto.STRING, - number=227560217, + number=138946292, ) resource: str = proto.Field( proto.STRING, number=195806222, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class GetIamPolicyReservationSubBlockRequest(proto.Message): - r"""A request message for ReservationSubBlocks.GetIamPolicy. See +class GetIamPolicyRegionBackendServiceRequest(proto.Message): + r"""A request message for RegionBackendServices.GetIamPolicy. See the method description for details. @@ -47481,15 +47798,12 @@ class GetIamPolicyReservationSubBlockRequest(proto.Message): Requested IAM Policy version. This field is a member of `oneof`_ ``_options_requested_policy_version``. - parent_resource (str): - Name or id of parent resource of the resource - for this request. project (str): Project ID for this request. + region (str): + The name of the region for this request. resource (str): Name or id of the resource for this request. - zone (str): - The name of the zone for this request. """ options_requested_policy_version: int = proto.Field( @@ -47497,26 +47811,22 @@ class GetIamPolicyReservationSubBlockRequest(proto.Message): number=499220029, optional=True, ) - parent_resource: str = proto.Field( - proto.STRING, - number=18091011, - ) project: str = proto.Field( proto.STRING, number=227560217, ) - resource: str = proto.Field( + region: str = proto.Field( proto.STRING, - number=195806222, + number=138946292, ) - zone: str = proto.Field( + resource: str = proto.Field( proto.STRING, - number=3744684, + number=195806222, ) -class GetIamPolicyResourcePolicyRequest(proto.Message): - r"""A request message for ResourcePolicies.GetIamPolicy. See the +class GetIamPolicyRegionDiskRequest(proto.Message): + r"""A request message for RegionDisks.GetIamPolicy. See the method description for details. @@ -47554,9 +47864,337 @@ class GetIamPolicyResourcePolicyRequest(proto.Message): ) -class GetIamPolicyServiceAttachmentRequest(proto.Message): - r"""A request message for ServiceAttachments.GetIamPolicy. See - the method description for details. +class GetIamPolicyRegionInstantSnapshotGroupRequest(proto.Message): + r"""A request message for + RegionInstantSnapshotGroups.GetIamPolicy. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionInstantSnapshotRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.GetIamPolicy. + See the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionNetworkFirewallPolicyRequest(proto.Message): + r"""A request message for + RegionNetworkFirewallPolicies.GetIamPolicy. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyRegionSnapshotRequest(proto.Message): + r"""A request message for RegionSnapshots.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyReservationBlockRequest(proto.Message): + r"""A request message for ReservationBlocks.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + parent_resource (str): + Name or id of parent resource of the resource + for this request. + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + parent_resource: str = proto.Field( + proto.STRING, + number=18091011, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class GetIamPolicyReservationRequest(proto.Message): + r"""A request message for Reservations.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class GetIamPolicyReservationSubBlockRequest(proto.Message): + r"""A request message for ReservationSubBlocks.GetIamPolicy. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + parent_resource (str): + Name or id of parent resource of the resource + for this request. + project (str): + Project ID for this request. + resource (str): + Name or id of the resource for this request. + zone (str): + The name of the zone for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + parent_resource: str = proto.Field( + proto.STRING, + number=18091011, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class GetIamPolicyResourcePolicyRequest(proto.Message): + r"""A request message for ResourcePolicies.GetIamPolicy. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + options_requested_policy_version (int): + Requested IAM Policy version. + + This field is a member of `oneof`_ ``_options_requested_policy_version``. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + resource (str): + Name or id of the resource for this request. + """ + + options_requested_policy_version: int = proto.Field( + proto.INT32, + number=499220029, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource: str = proto.Field( + proto.STRING, + number=195806222, + ) + + +class GetIamPolicyServiceAttachmentRequest(proto.Message): + r"""A request message for ServiceAttachments.GetIamPolicy. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -47785,6 +48423,34 @@ class GetImageRequest(proto.Message): ) +class GetImageViewRequest(proto.Message): + r"""A request message for ImageViews.Get. See the method + description for details. + + Attributes: + project (str): + Required. Project ID for this request. + region (str): + Required. Name of the region for this + request. + resource_id (str): + Name of the image resource to return. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + resource_id: str = proto.Field( + proto.STRING, + number=160795372, + ) + + class GetInstanceGroupManagerRequest(proto.Message): r"""A request message for InstanceGroupManagers.Get. See the method description for details. @@ -48867,6 +49533,49 @@ class GetOperationalStatusInterconnectGroupRequest(proto.Message): ) +class GetOrganizationRolloutPlanRequest(proto.Message): + r"""A request message for OrganizationRolloutPlans.Get. See the + method description for details. + + Attributes: + organization (str): + Organization ID for this request. + rollout_plan (str): + Name of the persistent rollout plan to + return. + """ + + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + rollout_plan: str = proto.Field( + proto.STRING, + number=459057399, + ) + + +class GetOrganizationRolloutRequest(proto.Message): + r"""A request message for OrganizationRollouts.Get. See the + method description for details. + + Attributes: + organization (str): + Organization ID for this request. + rollout (str): + Name of the persistent rollout to return. + """ + + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class GetOrganizationSecurityPolicyRequest(proto.Message): r"""A request message for OrganizationSecurityPolicies.Get. See the method description for details. @@ -49051,6 +49760,29 @@ class GetProjectRequest(proto.Message): ) +class GetProjectViewRequest(proto.Message): + r"""A request message for ProjectViews.Get. See the method + description for details. + + Attributes: + project (str): + Required. Project ID for this request. This + is part of the URL path. + region (str): + Required. Name of the region for this + request. This is part of the URL path. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + + class GetPublicAdvertisedPrefixeRequest(proto.Message): r"""A request message for PublicAdvertisedPrefixes.Get. See the method description for details. @@ -50108,6 +50840,28 @@ class GetRegionUrlMapRequest(proto.Message): ) +class GetReliabilityRiskRequest(proto.Message): + r"""A request message for ReliabilityRisks.Get. See the method + description for details. + + Attributes: + project (str): + Project ID for this request. + reliability_risk (str): + Name of the ReliabilityRisk resource to + return. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + reliability_risk: str = proto.Field( + proto.STRING, + number=340233140, + ) + + class GetReservationBlockRequest(proto.Message): r"""A request message for ReservationBlocks.Get. See the method description for details. @@ -51437,6 +52191,67 @@ class GetUrlMapRequest(proto.Message): ) +class GetVersionHostRequest(proto.Message): + r"""A request message for Hosts.GetVersion. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + association (str): + The parent resource association for the Host. + This field specifies the hierarchical context + (e.g., reservation, block, sub-block) when + accessing the host. + host (str): + The name of the host, formatted as RFC1035 or + a resource ID number. + hosts_get_version_request_resource (google.cloud.compute_v1beta.types.HostsGetVersionRequest): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + association: str = proto.Field( + proto.STRING, + number=449371265, + ) + host: str = proto.Field( + proto.STRING, + number=3208616, + ) + hosts_get_version_request_resource: "HostsGetVersionRequest" = proto.Field( + proto.MESSAGE, + number=273373442, + message="HostsGetVersionRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + class GetVersionOperationMetadata(proto.Message): r""" @@ -53112,6 +53927,8 @@ class Type(proto.Enum): set. BARE_METAL_LINUX_COMPATIBLE (354232740): No description available. + CCA_CAPABLE (79012270): + No description available. FEATURE_TYPE_UNSPECIFIED (531767259): No description available. GVNIC (68209305): @@ -53144,6 +53961,7 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 BARE_METAL_LINUX_COMPATIBLE = 354232740 + CCA_CAPABLE = 79012270 FEATURE_TYPE_UNSPECIFIED = 531767259 GVNIC = 68209305 IDPF = 2242641 @@ -56001,6 +56819,200 @@ class HelpLink(proto.Message): ) +class Host(proto.Message): + r"""Represents a host resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + alias_links (MutableSequence[str]): + Output only. All aliases for this resource. + e.g. + projects/123/zones/us-centra1-a/reservation/r1/reservationBlock/b1/hosts/h1 + creation_timestamp (str): + Output only. The creation timestamp, + formatted asRFC3339 text. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + An optional description of this resource. + + This field is a member of `oneof`_ ``_description``. + id (int): + Output only. The unique identifier for this + resource. This identifier is defined by the + server. + + This field is a member of `oneof`_ ``_id``. + kind (str): + Output only. The type of resource. + Alwayscompute#host for hosts. + + This field is a member of `oneof`_ ``_kind``. + name (str): + Output only. The name of the host. + + This field is a member of `oneof`_ ``_name``. + self_link (str): + Output only. The self link of the host. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + Output only. The self link with id of the + host. + + This field is a member of `oneof`_ ``_self_link_with_id``. + state (str): + Output only. The state of the host. + Check the State enum for the list of possible + values. + + This field is a member of `oneof`_ ``_state``. + status (google.cloud.compute_v1beta.types.HostStatus): + Output only. The status of the host + + This field is a member of `oneof`_ ``_status``. + zone (str): + Output only. The zone in which the host + resides. + + This field is a member of `oneof`_ ``_zone``. + """ + + class State(proto.Enum): + r"""Output only. The state of the host. + + Values: + UNDEFINED_STATE (0): + A value indicating that the enum field is not + set. + ACTIVE (314733318): + The host has allocated all its resources. + CREATING (455564985): + The resources are being allocated for the + host. + DELETING (528602024): + The host is currently being deleted. + STATE_UNSPECIFIED (470755401): + No description available. + UNAVAILABLE (413756464): + The host is currently unavailable. + """ + + UNDEFINED_STATE = 0 + ACTIVE = 314733318 + CREATING = 455564985 + DELETING = 528602024 + STATE_UNSPECIFIED = 470755401 + UNAVAILABLE = 413756464 + + alias_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=296963338, + ) + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + 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, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + state: str = proto.Field( + proto.STRING, + number=109757585, + optional=True, + ) + status: "HostStatus" = proto.Field( + proto.MESSAGE, + number=181260274, + optional=True, + message="HostStatus", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + optional=True, + ) + + +class HostPhysicalTopology(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + block (str): + The unique identifier of the capacity block + within the cluster. + + This field is a member of `oneof`_ ``_block``. + cluster (str): + The cluster name of the reservation + sub-block. + + This field is a member of `oneof`_ ``_cluster``. + host (str): + The unique identifier of the capacity host + within the capacity sub-block. + + This field is a member of `oneof`_ ``_host``. + sub_block (str): + The unique identifier of the capacity + sub-block within the capacity block. + + This field is a member of `oneof`_ ``_sub_block``. + """ + + block: str = proto.Field( + proto.STRING, + number=93832333, + optional=True, + ) + cluster: str = proto.Field( + proto.STRING, + number=335221242, + optional=True, + ) + host: str = proto.Field( + proto.STRING, + number=3208616, + optional=True, + ) + sub_block: str = proto.Field( + proto.STRING, + number=478033358, + optional=True, + ) + + class HostRule(proto.Message): r"""UrlMaps A host-matching rule for a URL. If matched, will use the @@ -56051,6 +57063,161 @@ class HostRule(proto.Message): ) +class HostStatus(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + physical_topology (google.cloud.compute_v1beta.types.HostPhysicalTopology): + Output only. The physical topology of the + reservation sub-block, if present + + This field is a member of `oneof`_ ``_physical_topology``. + running_instances (MutableSequence[str]): + Output only. The URIs of the instances + currently running on this host. + """ + + physical_topology: "HostPhysicalTopology" = proto.Field( + proto.MESSAGE, + number=279778519, + optional=True, + message="HostPhysicalTopology", + ) + running_instances: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=536292350, + ) + + +class HostsGetVersionRequest(proto.Message): + r""" + + Attributes: + sbom_selections (MutableSequence[str]): + The SBOM selection to return. Duplicate + values in the list will be ignored. Check the + SbomSelections enum for the list of possible + values. + """ + + class SbomSelections(proto.Enum): + r""" + + Values: + UNDEFINED_SBOM_SELECTIONS (0): + A value indicating that the enum field is not + set. + SBOM_SELECTION_CURRENT (423856692): + No description available. + SBOM_SELECTION_TARGET (152837462): + No description available. + SBOM_SELECTION_UNSPECIFIED (379615858): + No description available. + """ + + UNDEFINED_SBOM_SELECTIONS = 0 + SBOM_SELECTION_CURRENT = 423856692 + SBOM_SELECTION_TARGET = 152837462 + SBOM_SELECTION_UNSPECIFIED = 379615858 + + sbom_selections: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=69155705, + ) + + +class HostsListResponse(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + The unique identifier for the resource; + defined by the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1beta.types.Host]): + A list of host resources. + kind (str): + The type of resource. Always compute#host for + a list of hosts. + + 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): + The server-defined URL for this resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + Unreachable resources. end_interface: + MixerListResponseWithEtagBuilder + warning (google.cloud.compute_v1beta.types.Warning): + An informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["Host"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="Host", + ) + 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, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class HttpFaultAbort(proto.Message): r"""Specification for how requests are aborted as part of fault injection. @@ -56829,6 +57996,14 @@ class HttpRouteAction(proto.Message): management features. This field is a member of `oneof`_ ``_fault_injection_policy``. + image_optimization_policy (google.cloud.compute_v1beta.types.ImageOptimizationPolicy): + Image optimization policy for this URL Map's route. + Available only for Global EXTERNAL_MANAGED load balancer + schemes. Either Cloud CDN must be enabled on the backend + service or backend bucket serving the route, or cache policy + must be configured on the same route + + This field is a member of `oneof`_ ``_image_optimization_policy``. max_stream_duration (google.cloud.compute_v1beta.types.Duration): Specifies the maximum duration (timeout) for streams on the selected route. Unlike the timeout field where the timeout @@ -56927,6 +58102,12 @@ class HttpRouteAction(proto.Message): optional=True, message="HttpFaultInjection", ) + image_optimization_policy: "ImageOptimizationPolicy" = proto.Field( + proto.MESSAGE, + number=86640480, + optional=True, + message="ImageOptimizationPolicy", + ) max_stream_duration: "Duration" = proto.Field( proto.MESSAGE, number=61428376, @@ -58056,6 +59237,60 @@ def raw_page(self): ) +class ImageOptimizationPolicy(proto.Message): + r"""The configuration for Cloud CDN's image optimization feature. + This feature dynamically processes and delivers images from the + network edge. Image Optimization is only available for Global + External Application Load Balancers. + Either Cloud CDN must be enabled on the backend service or + backend bucket serving the route, or cache policy must be + configured on the same route. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + query_parameter_interpretation (str): + Specifies whether to interpret query + parameters for image optimization. Check the + QueryParameterInterpretation enum for the list + of possible values. + + This field is a member of `oneof`_ ``_query_parameter_interpretation``. + """ + + class QueryParameterInterpretation(proto.Enum): + r"""Specifies whether to interpret query parameters for image + optimization. + + Values: + UNDEFINED_QUERY_PARAMETER_INTERPRETATION (0): + A value indicating that the enum field is not + set. + DISABLED (516696700): + Query parameters for image optimization are + ignored. + ENABLED (182130465): + Query parameters for image optimization are + interpreted. + QUERY_PARAMETER_INTERPRETATION_UNSPECIFIED (417522445): + Default value. This field value translates to + the default behavior, which is to ignore query + parameters for image optimization. + """ + + UNDEFINED_QUERY_PARAMETER_INTERPRETATION = 0 + DISABLED = 516696700 + ENABLED = 182130465 + QUERY_PARAMETER_INTERPRETATION_UNSPECIFIED = 417522445 + + query_parameter_interpretation: str = proto.Field( + proto.STRING, + number=298574069, + optional=True, + ) + + class ImageParams(proto.Message): r"""Additional image params. @@ -58078,6 +59313,25 @@ class ImageParams(proto.Message): ) +class ImageView(proto.Message): + r"""Represents a read-only view of a global Image resource. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + image (google.cloud.compute_v1beta.types.Image): + + This field is a member of `oneof`_ ``_image``. + """ + + image: "Image" = proto.Field( + proto.MESSAGE, + number=100313435, + optional=True, + message="Image", + ) + + class InitialStateConfig(proto.Message): r"""Initial State for shielded instance, these are public keys which are safe to store in public @@ -60005,16 +61259,307 @@ class InsertNetworkEdgeSecurityServiceRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - validate_only (bool): - If true, the request will not be committed. - - This field is a member of `oneof`_ ``_validate_only``. + validate_only (bool): + If true, the request will not be committed. + + This field is a member of `oneof`_ ``_validate_only``. + """ + + network_edge_security_service_resource: "NetworkEdgeSecurityService" = proto.Field( + proto.MESSAGE, + number=477548966, + message="NetworkEdgeSecurityService", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=242744629, + optional=True, + ) + + +class InsertNetworkEndpointGroupRequest(proto.Message): + r"""A request message for NetworkEndpointGroups.Insert. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_endpoint_group_resource (google.cloud.compute_v1beta.types.NetworkEndpointGroup): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + The name of the zone where + you want to create the network endpoint group. + It should comply with RFC1035. + """ + + network_endpoint_group_resource: "NetworkEndpointGroup" = proto.Field( + proto.MESSAGE, + number=525788839, + message="NetworkEndpointGroup", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class InsertNetworkFirewallPolicyRequest(proto.Message): + r"""A request message for NetworkFirewallPolicies.Insert. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + firewall_policy_resource (google.cloud.compute_v1beta.types.FirewallPolicy): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + firewall_policy_resource: "FirewallPolicy" = proto.Field( + proto.MESSAGE, + number=495049532, + message="FirewallPolicy", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class InsertNetworkRequest(proto.Message): + r"""A request message for Networks.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + network_resource (google.cloud.compute_v1beta.types.Network): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + network_resource: "Network" = proto.Field( + proto.MESSAGE, + number=122105599, + message="Network", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class InsertNodeGroupRequest(proto.Message): + r"""A request message for NodeGroups.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + initial_node_count (int): + Initial count of nodes in the node group. + node_group_resource (google.cloud.compute_v1beta.types.NodeGroup): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + zone (str): + The name of the zone for this request. + """ + + initial_node_count: int = proto.Field( + proto.INT32, + number=71951469, + ) + node_group_resource: "NodeGroup" = proto.Field( + proto.MESSAGE, + number=505321899, + message="NodeGroup", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class InsertNodeTemplateRequest(proto.Message): + r"""A request message for NodeTemplates.Insert. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + node_template_resource (google.cloud.compute_v1beta.types.NodeTemplate): + The body resource for this request + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. """ - network_edge_security_service_resource: "NetworkEdgeSecurityService" = proto.Field( + node_template_resource: "NodeTemplate" = proto.Field( proto.MESSAGE, - number=477548966, - message="NetworkEdgeSecurityService", + number=127364406, + message="NodeTemplate", ) project: str = proto.Field( proto.STRING, @@ -60029,137 +61574,18 @@ class InsertNetworkEdgeSecurityServiceRequest(proto.Message): number=37109963, optional=True, ) - validate_only: bool = proto.Field( - proto.BOOL, - number=242744629, - optional=True, - ) - - -class InsertNetworkEndpointGroupRequest(proto.Message): - r"""A request message for NetworkEndpointGroups.Insert. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - network_endpoint_group_resource (google.cloud.compute_v1beta.types.NetworkEndpointGroup): - The body resource for this request - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of the zone where - you want to create the network endpoint group. - It should comply with RFC1035. - """ - network_endpoint_group_resource: "NetworkEndpointGroup" = proto.Field( - proto.MESSAGE, - number=525788839, - message="NetworkEndpointGroup", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - - -class InsertNetworkFirewallPolicyRequest(proto.Message): - r"""A request message for NetworkFirewallPolicies.Insert. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - firewall_policy_resource (google.cloud.compute_v1beta.types.FirewallPolicy): - The body resource for this request - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - """ - - firewall_policy_resource: "FirewallPolicy" = proto.Field( - proto.MESSAGE, - number=495049532, - message="FirewallPolicy", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - - -class InsertNetworkRequest(proto.Message): - r"""A request message for Networks.Insert. See the method - description for details. +class InsertOrganizationRolloutPlanRequest(proto.Message): + r"""A request message for OrganizationRolloutPlans.Insert. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - network_resource (google.cloud.compute_v1beta.types.Network): - The body resource for this request - project (str): - Project ID for this request. + organization (str): + Organization ID for this request. request_id (str): An optional request ID to identify requests. Specify a unique request ID so that if you must @@ -60182,143 +61608,23 @@ class InsertNetworkRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - """ - - network_resource: "Network" = proto.Field( - proto.MESSAGE, - number=122105599, - message="Network", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - - -class InsertNodeGroupRequest(proto.Message): - r"""A request message for NodeGroups.Insert. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - initial_node_count (int): - Initial count of nodes in the node group. - node_group_resource (google.cloud.compute_v1beta.types.NodeGroup): + rollout_plan_resource (google.cloud.compute_v1beta.types.RolloutPlan): The body resource for this request - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of the zone for this request. """ - initial_node_count: int = proto.Field( - proto.INT32, - number=71951469, - ) - node_group_resource: "NodeGroup" = proto.Field( - proto.MESSAGE, - number=505321899, - message="NodeGroup", - ) - project: str = proto.Field( + organization: str = proto.Field( proto.STRING, - number=227560217, + number=105180467, ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - - -class InsertNodeTemplateRequest(proto.Message): - r"""A request message for NodeTemplates.Insert. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - node_template_resource (google.cloud.compute_v1beta.types.NodeTemplate): - The body resource for this request - project (str): - Project ID for this request. - region (str): - The name of the region for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - """ - - node_template_resource: "NodeTemplate" = proto.Field( + rollout_plan_resource: "RolloutPlan" = proto.Field( proto.MESSAGE, - number=127364406, - message="NodeTemplate", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, + number=38629974, + message="RolloutPlan", ) @@ -63796,6 +65102,13 @@ class Instance(proto.Message): inRFC3339 text format. This field is a member of `oneof`_ ``_last_suspended_timestamp``. + local_ssd_encryption_mode (str): + Specifies which method should be used for + encrypting the Local SSDs attached to the VM. + Check the LocalSsdEncryptionMode enum for the + list of possible values. + + This field is a member of `oneof`_ ``_local_ssd_encryption_mode``. machine_type (str): Full or partial URL of the machine type resource to use for this instance, in the @@ -64012,6 +65325,34 @@ class KeyRevocationActionType(proto.Enum): NONE = 2402104 STOP = 2555906 + class LocalSsdEncryptionMode(proto.Enum): + r"""Specifies which method should be used for encrypting the + Local SSDs attached to the VM. + + Values: + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE (0): + A value indicating that the enum field is not + set. + EPHEMERAL_KEY_ENCRYPTION (413047941): + The given VM will opt-in for using ephemeral + key for encryption of Local SSDs. + The Local SSDs will not be able to recover data + in case of VM crash. + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED (454655720): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + STANDARD_ENCRYPTION (269392453): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + """ + + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE = 0 + EPHEMERAL_KEY_ENCRYPTION = 413047941 + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED = 454655720 + STANDARD_ENCRYPTION = 269392453 + class PostKeyRevocationActionType(proto.Enum): r"""PostKeyRevocationActionType of the instance. @@ -64235,6 +65576,11 @@ class Status(proto.Enum): number=356275337, optional=True, ) + local_ssd_encryption_mode: str = proto.Field( + proto.STRING, + number=121582032, + optional=True, + ) machine_type: str = proto.Field( proto.STRING, number=227711026, @@ -65565,6 +66911,12 @@ class InstanceGroupManagerActionsSummary(proto.Message): restarted or are currently being restarted. This field is a member of `oneof`_ ``_restarting``. + restarting_in_place (int): + Output only. The number of instances in the + managed instance group that are scheduled to be + restarted or are currently being restarted. + + This field is a member of `oneof`_ ``_restarting_in_place``. resuming (int): Output only. The number of instances in the managed instance group that are scheduled to be @@ -65643,6 +66995,11 @@ class InstanceGroupManagerActionsSummary(proto.Message): number=372312947, optional=True, ) + restarting_in_place: int = proto.Field( + proto.INT32, + number=435187897, + optional=True, + ) resuming: int = proto.Field( proto.INT32, number=201100714, @@ -65957,10 +67314,15 @@ class InstanceGroupManagerInstanceLifecyclePolicy(proto.Message): The action that a MIG performs on a failed VM. If the value of the onFailedHealthCheck field is ``DEFAULT_ACTION``, then the same action also applies to the VMs on which your - application fails a health check. Valid values are - REPAIR - (default): MIG automatically repairs a failed VM by - recreating it. For more information, seeAbout repairing VMs - in a MIG. - DO_NOTHING: MIG does not repair a failed VM. + application fails a health check. Valid values are + + :: + + - REPAIR (default): MIG automatically repairs a failed VM + by recreating it. For more information, see About + repairing VMs in a MIG. + - DO_NOTHING: MIG does not repair a failed VM. + Check the DefaultActionOnFailure enum for the list of possible values. @@ -66014,10 +67376,16 @@ class DefaultActionOnFailure(proto.Enum): r"""The action that a MIG performs on a failed VM. If the value of the onFailedHealthCheck field is ``DEFAULT_ACTION``, then the same action also applies to the VMs on which your application fails a - health check. Valid values are - REPAIR (default): MIG automatically - repairs a failed VM by recreating it. For more information, seeAbout - repairing VMs in a MIG. - DO_NOTHING: MIG does not repair a failed - VM. Additional supported values which may be not listed in the enum + health check. Valid values are + + :: + + - REPAIR (default): MIG automatically repairs a failed VM + by recreating it. For more information, see About + repairing VMs in a MIG. + - DO_NOTHING: MIG does not repair a failed VM. + + Additional supported values which may be not listed in the enum directly due to technical reasons: DO_NOTHING REPAIR Values: @@ -67362,6 +68730,10 @@ class InstanceGroupManagerUpdatePolicy(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + allowed_actions (MutableSequence[str]): + Actions that are allowed to update instances + within MIG. Check the AllowedActions enum for + the list of possible values. instance_redistribution_type (str): The instance redistribution policy for regional @@ -67488,6 +68860,19 @@ class InstanceGroupManagerUpdatePolicy(proto.Message): This field is a member of `oneof`_ ``_type``. """ + class AllowedActions(proto.Enum): + r"""Additional supported values which may be not listed in the enum + directly due to technical reasons: NONE REFRESH REPLACE RESTART + RESTART_IN_PLACE + + Values: + UNDEFINED_ALLOWED_ACTIONS (0): + A value indicating that the enum field is not + set. + """ + + UNDEFINED_ALLOWED_ACTIONS = 0 + class InstanceRedistributionType(proto.Enum): r"""The instance redistribution policy for regional managed instance @@ -67516,24 +68901,20 @@ class MinimalAction(proto.Enum): minimize disruption as much as possible or to apply a more disruptive action than is necessary. - - To limit disruption as much as possible, set the minimal - action toREFRESH. If your update requires a more disruptive - action, Compute Engine performs the necessary action to - execute the update. - - To apply a more disruptive action than is strictly - necessary, set the minimal action to RESTART or REPLACE. - For - example, Compute Engine does not need to restart a VM to - change its metadata. But if your application reads instance - metadata only when a VM is restarted, you can set the minimal - action to RESTART in order to pick up metadata changes. - Additional supported values which may be not listed in the enum - directly due to technical reasons: + :: - NONE - REFRESH - REPLACE - RESTART + - To limit disruption as much as possible, set the minimal action toREFRESH. If your update requires a more disruptive action, + Compute Engine performs the necessary action to execute the update. + - To apply a more disruptive action than is strictly necessary, set the + minimal action to RESTART or REPLACE. For + example, Compute Engine does not need to restart a VM to change its + metadata. But if your application reads instance metadata only when a VM + is restarted, you can set the minimal action to RESTART in + order to pick up metadata changes. + + Additional supported values which may be not listed in the enum + directly due to technical reasons: NONE REFRESH REPLACE RESTART + RESTART_IN_PLACE Values: UNDEFINED_MINIMAL_ACTION (0): @@ -67544,22 +68925,16 @@ class MinimalAction(proto.Enum): UNDEFINED_MINIMAL_ACTION = 0 class MostDisruptiveAllowedAction(proto.Enum): - r"""Most disruptive action that is allowed to be taken on an - instance. You can specify either NONE to forbid any - actions,REFRESH to avoid restarting the VM and to limit - disruption as much as possible. RESTART to allow actions that - can be applied without instance replacing or REPLACE to allow - all possible actions. If the Updater determines that the minimal - update action needed is more disruptive than most disruptive - allowed action you specify it will not perform the update at - all. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - NONE - REFRESH - REPLACE - RESTART + r"""Most disruptive action that is allowed to be taken on an instance. + You can specify either NONE to forbid any actions,REFRESH to avoid + restarting the VM and to limit disruption as much as possible. + RESTART to allow actions that can be applied without instance + replacing or REPLACE to allow all possible actions. If the Updater + determines that the minimal update action needed is more disruptive + than most disruptive allowed action you specify it will not perform + the update at all. Additional supported values which may be not + listed in the enum directly due to technical reasons: NONE REFRESH + REPLACE RESTART RESTART_IN_PLACE Values: UNDEFINED_MOST_DISRUPTIVE_ALLOWED_ACTION (0): @@ -67613,6 +68988,10 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 OPPORTUNISTIC = 429530089 + allowed_actions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=341166438, + ) instance_redistribution_type: str = proto.Field( proto.STRING, number=292630424, @@ -67750,6 +69129,10 @@ class InstanceGroupManagersApplyUpdatesRequest(proto.Message): specified in the request. This field is a member of `oneof`_ ``_all_instances``. + allowed_actions (MutableSequence[str]): + Actions that are allowed to update instances + within MIG. Check the AllowedActions enum for + the list of possible values. instances (MutableSequence[str]): The list of URLs of one or more instances for which you want to apply updates. Each URL can be a full URL or a partial @@ -67800,13 +69183,27 @@ class InstanceGroupManagersApplyUpdatesRequest(proto.Message): This field is a member of `oneof`_ ``_most_disruptive_allowed_action``. """ + class AllowedActions(proto.Enum): + r"""Additional supported values which may be not listed in the enum + directly due to technical reasons: NONE REFRESH REPLACE RESTART + RESTART_IN_PLACE + + Values: + UNDEFINED_ALLOWED_ACTIONS (0): + A value indicating that the enum field is not + set. + """ + + UNDEFINED_ALLOWED_ACTIONS = 0 + class MinimalAction(proto.Enum): - r"""The minimal action that you want to perform on each instance - during the update: + r"""The minimal action that you want to perform on each instance during + the update: + :: - REPLACE: At minimum, delete the instance and create it - again. + again. - RESTART: Stop the instance and start it again. - REFRESH: Do not stop the instance and limit @@ -67814,16 +69211,11 @@ class MinimalAction(proto.Enum): - NONE: Do not disrupt the instance at all. - By default, the minimum action is NONE. If your update requires - a more disruptive action than you set with this flag, the - necessary action is performed to execute the update. Additional - supported values which may be not listed in the enum directly - due to technical reasons: - - NONE - REFRESH - REPLACE - RESTART + By default, the minimum action is NONE. If your update requires a + more disruptive action than you set with this flag, the necessary + action is performed to execute the update. Additional supported + values which may be not listed in the enum directly due to technical + reasons: NONE REFRESH REPLACE RESTART RESTART_IN_PLACE Values: UNDEFINED_MINIMAL_ACTION (0): @@ -67834,27 +69226,23 @@ class MinimalAction(proto.Enum): UNDEFINED_MINIMAL_ACTION = 0 class MostDisruptiveAllowedAction(proto.Enum): - r"""The most disruptive action that you want to perform on each - instance during the update: + r"""The most disruptive action that you want to perform on each instance + during the update: + :: - REPLACE: Delete the instance and create it again. - RESTART: Stop the instance and start it again. - REFRESH: Do not stop the instance and limit disruption - as much as possible. + as much as possible. - NONE: Do not disrupt the instance at all. - By default, the most disruptive allowed action is REPLACE. If - your update requires a more disruptive action than you set with - this flag, the update request will fail. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - NONE - REFRESH - REPLACE - RESTART + By default, the most disruptive allowed action is REPLACE. If your + update requires a more disruptive action than you set with this + flag, the update request will fail. Additional supported values + which may be not listed in the enum directly due to technical + reasons: NONE REFRESH REPLACE RESTART RESTART_IN_PLACE Values: UNDEFINED_MOST_DISRUPTIVE_ALLOWED_ACTION (0): @@ -67869,6 +69257,10 @@ class MostDisruptiveAllowedAction(proto.Enum): number=403676512, optional=True, ) + allowed_actions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=341166438, + ) instances: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=29097598, @@ -69087,17 +70479,18 @@ class InstanceManagedByIgmError(proto.Message): Attributes: error (google.cloud.compute_v1beta.types.InstanceManagedByIgmErrorManagedInstanceError): - Output only. [Output Only] Contents of the error. + Output only. Contents of the error. This field is a member of `oneof`_ ``_error``. instance_action_details (google.cloud.compute_v1beta.types.InstanceManagedByIgmErrorInstanceActionDetails): - Output only. [Output Only] Details of the instance action - that triggered this error. May be null, if the error was not - caused by an action on an instance. This field is optional. + Output only. Details of the instance action + that triggered this error. May be null, if the + error was not caused by an action on an + instance. This field is optional. This field is a member of `oneof`_ ``_instance_action_details``. timestamp (str): - Output only. [Output Only] The time that this error + Output only. The time that this error occurred. This value is in RFC3339 text format. This field is a member of `oneof`_ ``_timestamp``. @@ -69131,30 +70524,34 @@ class InstanceManagedByIgmErrorInstanceActionDetails(proto.Message): Attributes: action (str): - Output only. [Output Only] Action that managed instance - group was executing on the instance when the error occurred. - Possible values: Check the Action enum for the list of - possible values. + Output only. Action that managed instance + group was executing on the instance when the + error occurred. Possible values: + + Check the Action enum for the list of possible + values. This field is a member of `oneof`_ ``_action``. instance (str): - Output only. [Output Only] The URL of the instance. The URL - can be set even if the instance has not yet been created. + Output only. The URL of the instance. The URL + can be set even if the instance has not yet been + created. This field is a member of `oneof`_ ``_instance``. version (google.cloud.compute_v1beta.types.ManagedInstanceVersion): - Output only. [Output Only] Version this instance was created - from, or was being created from, but the creation failed. - Corresponds to one of the versions that were set on the - Instance Group Manager resource at the time this instance - was being created. + Output only. Version this instance was + created from, or was being created from, but the + creation failed. Corresponds to one of the + versions that were set on the Instance Group + Manager resource at the time this instance was + being created. This field is a member of `oneof`_ ``_version``. """ class Action(proto.Enum): - r"""Output only. [Output Only] Action that managed instance group was - executing on the instance when the error occurred. Possible values: + r"""Output only. Action that managed instance group was executing + on the instance when the error occurred. Possible values: Values: UNDEFINED_ACTION (0): @@ -69197,6 +70594,10 @@ class Action(proto.Enum): RESTARTING (320534387): The managed instance group is restarting this instance. + RESTARTING_IN_PLACE (212928665): + The managed instance group is restarting this + instance while preserving its capacity and local + SSDs. RESUMING (446856618): The managed instance group is resuming this instance. @@ -69235,6 +70636,7 @@ class Action(proto.Enum): RECREATING = 287278572 REFRESHING = 163266343 RESTARTING = 320534387 + RESTARTING_IN_PLACE = 212928665 RESUMING = 446856618 STARTING = 488820800 STOPPING = 350791796 @@ -69266,11 +70668,11 @@ class InstanceManagedByIgmErrorManagedInstanceError(proto.Message): Attributes: code (str): - Output only. [Output Only] Error code. + Output only. Error code. This field is a member of `oneof`_ ``_code``. message (str): - Output only. [Output Only] Error message. + Output only. Error message. This field is a member of `oneof`_ ``_message``. """ @@ -69429,6 +70831,13 @@ class InstanceProperties(proto.Message): labels (MutableMapping[str, str]): Labels to apply to instances that are created from these properties. + local_ssd_encryption_mode (str): + Specifies which method should be used for + encrypting the Local SSDs attached to the VM. + Check the LocalSsdEncryptionMode enum for the + list of possible values. + + This field is a member of `oneof`_ ``_local_ssd_encryption_mode``. machine_type (str): The machine type to use for instances that are created from these properties. This field only accepts a machine type @@ -69563,6 +70972,34 @@ class KeyRevocationActionType(proto.Enum): NONE = 2402104 STOP = 2555906 + class LocalSsdEncryptionMode(proto.Enum): + r"""Specifies which method should be used for encrypting the + Local SSDs attached to the VM. + + Values: + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE (0): + A value indicating that the enum field is not + set. + EPHEMERAL_KEY_ENCRYPTION (413047941): + The given VM will opt-in for using ephemeral + key for encryption of Local SSDs. + The Local SSDs will not be able to recover data + in case of VM crash. + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED (454655720): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + STANDARD_ENCRYPTION (269392453): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + """ + + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE = 0 + EPHEMERAL_KEY_ENCRYPTION = 413047941 + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED = 454655720 + STANDARD_ENCRYPTION = 269392453 + class PostKeyRevocationActionType(proto.Enum): r"""PostKeyRevocationActionType of the instance. @@ -69663,6 +71100,11 @@ class PrivateIpv6GoogleAccess(proto.Enum): proto.STRING, number=500195327, ) + local_ssd_encryption_mode: str = proto.Field( + proto.STRING, + number=121582032, + optional=True, + ) machine_type: str = proto.Field( proto.STRING, number=227711026, @@ -71847,6 +73289,13 @@ class Interconnect(proto.Message): resource. This field is a member of `oneof`_ ``_description``. + effective_location (str): + Output only. URL of the InterconnectLocation + object that represents where this connection is + to be provisioned. By default it will be the + same as the location field. + + This field is a member of `oneof`_ ``_effective_location``. expected_outages (MutableSequence[google.cloud.compute_v1beta.types.InterconnectOutageNotification]): Output only. [Output Only] A list of outages expected for this Interconnect. @@ -72288,6 +73737,11 @@ class Subzone(proto.Enum): number=422937596, optional=True, ) + effective_location: str = proto.Field( + proto.STRING, + number=302355277, + optional=True, + ) expected_outages: MutableSequence["InterconnectOutageNotification"] = ( proto.RepeatedField( proto.MESSAGE, @@ -82490,15 +83944,172 @@ class ListFutureReservationsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class ListGlobalAddressesRequest(proto.Message): + r"""A request message for GlobalAddresses.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``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) -class ListGlobalAddressesRequest(proto.Message): - r"""A request message for GlobalAddresses.List. See the method - description for details. +class ListGlobalForwardingRulesRequest(proto.Message): + r"""A request message for GlobalForwardingRules.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -82653,9 +84264,9 @@ class ListGlobalAddressesRequest(proto.Message): ) -class ListGlobalForwardingRulesRequest(proto.Message): - r"""A request message for GlobalForwardingRules.List. See the - method description for details. +class ListGlobalNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for GlobalNetworkEndpointGroups.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -82810,9 +84421,9 @@ class ListGlobalForwardingRulesRequest(proto.Message): ) -class ListGlobalNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for GlobalNetworkEndpointGroups.List. See - the method description for details. +class ListGlobalOperationsRequest(proto.Message): + r"""A request message for GlobalOperations.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -82967,9 +84578,9 @@ class ListGlobalNetworkEndpointGroupsRequest(proto.Message): ) -class ListGlobalOperationsRequest(proto.Message): - r"""A request message for GlobalOperations.List. See the method - description for details. +class ListGlobalOrganizationOperationsRequest(proto.Message): + r"""A request message for GlobalOrganizationOperations.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -83078,8 +84689,10 @@ class ListGlobalOperationsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. + parent_id (str): + Parent ID for this request. + + This field is a member of `oneof`_ ``_parent_id``. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -83113,9 +84726,10 @@ class ListGlobalOperationsRequest(proto.Message): number=19994697, optional=True, ) - project: str = proto.Field( + parent_id: str = proto.Field( proto.STRING, - number=227560217, + number=459714768, + optional=True, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -83124,8 +84738,8 @@ class ListGlobalOperationsRequest(proto.Message): ) -class ListGlobalOrganizationOperationsRequest(proto.Message): - r"""A request message for GlobalOrganizationOperations.List. See +class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for GlobalPublicDelegatedPrefixes.List. See the method description for details. @@ -83235,10 +84849,8 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_id (str): - Parent ID for this request. - - This field is a member of `oneof`_ ``_parent_id``. + project (str): + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -83272,10 +84884,9 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): number=19994697, optional=True, ) - parent_id: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=459714768, - optional=True, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -83284,9 +84895,9 @@ class ListGlobalOrganizationOperationsRequest(proto.Message): ) -class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for GlobalPublicDelegatedPrefixes.List. See - the method description for details. +class ListGlobalVmExtensionPoliciesRequest(proto.Message): + r"""A request message for GlobalVmExtensionPolicies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -83441,9 +85052,9 @@ class ListGlobalPublicDelegatedPrefixesRequest(proto.Message): ) -class ListGlobalVmExtensionPoliciesRequest(proto.Message): - r"""A request message for GlobalVmExtensionPolicies.List. See the - method description for details. +class ListHealthChecksRequest(proto.Message): + r"""A request message for HealthChecks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -83598,14 +85209,22 @@ class ListGlobalVmExtensionPoliciesRequest(proto.Message): ) -class ListHealthChecksRequest(proto.Message): - r"""A request message for HealthChecks.List. See the method - description for details. +class ListHostsRequest(proto.Message): + r"""A request message for Hosts.List. See the method description + for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + association (str): + The parent resource association for the Host. This field + specifies the hierarchical context (e.g., reservation, + block, sub-block) when accessing the host. For example, + reservations/reservation_name, + reservations/reservation_name/reservationBlocks/reservation_block_name + or + reservations/reservation_name/reservationBlocks/reservation_block_name/reservationSubBlocks/reservation_sub_block_name. filter (str): A filter expression that filters resources listed in the response. Most Compute resources support two types of filter @@ -83710,7 +85329,7 @@ class ListHealthChecksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): - Project ID for this request. + The project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -83722,8 +85341,15 @@ class ListHealthChecksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request, + formatted as RFC1035. """ + association: str = proto.Field( + proto.STRING, + number=449371265, + ) filter: str = proto.Field( proto.STRING, number=336120696, @@ -83753,6 +85379,10 @@ class ListHealthChecksRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) class ListImagesRequest(proto.Message): @@ -88139,10 +89769,190 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone where - the network endpoint group is located. It should - comply with RFC1035. + zone (str): + The name of the zone where + the network endpoint group is located. It should + comply with RFC1035. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + network_endpoint_group: str = proto.Field( + proto.STRING, + number=433907078, + ) + network_endpoint_groups_list_endpoints_request_resource: "NetworkEndpointGroupsListEndpointsRequest" = proto.Field( + proto.MESSAGE, + number=59493390, + message="NetworkEndpointGroupsListEndpointsRequest", + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for + RegionNetworkEndpointGroups.ListNetworkEndpoints. 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``. + network_endpoint_group (str): + The name of the network endpoint group from + which you want to generate a list of included + network endpoints. It should comply with + RFC1035. + 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): + The name of theregion + where the network endpoint group is located. It + should comply with 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( @@ -88159,11 +89969,6 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=433907078, ) - network_endpoint_groups_list_endpoints_request_resource: "NetworkEndpointGroupsListEndpointsRequest" = proto.Field( - proto.MESSAGE, - number=59493390, - message="NetworkEndpointGroupsListEndpointsRequest", - ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -88178,21 +89983,20 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for - RegionNetworkEndpointGroups.ListNetworkEndpoints. See the method - description for details. +class ListNetworkFirewallPoliciesRequest(proto.Message): + r"""A request message for NetworkFirewallPolicies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -88278,11 +90082,6 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. - network_endpoint_group (str): - The name of the network endpoint group from - which you want to generate a list of included - network endpoints. It should comply with - RFC1035. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -88308,10 +90107,6 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - The name of theregion - where the network endpoint group is located. It - should comply with RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88335,10 +90130,6 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): number=54715419, optional=True, ) - network_endpoint_group: str = proto.Field( - proto.STRING, - number=433907078, - ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -88353,10 +90144,6 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -88364,9 +90151,9 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): ) -class ListNetworkFirewallPoliciesRequest(proto.Message): - r"""A request message for NetworkFirewallPolicies.List. See the - method description for details. +class ListNetworkProfilesRequest(proto.Message): + r"""A request message for NetworkProfiles.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -88521,8 +90308,8 @@ class ListNetworkFirewallPoliciesRequest(proto.Message): ) -class ListNetworkProfilesRequest(proto.Message): - r"""A request message for NetworkProfiles.List. See the method +class ListNetworksRequest(proto.Message): + r"""A request message for Networks.List. See the method description for details. @@ -88678,8 +90465,8 @@ class ListNetworkProfilesRequest(proto.Message): ) -class ListNetworksRequest(proto.Message): - r"""A request message for Networks.List. See the method +class ListNodeGroupsRequest(proto.Message): + r"""A request message for NodeGroups.List. See the method description for details. @@ -88802,6 +90589,8 @@ class ListNetworksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -88833,10 +90622,14 @@ class ListNetworksRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListNodeGroupsRequest(proto.Message): - r"""A request message for NodeGroups.List. See the method +class ListNodeTemplatesRequest(proto.Message): + r"""A request message for NodeTemplates.List. See the method description for details. @@ -88948,6 +90741,8 @@ class ListNodeGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88959,8 +90754,6 @@ class ListNodeGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -88987,19 +90780,19 @@ class ListNodeGroupsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListNodeTemplatesRequest(proto.Message): - r"""A request message for NodeTemplates.List. See the method +class ListNodeTypesRequest(proto.Message): + r"""A request message for NodeTypes.List. See the method description for details. @@ -89111,8 +90904,6 @@ class ListNodeTemplatesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -89124,6 +90915,8 @@ class ListNodeTemplatesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -89150,19 +90943,19 @@ class ListNodeTemplatesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListNodeTypesRequest(proto.Message): - r"""A request message for NodeTypes.List. See the method +class ListNodesNodeGroupsRequest(proto.Message): + r"""A request message for NodeGroups.ListNodes. See the method description for details. @@ -89249,6 +91042,9 @@ class ListNodeTypesRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. + node_group (str): + Name of the NodeGroup resource whose nodes + you want to list. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -89299,6 +91095,10 @@ class ListNodeTypesRequest(proto.Message): number=54715419, optional=True, ) + node_group: str = proto.Field( + proto.STRING, + number=469958146, + ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -89324,9 +91124,166 @@ class ListNodeTypesRequest(proto.Message): ) -class ListNodesNodeGroupsRequest(proto.Message): - r"""A request message for NodeGroups.ListNodes. See the method - description for details. +class ListOrganizationRolloutPlansRequest(proto.Message): + r"""A request message for OrganizationRolloutPlans.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``. + 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``. + organization (str): + Organization ID for this request. + 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``. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListOrganizationRolloutsRequest(proto.Message): + r"""A request message for OrganizationRollouts.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -89412,9 +91369,6 @@ class ListNodesNodeGroupsRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. - node_group (str): - Name of the NodeGroup resource whose nodes - you want to list. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -89432,14 +91386,14 @@ class ListNodesNodeGroupsRequest(proto.Message): ``creationTimestamp desc`` is supported. This field is a member of `oneof`_ ``_order_by``. + organization (str): + Required. Organization ID for this request. page_token (str): Specifies a page token to use. Set ``pageToken`` to the ``nextPageToken`` returned by a previous list request to get the next page of results. This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -89451,8 +91405,6 @@ class ListNodesNodeGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -89465,33 +91417,25 @@ class ListNodesNodeGroupsRequest(proto.Message): number=54715419, optional=True, ) - node_group: str = proto.Field( - proto.STRING, - number=469958146, - ) order_by: str = proto.Field( proto.STRING, number=160562920, optional=True, ) + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) page_token: str = proto.Field( proto.STRING, number=19994697, optional=True, ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) class ListOrganizationSecurityPoliciesRequest(proto.Message): @@ -96930,6 +98874,163 @@ class ListRegionsRequest(proto.Message): ) +class ListReliabilityRisksRequest(proto.Message): + r"""A request message for ReliabilityRisks.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``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + class ListReservationBlocksRequest(proto.Message): r"""A request message for ReservationBlocks.List. See the method description for details. @@ -104159,6 +106260,12 @@ class MachineImageParams(proto.Message): r"""Machine Image parameters Attributes: + excluded_disks (MutableSequence[str]): + Input only. [Input Only] Specifies the list of disk device + names that must be excluded from the new machine image. + included_disks (MutableSequence[str]): + Input only. [Input Only] Specifies the list of disk device + names that must be included with the new machine image. resource_manager_tags (MutableMapping[str, str]): Input only. Resource manager tags to be bound to the machine image. Tag keys and values have the same definition as @@ -104170,6 +106277,14 @@ class MachineImageParams(proto.Message): PATCH) when empty. """ + excluded_disks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=301656001, + ) + included_disks: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=139709747, + ) resource_manager_tags: MutableMapping[str, str] = proto.MapField( proto.STRING, proto.STRING, @@ -104657,14 +106772,15 @@ class ManagedInstance(proto.Message): This field is a member of `oneof`_ ``_properties_from_flexibility_policy``. scheduling (google.cloud.compute_v1beta.types.ManagedInstanceScheduling): - Output only. [Output Only] Information about the termination - timestamp of the instance, if applicable. + Output only. Information about the + termination timestamp of the instance, if + applicable. This field is a member of `oneof`_ ``_scheduling``. shutdown_details (google.cloud.compute_v1beta.types.ManagedInstanceShutdownDetails): - Output only. [Output Only] Specifies the graceful shutdown - details if the instance is in ``PENDING_STOP`` state or - there is a programmed stop scheduled. + Output only. Specifies the graceful shutdown details if the + instance is in ``PENDING_STOP`` state or there is a + programmed stop scheduled. This field is a member of `oneof`_ ``_shutdown_details``. target_status (str): @@ -104756,6 +106872,10 @@ class CurrentAction(proto.Enum): RESTARTING (320534387): The managed instance group is restarting this instance. + RESTARTING_IN_PLACE (212928665): + The managed instance group is restarting this + instance while preserving its capacity and local + SSDs. RESUMING (446856618): The managed instance group is resuming this instance. @@ -104788,6 +106908,7 @@ class CurrentAction(proto.Enum): RECREATING = 287278572 REFRESHING = 163266343 RESTARTING = 320534387 + RESTARTING_IN_PLACE = 212928665 RESUMING = 446856618 STARTING = 488820800 VERIFYING = 16982185 @@ -105172,15 +107293,16 @@ class ManagedInstanceScheduling(proto.Message): Attributes: graceful_shutdown_timestamp (str): - Output only. [Output Only] The timestamp at which the - underlying instance will be triggered for graceful shutdown - if it is configured. This is in RFC3339 text format. + Output only. The timestamp at which the + underlying instance will be triggered for + graceful shutdown if it is configured. This is + in RFC3339 text format. This field is a member of `oneof`_ ``_graceful_shutdown_timestamp``. termination_timestamp (str): - Output only. [Output Only] The timestamp at which the - managed instance will be terminated. This is in RFC3339 text - format. + Output only. The timestamp at which the + managed instance will be terminated. This is in + RFC3339 text format. This field is a member of `oneof`_ ``_termination_timestamp``. """ @@ -105204,15 +107326,13 @@ class ManagedInstanceShutdownDetails(proto.Message): Attributes: max_duration (google.cloud.compute_v1beta.types.Duration): - Output only. [Output Only] The duration for graceful - shutdown. Only applicable when the instance is in - ``PENDING_STOP`` state. + Output only. The duration for graceful shutdown. Only + applicable when the instance is in ``PENDING_STOP`` state. This field is a member of `oneof`_ ``_max_duration``. request_timestamp (str): - Output only. [Output Only] Past timestamp indicating the - beginning of ``PENDING_STOP`` state of instance in RFC3339 - text format. + Output only. Past timestamp indicating the beginning of + ``PENDING_STOP`` state of instance in RFC3339 text format. This field is a member of `oneof`_ ``_request_timestamp``. """ @@ -106949,13 +109069,15 @@ class NetworkAttachment(proto.Message): This field is a member of `oneof`_ ``_network``. producer_accept_lists (MutableSequence[str]): - Projects that are allowed to connect to this - network attachment. The project can be specified - using its id or number. + Projects or service class ids that are allowed to connect to + this network attachment. The project can be specified using + its id or number. Service class id can be specified as + "serviceclasses/{service_class_id}". producer_reject_lists (MutableSequence[str]): - Projects that are not allowed to connect to - this network attachment. The project can be - specified using its id or number. + Projects or service class ids that are not allowed to + connect to this network attachment. The project can be + specified using its id or number. Service class id can be + specified as "serviceclasses/{service_class_id}". region (str): Output only. [Output Only] URL of the region where the network attachment resides. This field applies only to the @@ -107838,9 +109960,14 @@ class NetworkEndpointGroup(proto.Message): This field is a member of `oneof`_ ``_name``. network (str): - The URL of the network to which all network - endpoints in the NEG belong. Uses default - project network if unspecified. + The URL of the network to which all network endpoints in the + NEG belong. For networkEndpointType + GCE_VM_IP_PORT,GCE_VM_IP_PORTMAP or NON_GCP_PRIVATE_IP_PORT, + if this field is not specified, a default network will be + used. This field cannot be set for NEGs with + networkEndpointType set toSERVERLESS or + PRIVATE_SERVICE_CONNECT and for global NEGs. For all other + network endpoint types, this field is required. This field is a member of `oneof`_ ``_network``. network_endpoint_type (str): @@ -108361,8 +110488,14 @@ class NetworkEndpointGroupLbNetworkEndpointGroup(proto.Message): This field is a member of `oneof`_ ``_default_port``. network (str): The URL of the network to which all network endpoints in the - NEG belong. Uses default project network if unspecified. - [Deprecated] This field is deprecated. + NEG belong. For networkEndpointType + GCE_VM_IP_PORT,GCE_VM_IP_PORTMAP or NON_GCP_PRIVATE_IP_PORT, + if this field is not specified, a default network will be + used. This field cannot be set for NEGs with + networkEndpointType set toSERVERLESS or + PRIVATE_SERVICE_CONNECT and for global NEGs. For all other + network endpoint types, this field is required. [Deprecated] + This field is deprecated. This field is a member of `oneof`_ ``_network``. subnetwork (str): @@ -111203,6 +113336,11 @@ class AddressPurposes(proto.Enum): A private network IP address that can be shared by multiple Internal Load Balancer forwarding rules. + SYSTEM_MANAGED (429787503): + A regional internal IP address that is + reserved and managed internally. It can not be + assigned to compute resources such as VM and + internal load balancer. VPC_PEERING (400800170): IP range for peer networks. """ @@ -111217,6 +113355,7 @@ class AddressPurposes(proto.Enum): PRIVATE_SERVICE_CONNECT = 48134724 SERVERLESS = 270492508 SHARED_LOADBALANCER_VIP = 294447572 + SYSTEM_MANAGED = 429787503 VPC_PEERING = 400800170 class AllowAddressCreation(proto.Enum): @@ -115402,6 +117541,86 @@ class OperationsScopedList(proto.Message): ) +class OrganizationRolloutsListResponse(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1beta.types.Rollout]): + A list of Rollout resources. + next_page_token (str): + [Output Only] 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``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + end_interface: MixerListResponseWithEtagBuilder + warning (google.cloud.compute_v1beta.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["Rollout"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="Rollout", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class OrganizationSecurityPoliciesListAssociationsResponse(proto.Message): r""" @@ -121334,6 +123553,134 @@ class PathRule(proto.Message): ) +class PauseOrganizationRolloutRequest(proto.Message): + r"""A request message for OrganizationRollouts.Pause. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + The etag of the Rollout. + If this is provided, the request will only + succeed if the etag matches the current etag of + the Rollout. + + This field is a member of `oneof`_ ``_etag``. + organization (str): + Required. Organization ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + pause. + """ + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + +class PauseRolloutRequest(proto.Message): + r"""A request message for Rollouts.Pause. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + The etag of the Rollout. + If this is provided, the request will only + succeed if the etag matches the current etag of + the Rollout. + + This field is a member of `oneof`_ ``_etag``. + project (str): + Required. Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + pause. + """ + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class PerInstanceConfig(proto.Message): r""" @@ -121594,21 +123941,166 @@ class PerformMaintenanceReservationBlockRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - reservation (str): - The name of the reservation. - Name should conform to RFC1035 or be a resource - ID. - reservation_block (str): - The name of the reservation block. + reservation (str): + The name of the reservation. + Name should conform to RFC1035 or be a resource + ID. + reservation_block (str): + The name of the reservation block. + Name should conform to RFC1035 or be a resource + ID. + reservations_blocks_perform_maintenance_request_resource (google.cloud.compute_v1beta.types.ReservationsBlocksPerformMaintenanceRequest): + The body resource for this request + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + reservation: str = proto.Field( + proto.STRING, + number=47530956, + ) + reservation_block: str = proto.Field( + proto.STRING, + number=532832858, + ) + reservations_blocks_perform_maintenance_request_resource: "ReservationsBlocksPerformMaintenanceRequest" = proto.Field( + proto.MESSAGE, + number=485823625, + message="ReservationsBlocksPerformMaintenanceRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class PerformMaintenanceReservationRequest(proto.Message): + r"""A request message for Reservations.PerformMaintenance. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + reservation (str): + The name of the reservation. + Name should conform to RFC1035 or be a resource + ID. + reservations_perform_maintenance_request_resource (google.cloud.compute_v1beta.types.ReservationsPerformMaintenanceRequest): + The body resource for this request + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + reservation: str = proto.Field( + proto.STRING, + number=47530956, + ) + reservations_perform_maintenance_request_resource: "ReservationsPerformMaintenanceRequest" = proto.Field( + proto.MESSAGE, + number=29702816, + message="ReservationsPerformMaintenanceRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class PerformMaintenanceReservationSubBlockRequest(proto.Message): + r"""A request message for + ReservationSubBlocks.PerformMaintenance. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + reservation_sub_block (str): + The name of the reservation subBlock. Name should conform to RFC1035 or be a resource ID. - reservations_blocks_perform_maintenance_request_resource (google.cloud.compute_v1beta.types.ReservationsBlocksPerformMaintenanceRequest): - The body resource for this request zone (str): Name of the zone for this request. Zone name should conform to RFC1035. """ + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -121618,18 +124110,9 @@ class PerformMaintenanceReservationBlockRequest(proto.Message): number=37109963, optional=True, ) - reservation: str = proto.Field( - proto.STRING, - number=47530956, - ) - reservation_block: str = proto.Field( + reservation_sub_block: str = proto.Field( proto.STRING, - number=532832858, - ) - reservations_blocks_perform_maintenance_request_resource: "ReservationsBlocksPerformMaintenanceRequest" = proto.Field( - proto.MESSAGE, - number=485823625, - message="ReservationsBlocksPerformMaintenanceRequest", + number=22750491, ) zone: str = proto.Field( proto.STRING, @@ -121637,139 +124120,210 @@ class PerformMaintenanceReservationBlockRequest(proto.Message): ) -class PerformMaintenanceReservationRequest(proto.Message): - r"""A request message for Reservations.PerformMaintenance. See - the method description for details. +class PeriodicPartialMaintenanceSchedule(proto.Message): + r"""The periodic partial maintenance schedule includes 52 weeks + worth of maintenance windows. + LINT.IfChange(PeriodicPartialMaintenanceSchedule) .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + sub_type (str): + The maintenance type in which the zone is + during the given window. Check the SubType enum + for the list of possible values. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + This field is a member of `oneof`_ ``_sub_type``. + target_resource (str): + The target resource that the maintenance + window is for. For example, + "projects/my-project/zones/us-central1-a". - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + This field is a member of `oneof`_ ``_target_resource``. + type_ (str): + Check the Type enum for the list of possible + values. - This field is a member of `oneof`_ ``_request_id``. - reservation (str): - The name of the reservation. - Name should conform to RFC1035 or be a resource - ID. - reservations_perform_maintenance_request_resource (google.cloud.compute_v1beta.types.ReservationsPerformMaintenanceRequest): - The body resource for this request - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. + This field is a member of `oneof`_ ``_type``. + window_end_time (google.cloud.compute_v1beta.types.DateTime): + The end civil timestamp of the window (not + inclusive). This contains a time zone. + + This field is a member of `oneof`_ ``_window_end_time``. + window_start_time (google.cloud.compute_v1beta.types.DateTime): + The start civil timestamp of the window. + This contains a time zone. + + This field is a member of `oneof`_ ``_window_start_time``. """ - project: str = proto.Field( + class SubType(proto.Enum): + r"""The maintenance type in which the zone is during the given + window. + + Values: + UNDEFINED_SUB_TYPE (0): + A value indicating that the enum field is not + set. + MAINTENANCE_SUBTYPE_UNSPECIFIED (294853734): + Default value. + MAINTENANCE_TYPE_CUSTOMER_MAINTENANCE (431585707): + A dedicated window for customers to perform their own + maintenance. This often runs concurrently with a + DISRUPTIVE_UPGRADE. + MAINTENANCE_TYPE_DISRUPTIVE_UPGRADE (385079609): + For disruptive updates, including host + machine kernel or firmware upgrades. + MAINTENANCE_TYPE_STABLE (141316244): + A post-maintenance window for customers to + conduct final testing and performance validation + before resuming full business operations. + MAINTENANCE_TYPE_TRANSITION (348575278): + For preliminary, non-disruptive tasks such as + key rotations. + """ + + UNDEFINED_SUB_TYPE = 0 + MAINTENANCE_SUBTYPE_UNSPECIFIED = 294853734 + MAINTENANCE_TYPE_CUSTOMER_MAINTENANCE = 431585707 + MAINTENANCE_TYPE_DISRUPTIVE_UPGRADE = 385079609 + MAINTENANCE_TYPE_STABLE = 141316244 + MAINTENANCE_TYPE_TRANSITION = 348575278 + + class Type(proto.Enum): + r""" + + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + MAINTENANCE_TYPE_UNSPECIFIED (351550814): + Default value. + PRIVATE_ZONE_MAINTENANCE (55583292): + The zone is in a private maintenance window. + """ + + UNDEFINED_TYPE = 0 + MAINTENANCE_TYPE_UNSPECIFIED = 351550814 + PRIVATE_ZONE_MAINTENANCE = 55583292 + + sub_type: str = proto.Field( proto.STRING, - number=227560217, + number=67924441, + optional=True, ) - request_id: str = proto.Field( + target_resource: str = proto.Field( proto.STRING, - number=37109963, + number=467318524, optional=True, ) - reservation: str = proto.Field( + type_: str = proto.Field( proto.STRING, - number=47530956, + number=3575610, + optional=True, ) - reservations_perform_maintenance_request_resource: "ReservationsPerformMaintenanceRequest" = proto.Field( + window_end_time: "DateTime" = proto.Field( proto.MESSAGE, - number=29702816, - message="ReservationsPerformMaintenanceRequest", + number=271816480, + optional=True, + message="DateTime", ) - zone: str = proto.Field( - proto.STRING, - number=3744684, + window_start_time: "DateTime" = proto.Field( + proto.MESSAGE, + number=473061433, + optional=True, + message="DateTime", ) -class PerformMaintenanceReservationSubBlockRequest(proto.Message): - r"""A request message for - ReservationSubBlocks.PerformMaintenance. See the method - description for details. - +class PersistentDiskResourceCommitment(proto.Message): + r"""Commitment for a particular persistent disk resource. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - parent_name (str): - The name of the parent reservation and parent block. In the - format of - reservations/{reservation_name}/reservationBlocks/{reservation_block_name} - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + amount (int): + Required. The amount of the resource to + commit to, in GiB. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + This field is a member of `oneof`_ ``_amount``. + dimension_type (str): + The specific dimension of the product for + this amount. Check the DimensionType enum for + the list of possible values. - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + This field is a member of `oneof`_ ``_dimension_type``. + product_type (str): + The PD product being committed to. All entries in a + Commitment.persistent_disk_resources list must have the same + product_type. Check the ProductType enum for the list of + possible values. - This field is a member of `oneof`_ ``_request_id``. - reservation_sub_block (str): - The name of the reservation subBlock. - Name should conform to RFC1035 or be a resource - ID. - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. + This field is a member of `oneof`_ ``_product_type``. """ - parent_name: str = proto.Field( - proto.STRING, - number=478151936, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, + class DimensionType(proto.Enum): + r"""The specific dimension of the product for this amount. + + Values: + UNDEFINED_DIMENSION_TYPE (0): + A value indicating that the enum field is not + set. + CAPACITY_OPTIMIZED (17430466): + Dimensions for HYPERDISK_EXAPOOL\_\* Represents a commitment + for HYPERDISK_EXAPOOL_CAPACITY_CAPACITY_OPTIMIZED SKU. + DIMENSION_TYPE_UNSPECIFIED (536500075): + No description available. + READ_OPTIMIZED (510648734): + No description available. + WRITE_OPTIMIZED (153161863): + No description available. + """ + + UNDEFINED_DIMENSION_TYPE = 0 + CAPACITY_OPTIMIZED = 17430466 + DIMENSION_TYPE_UNSPECIFIED = 536500075 + READ_OPTIMIZED = 510648734 + WRITE_OPTIMIZED = 153161863 + + class ProductType(proto.Enum): + r"""The PD product being committed to. All entries in a + Commitment.persistent_disk_resources list must have the same + product_type. + + Values: + UNDEFINED_PRODUCT_TYPE (0): + A value indicating that the enum field is not + set. + HYPERDISK_EXAPOOL_BALANCED (367619635): + Represents a commitment for Hyperdisk Exapool + Balanced. + HYPERDISK_EXAPOOL_THROUGHPUT (475649173): + No description available. + PRODUCT_TYPE_UNSPECIFIED (93839106): + No description available. + """ + + UNDEFINED_PRODUCT_TYPE = 0 + HYPERDISK_EXAPOOL_BALANCED = 367619635 + HYPERDISK_EXAPOOL_THROUGHPUT = 475649173 + PRODUCT_TYPE_UNSPECIFIED = 93839106 + + amount: int = proto.Field( + proto.INT64, + number=196759640, optional=True, ) - reservation_sub_block: str = proto.Field( + dimension_type: str = proto.Field( proto.STRING, - number=22750491, + number=299911795, + optional=True, ) - zone: str = proto.Field( + product_type: str = proto.Field( proto.STRING, - number=3744684, + number=477706378, + optional=True, ) @@ -122917,6 +125471,30 @@ class XpnProjectStatus(proto.Enum): ) +class ProjectView(proto.Message): + r"""Represents a ProjectView resource. + + A ProjectView resource contains read-only project data which is + available globally. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (google.cloud.compute_v1beta.types.Project): + The project data. + + This field is a member of `oneof`_ ``_project``. + """ + + project: "Project" = proto.Field( + proto.MESSAGE, + number=227560217, + optional=True, + message="Project", + ) + + class ProjectsDisableXpnResourceRequest(proto.Message): r""" @@ -125638,6 +128216,59 @@ class Reference(proto.Message): ) +class RegexRewrite(proto.Message): + r"""The spec for modifying the path using a regular expression. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + path_pattern (str): + The regular expression used to match against the URL path. + It uses RE2 syntax with the following constraints: + + :: + + - Any single character operators + - Groups are allowed to have only submatch operator inside + - Groups are allowed only without any char repetition, e.g. + .* + - Any char repetition, e.g. .*, is + only allowed to be used in a single regex together with: + + + - Empty string operators + - Other repetitions + - Ranges + - Repetitions of ranges + + + - Ranges are only allowed to have: + + + - Character range + - Digits range + - Symbols listed in characters allowed for ranges + + This field is a member of `oneof`_ ``_path_pattern``. + path_substitution (str): + Required when path pattern is specified. Used + to rewrite matching parts of the path. + + This field is a member of `oneof`_ ``_path_substitution``. + """ + + path_pattern: str = proto.Field( + proto.STRING, + number=316473718, + optional=True, + ) + path_substitution: str = proto.Field( + proto.STRING, + number=268020951, + optional=True, + ) + + class Region(proto.Message): r"""Represents a Region resource. @@ -126447,6 +129078,10 @@ class RegionInstanceGroupManagersApplyUpdatesRequest(proto.Message): specified in the request. This field is a member of `oneof`_ ``_all_instances``. + allowed_actions (MutableSequence[str]): + Actions that are allowed to update instances + within MIG. Check the AllowedActions enum for + the list of possible values. instances (MutableSequence[str]): The list of URLs of one or more instances for which you want to apply updates. Each URL can be a full URL or a partial @@ -126497,13 +129132,27 @@ class RegionInstanceGroupManagersApplyUpdatesRequest(proto.Message): This field is a member of `oneof`_ ``_most_disruptive_allowed_action``. """ + class AllowedActions(proto.Enum): + r"""Additional supported values which may be not listed in the enum + directly due to technical reasons: NONE REFRESH REPLACE RESTART + RESTART_IN_PLACE + + Values: + UNDEFINED_ALLOWED_ACTIONS (0): + A value indicating that the enum field is not + set. + """ + + UNDEFINED_ALLOWED_ACTIONS = 0 + class MinimalAction(proto.Enum): - r"""The minimal action that you want to perform on each instance - during the update: + r"""The minimal action that you want to perform on each instance during + the update: + :: - REPLACE: At minimum, delete the instance and create it - again. + again. - RESTART: Stop the instance and start it again. - REFRESH: Do not stop the instance and limit @@ -126511,16 +129160,11 @@ class MinimalAction(proto.Enum): - NONE: Do not disrupt the instance at all. - By default, the minimum action is NONE. If your update requires - a more disruptive action than you set with this flag, the - necessary action is performed to execute the update. Additional - supported values which may be not listed in the enum directly - due to technical reasons: - - NONE - REFRESH - REPLACE - RESTART + By default, the minimum action is NONE. If your update requires a + more disruptive action than you set with this flag, the necessary + action is performed to execute the update. Additional supported + values which may be not listed in the enum directly due to technical + reasons: NONE REFRESH REPLACE RESTART RESTART_IN_PLACE Values: UNDEFINED_MINIMAL_ACTION (0): @@ -126531,27 +129175,23 @@ class MinimalAction(proto.Enum): UNDEFINED_MINIMAL_ACTION = 0 class MostDisruptiveAllowedAction(proto.Enum): - r"""The most disruptive action that you want to perform on each - instance during the update: + r"""The most disruptive action that you want to perform on each instance + during the update: + :: - REPLACE: Delete the instance and create it again. - RESTART: Stop the instance and start it again. - REFRESH: Do not stop the instance and limit disruption - as much as possible. + as much as possible. - NONE: Do not disrupt the instance at all. - By default, the most disruptive allowed action is REPLACE. If - your update requires a more disruptive action than you set with - this flag, the update request will fail. - Additional supported values which may be not listed in the enum - directly due to technical reasons: - - NONE - REFRESH - REPLACE - RESTART + By default, the most disruptive allowed action is REPLACE. If your + update requires a more disruptive action than you set with this + flag, the update request will fail. Additional supported values + which may be not listed in the enum directly due to technical + reasons: NONE REFRESH REPLACE RESTART RESTART_IN_PLACE Values: UNDEFINED_MOST_DISRUPTIVE_ALLOWED_ACTION (0): @@ -126566,6 +129206,10 @@ class MostDisruptiveAllowedAction(proto.Enum): number=403676512, optional=True, ) + allowed_actions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=341166438, + ) instances: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=29097598, @@ -127516,6 +130160,188 @@ class RegionUrlMapsValidateRequest(proto.Message): ) +class ReliabilityRisk(proto.Message): + r"""Represents a ReliabilityRisk 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 in RFC3339 + text format. + + This field is a member of `oneof`_ ``_creation_timestamp``. + description (str): + An optional textual description of the + resource; provided when the resource is created. + + This field is a member of `oneof`_ ``_description``. + details (google.cloud.compute_v1beta.types.RiskDetails): + [Output Only] Details of the reliability risk resource + + This field is a member of `oneof`_ ``_details``. + id (int): + [Output Only] The unique identifier for the resource. This + identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + kind (str): + Output only. [Output Only] Type of resource. Always + compute#reliabilityRisk for reliability risks. + + This field is a member of `oneof`_ ``_kind``. + name (str): + Name of the resource. The name must be 1-63 + characters long and comply with RFC1035. + + This field is a member of `oneof`_ ``_name``. + recommendation (google.cloud.compute_v1beta.types.RiskRecommendation): + The recommendation to mitigate the risk. + + This field is a member of `oneof`_ ``_recommendation``. + self_link (str): + Output only. [Output Only] Server-defined URL for the + resource. + + This field is a member of `oneof`_ ``_self_link``. + self_link_with_id (str): + Output only. [Output Only] Server-defined URL for this + resource with the resource id. + + This field is a member of `oneof`_ ``_self_link_with_id``. + """ + + creation_timestamp: str = proto.Field( + proto.STRING, + number=30525366, + optional=True, + ) + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + details: "RiskDetails" = proto.Field( + proto.MESSAGE, + number=483979842, + optional=True, + message="RiskDetails", + ) + 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, + ) + recommendation: "RiskRecommendation" = proto.Field( + proto.MESSAGE, + number=45105081, + optional=True, + message="RiskRecommendation", + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + self_link_with_id: str = proto.Field( + proto.STRING, + number=44520962, + optional=True, + ) + + +class ReliabilityRisksListResponse(proto.Message): + r"""Response message for the List method of + ReliabilityRisksService. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] Unique identifier for the resource; defined by + the server. + + This field is a member of `oneof`_ ``_id``. + items (MutableSequence[google.cloud.compute_v1beta.types.ReliabilityRisk]): + A list of ReliabilityRisk resources. + next_page_token (str): + [Output Only] 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``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + end_interface: MixerListResponseWithEtagBuilder + warning (google.cloud.compute_v1beta.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + items: MutableSequence["ReliabilityRisk"] = proto.RepeatedField( + proto.MESSAGE, + number=100526016, + message="ReliabilityRisk", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class RemoveAssociationFirewallPolicyRequest(proto.Message): r"""A request message for FirewallPolicies.RemoveAssociation. See the method description for details. @@ -133465,6 +136291,11 @@ class ResourceStatusPhysicalHostTopology(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + additional_attributes (google.cloud.compute_v1beta.types.ResourceStatusPhysicalHostTopologyAdditionalAttributes): + Output only. [Output Only] Additional location information + of the running instance. + + This field is a member of `oneof`_ ``_additional_attributes``. block (str): [Output Only] The ID of the block in which the running instance is located. Instances within the same block @@ -133491,6 +136322,14 @@ class ResourceStatusPhysicalHostTopology(proto.Message): This field is a member of `oneof`_ ``_subblock``. """ + additional_attributes: "ResourceStatusPhysicalHostTopologyAdditionalAttributes" = ( + proto.Field( + proto.MESSAGE, + number=74463343, + optional=True, + message="ResourceStatusPhysicalHostTopologyAdditionalAttributes", + ) + ) block: str = proto.Field( proto.STRING, number=93832333, @@ -133513,6 +136352,25 @@ class ResourceStatusPhysicalHostTopology(proto.Message): ) +class ResourceStatusPhysicalHostTopologyAdditionalAttributes(proto.Message): + r"""Additional location information of the running instance. + + Attributes: + accelerator_topology_ids (MutableMapping[str, str]): + Output only. The IDs of the accelerator + topologies the instance belongs to. For example + The key will be topologies like "4x4", "2x2x2" + and the value will be the location ID of the + topologies. + """ + + accelerator_topology_ids: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=338216508, + ) + + class ResourceStatusReservationConsumptionInfo(proto.Message): r"""Reservation consumption information that the instance is consuming from. @@ -133526,6 +136384,16 @@ class ResourceStatusReservationConsumptionInfo(proto.Message): reservation that this instance is consuming from. This field is a member of `oneof`_ ``_consumed_reservation``. + consumed_reservation_block (str): + Output only. [Output Only] The full resource name of the + reservation block that this instance is consuming from. + + This field is a member of `oneof`_ ``_consumed_reservation_block``. + consumed_reservation_sub_block (str): + Output only. [Output Only] The full resource name of the + reservation sub-block that this instance is consuming from. + + This field is a member of `oneof`_ ``_consumed_reservation_sub_block``. """ consumed_reservation: str = proto.Field( @@ -133533,6 +136401,16 @@ class ResourceStatusReservationConsumptionInfo(proto.Message): number=318474741, optional=True, ) + consumed_reservation_block: str = proto.Field( + proto.STRING, + number=142321091, + optional=True, + ) + consumed_reservation_sub_block: str = proto.Field( + proto.STRING, + number=461540356, + optional=True, + ) class ResourceStatusScheduling(proto.Message): @@ -133757,19 +136635,212 @@ class ResumeInstancesInstanceGroupManagerRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of thezone where the managed - instance group is located. + zone (str): + The name of thezone where the managed + instance group is located. + """ + + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) + instance_group_managers_resume_instances_request_resource: "InstanceGroupManagersResumeInstancesRequest" = proto.Field( + proto.MESSAGE, + number=129015618, + message="InstanceGroupManagersResumeInstancesRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class ResumeInstancesRegionInstanceGroupManagerRequest(proto.Message): + r"""A request message for + RegionInstanceGroupManagers.ResumeInstances. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + instance_group_manager (str): + Name of the managed instance group. + project (str): + Project ID for this request. + region (str): + Name of the region scoping this request. + region_instance_group_managers_resume_instances_request_resource (google.cloud.compute_v1beta.types.RegionInstanceGroupManagersResumeInstancesRequest): + The body resource for this request + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_instance_group_managers_resume_instances_request_resource: "RegionInstanceGroupManagersResumeInstancesRequest" = proto.Field( + proto.MESSAGE, + number=463471031, + message="RegionInstanceGroupManagersResumeInstancesRequest", + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class ResumeOrganizationRolloutRequest(proto.Message): + r"""A request message for OrganizationRollouts.Resume. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + The etag of the Rollout. + If this is provided, the request will only + succeed if the etag matches the current etag of + the Rollout. + + This field is a member of `oneof`_ ``_etag``. + organization (str): + Required. Organization ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + resume. + """ + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + organization: str = proto.Field( + proto.STRING, + number=105180467, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + +class ResumeRolloutRequest(proto.Message): + r"""A request message for Rollouts.Resume. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + The etag of the Rollout. + If this is provided, the request will only + succeed if the etag matches the current etag of + the Rollout. + + This field is a member of `oneof`_ ``_etag``. + project (str): + Required. Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + resume. """ - instance_group_manager: str = proto.Field( + etag: str = proto.Field( proto.STRING, - number=249363395, - ) - instance_group_managers_resume_instances_request_resource: "InstanceGroupManagersResumeInstancesRequest" = proto.Field( - proto.MESSAGE, - number=129015618, - message="InstanceGroupManagersResumeInstancesRequest", + number=3123477, + optional=True, ) project: str = proto.Field( proto.STRING, @@ -133780,73 +136851,194 @@ class ResumeInstancesInstanceGroupManagerRequest(proto.Message): number=37109963, optional=True, ) - zone: str = proto.Field( + rollout: str = proto.Field( proto.STRING, - number=3744684, + number=303366577, ) -class ResumeInstancesRegionInstanceGroupManagerRequest(proto.Message): - r"""A request message for - RegionInstanceGroupManagers.ResumeInstances. See the method - description for details. +class RiskDetails(proto.Message): + r"""Detailed insights and metrics about a detected reliability + risk. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - instance_group_manager (str): - Name of the managed instance group. - project (str): - Project ID for this request. - region (str): - Name of the region scoping this request. - region_instance_group_managers_resume_instances_request_resource (google.cloud.compute_v1beta.types.RegionInstanceGroupManagersResumeInstancesRequest): - The body resource for this request - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + duration (str): + The duration of the risk since it was + detected. - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + This field is a member of `oneof`_ ``_duration``. + global_dns_insight (google.cloud.compute_v1beta.types.RiskDetailsGlobalDnsInsight): + Insight details for global DNS risk. - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + This field is a member of `oneof`_ ``_global_dns_insight``. + last_update_timestamp (str): + The last time the risk was updated. - This field is a member of `oneof`_ ``_request_id``. + This field is a member of `oneof`_ ``_last_update_timestamp``. + severity (str): + The severity of the risk. + Check the Severity enum for the list of possible + values. + + This field is a member of `oneof`_ ``_severity``. + type_ (str): + The type of risk. + Check the Type enum for the list of possible + values. + + This field is a member of `oneof`_ ``_type``. """ - instance_group_manager: str = proto.Field( + class Severity(proto.Enum): + r"""The severity of the risk. + + Values: + UNDEFINED_SEVERITY (0): + A value indicating that the enum field is not + set. + CRITICAL (50423711): + Critical severity. + HIGH (2217378): + High severity. + LOW (75572): + Low severity. + MEDIUM (122782581): + Medium severity. + SEVERITY_UNSPECIFIED (304082133): + No severity specified. The default value. + """ + + UNDEFINED_SEVERITY = 0 + CRITICAL = 50423711 + HIGH = 2217378 + LOW = 75572 + MEDIUM = 122782581 + SEVERITY_UNSPECIFIED = 304082133 + + class Type(proto.Enum): + r"""The type of risk. + + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + GLOBAL_DNS (164472429): + Risk type related to global DNS. + RISK_TYPE_UNSPECIFIED (71308546): + Default value. This value is unused. + """ + + UNDEFINED_TYPE = 0 + GLOBAL_DNS = 164472429 + RISK_TYPE_UNSPECIFIED = 71308546 + + duration: str = proto.Field( proto.STRING, - number=249363395, + number=155471252, + optional=True, ) - project: str = proto.Field( + global_dns_insight: "RiskDetailsGlobalDnsInsight" = proto.Field( + proto.MESSAGE, + number=514929638, + optional=True, + message="RiskDetailsGlobalDnsInsight", + ) + last_update_timestamp: str = proto.Field( proto.STRING, - number=227560217, + number=12338089, + optional=True, ) - region: str = proto.Field( + severity: str = proto.Field( proto.STRING, - number=138946292, + number=404558589, + optional=True, ) - region_instance_group_managers_resume_instances_request_resource: "RegionInstanceGroupManagersResumeInstancesRequest" = proto.Field( - proto.MESSAGE, - number=463471031, - message="RegionInstanceGroupManagersResumeInstancesRequest", + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, ) - request_id: str = proto.Field( + + +class RiskDetailsGlobalDnsInsight(proto.Message): + r"""Detailed insights for a global DNS reliability risk. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project_default_is_global_dns (bool): + Indicates whether the project's default DNS + setting is global DNS. + + This field is a member of `oneof`_ ``_project_default_is_global_dns``. + query_observation_window (str): + The observation window for the query counts. + + This field is a member of `oneof`_ ``_query_observation_window``. + risky_query_count (int): + The number of queries that are risky. This is always less + than or equal to total_query_count. + + This field is a member of `oneof`_ ``_risky_query_count``. + total_query_count (int): + The total number of queries in the + observation window. + + This field is a member of `oneof`_ ``_total_query_count``. + """ + + project_default_is_global_dns: bool = proto.Field( + proto.BOOL, + number=366337694, + optional=True, + ) + query_observation_window: str = proto.Field( proto.STRING, - number=37109963, + number=511008826, + optional=True, + ) + risky_query_count: int = proto.Field( + proto.INT64, + number=351692195, + optional=True, + ) + total_query_count: int = proto.Field( + proto.INT64, + number=171936349, + optional=True, + ) + + +class RiskRecommendation(proto.Message): + r"""Recommendation for mitigating a reliability risk, including a + reference URL. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + content (str): + Mitigation guide for the risk. + + This field is a member of `oneof`_ ``_content``. + reference_url (str): + URL referencing a more detailed mitigation + guide. + + This field is a member of `oneof`_ ``_reference_url``. + """ + + content: str = proto.Field( + proto.STRING, + number=414659705, + optional=True, + ) + reference_url: str = proto.Field( + proto.STRING, + number=527537787, optional=True, ) @@ -133914,6 +137106,16 @@ class Rollout(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + pause_time (str): + Output only. The timestamp at which the + Rollout was paused. + + This field is a member of `oneof`_ ``_pause_time``. + resume_time (str): + Output only. The timestamp at which the + Rollout was resumed. + + This field is a member of `oneof`_ ``_resume_time``. rollout_entity (google.cloud.compute_v1beta.types.RolloutRolloutEntity): Required. The resource being rolled out. @@ -134065,6 +137267,16 @@ class State(proto.Enum): number=3373707, optional=True, ) + pause_time: str = proto.Field( + proto.STRING, + number=489697142, + optional=True, + ) + resume_time: str = proto.Field( + proto.STRING, + number=457856927, + optional=True, + ) rollout_entity: "RolloutRolloutEntity" = proto.Field( proto.MESSAGE, number=70633009, @@ -137094,6 +140306,14 @@ class RouterNat(proto.Message): IPs that have been assigned to the NAT. These IPs should be used for updating/patching a NAT only. + effective_tcp_time_wait_timeout_sec (int): + Output only. Effective timeout (in seconds) for TCP + connections that are in TIME_WAIT state. This value is equal + to tcp_time_wait_timeout_sec. If tcp_time_wait_timeout_sec + isn't set, the effective timeout is 30s or 120s. The field + is output only. + + This field is a member of `oneof`_ ``_effective_tcp_time_wait_timeout_sec``. enable_dynamic_port_allocation (bool): Enable Dynamic Port Allocation. @@ -137451,6 +140671,11 @@ class Type(proto.Enum): proto.STRING, number=504078535, ) + effective_tcp_time_wait_timeout_sec: int = proto.Field( + proto.INT32, + number=248089957, + optional=True, + ) enable_dynamic_port_allocation: bool = proto.Field( proto.BOOL, number=532106402, @@ -140920,18 +144145,24 @@ class DdosAdaptiveProtection(proto.Enum): UNDEFINED_DDOS_ADAPTIVE_PROTECTION (0): A value indicating that the enum field is not set. + DDOS_ADAPTIVE_PROTECTION_UNSPECIFIED (314527935): + No description available. DISABLED (516696700): No description available. ENABLED (182130465): No description available. PREVIEW (399798184): No description available. + UNSPECIFIED_ADAPTIVE_PROTECTION (86330138): + No description available. """ UNDEFINED_DDOS_ADAPTIVE_PROTECTION = 0 + DDOS_ADAPTIVE_PROTECTION_UNSPECIFIED = 314527935 DISABLED = 516696700 ENABLED = 182130465 PREVIEW = 399798184 + UNSPECIFIED_ADAPTIVE_PROTECTION = 86330138 class DdosProtection(proto.Enum): r""" @@ -142878,6 +146109,12 @@ class ServiceAttachment(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + nat_ips_per_endpoint (int): + The number of NAT IP addresses to be + allocated per connected endpoint. If not + specified, the default value is 1. + + This field is a member of `oneof`_ ``_nat_ips_per_endpoint``. nat_subnets (MutableSequence[str]): An array of URLs where each entry is the URL of a subnet provided by the service producer to @@ -143059,6 +146296,11 @@ class ConnectionPreference(proto.Enum): number=3373707, optional=True, ) + nat_ips_per_endpoint: int = proto.Field( + proto.UINT32, + number=371459848, + optional=True, + ) nat_subnets: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=374785944, @@ -149090,6 +152332,12 @@ class ShareSettings(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + folder_map (MutableMapping[str, google.cloud.compute_v1beta.types.ShareSettingsFolderConfig]): + A map of folder id and folder config to specify consumer + projects for this shared-reservation. This is only valid + when share_type's value is + DIRECT_PROJECTS_UNDER_SPECIFIC_FOLDERS. Folder id should be + a string of number, and without "folders/" prefix. project_map (MutableMapping[str, google.cloud.compute_v1beta.types.ShareSettingsProjectConfig]): A map of project id and project config. This is only valid when share_type's value is SPECIFIC_PROJECTS. @@ -149112,6 +152360,9 @@ class ShareType(proto.Enum): UNDEFINED_SHARE_TYPE (0): A value indicating that the enum field is not set. + DIRECT_PROJECTS_UNDER_SPECIFIC_FOLDERS (325211982): + Shared-reservation is open to direct child + projects of specific folders. LOCAL (72607563): Default value. ORGANIZATION (274978099): @@ -149125,11 +152376,18 @@ class ShareType(proto.Enum): """ UNDEFINED_SHARE_TYPE = 0 + DIRECT_PROJECTS_UNDER_SPECIFIC_FOLDERS = 325211982 LOCAL = 72607563 ORGANIZATION = 274978099 SHARE_TYPE_UNSPECIFIED = 494771730 SPECIFIC_PROJECTS = 347838695 + folder_map: MutableMapping[str, "ShareSettingsFolderConfig"] = proto.MapField( + proto.STRING, + proto.MESSAGE, + number=246024715, + message="ShareSettingsFolderConfig", + ) project_map: MutableMapping[str, "ShareSettingsProjectConfig"] = proto.MapField( proto.STRING, proto.MESSAGE, @@ -149147,6 +152405,28 @@ class ShareType(proto.Enum): ) +class ShareSettingsFolderConfig(proto.Message): + r"""Config for each folder in the share settings. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + folder_id (str): + The folder ID, should be same as the key of + this folder config in the parent map. + Folder id should be a string of number, and + without "folders/" prefix. + + This field is a member of `oneof`_ ``_folder_id``. + """ + + folder_id: str = proto.Field( + proto.STRING, + number=527488652, + optional=True, + ) + + class ShareSettingsProjectConfig(proto.Message): r"""Config for each project in the share settings. @@ -149904,13 +153184,15 @@ class Snapshot(proto.Message): This field is a member of `oneof`_ ``_storage_bytes``. storage_bytes_status (str): - Output only. [Output Only] An indicator whether storageBytes - is in a stable state or it is being adjusted as a result of - shared storage reallocation. This status can either be - UPDATING, meaning the size of the snapshot is being updated, - or UP_TO_DATE, meaning the size of the snapshot is - up-to-date. Check the StorageBytesStatus enum for the list - of possible values. + Output only. [Deprecated] Instead, check the storageBytes + field. After snapshot creation, the storageBytesStatus field + is alwaysUP_TO_DATE. [Output Only] An indicator whether + storageBytes is in a stable state or it is being adjusted as + a result of shared storage reallocation. This status can + either be unset, meaning the snapshot is being created, or + UP_TO_DATE, meaning the size of the snapshot is up-to-date. + Check the StorageBytesStatus enum for the list of possible + values. This field is a member of `oneof`_ ``_storage_bytes_status``. storage_locations (MutableSequence[str]): @@ -149987,11 +153269,13 @@ class Status(proto.Enum): UPLOADING = 267603489 class StorageBytesStatus(proto.Enum): - r"""Output only. [Output Only] An indicator whether storageBytes is in a - stable state or it is being adjusted as a result of shared storage - reallocation. This status can either be UPDATING, meaning the size - of the snapshot is being updated, or UP_TO_DATE, meaning the size of - the snapshot is up-to-date. + r"""Output only. [Deprecated] Instead, check the storageBytes field. + After snapshot creation, the storageBytesStatus field is + alwaysUP_TO_DATE. [Output Only] An indicator whether storageBytes is + in a stable state or it is being adjusted as a result of shared + storage reallocation. This status can either be unset, meaning the + snapshot is being created, or UP_TO_DATE, meaning the size of the + snapshot is up-to-date. Values: UNDEFINED_STORAGE_BYTES_STATUS (0): @@ -152228,9 +155512,6 @@ class SslPolicyReference(proto.Message): Attributes: ssl_policy (str): - URL of the SSL policy resource. Set this to - empty string to clear any existing SSL policy - associated with the target proxy resource. This field is a member of `oneof`_ ``_ssl_policy``. """ @@ -154804,6 +158085,15 @@ class Subnetwork(proto.Message): values. This field is a member of `oneof`_ ``_ipv6_gce_endpoint``. + ipv6_network_tier (str): + Specifies the network tier for EXTERNAL IPv6. Can only be + set when ipv6_access_type is EXTERNAL. Defaults to project + defaultNetworkTier if not specified during the creation of + the subnetwork. This field is IMMUTABLE once set with + EXTERNAL IPv6. Check the Ipv6NetworkTier enum for the list + of possible values. + + This field is a member of `oneof`_ ``_ipv6_network_tier``. kind (str): Output only. [Output Only] Type of the resource. Always compute#subnetwork for Subnetwork resources. @@ -154994,6 +158284,35 @@ class Ipv6GceEndpoint(proto.Enum): VM_AND_FR = 41830108 VM_ONLY = 236773428 + class Ipv6NetworkTier(proto.Enum): + r"""Specifies the network tier for EXTERNAL IPv6. Can only be set when + ipv6_access_type is EXTERNAL. Defaults to project defaultNetworkTier + if not specified during the creation of the subnetwork. This field + is IMMUTABLE once set with EXTERNAL IPv6. + + Values: + UNDEFINED_IPV6_NETWORK_TIER (0): + A value indicating that the enum field is not + set. + FIXED_STANDARD (310464328): + Public internet quality with fixed bandwidth. + PREMIUM (399530551): + High quality, Google-grade network tier, + support for all networking products. + STANDARD (484642493): + Public internet quality, only limited support + for other networking products. + STANDARD_OVERRIDES_FIXED_STANDARD (465847234): + (Output only) Temporary tier for FIXED_STANDARD when fixed + standard tier is expired or not configured. + """ + + UNDEFINED_IPV6_NETWORK_TIER = 0 + FIXED_STANDARD = 310464328 + PREMIUM = 399530551 + STANDARD = 484642493 + STANDARD_OVERRIDES_FIXED_STANDARD = 465847234 + class PrivateIpv6GoogleAccess(proto.Enum): r"""This field is for internal use. @@ -155236,6 +158555,11 @@ class State(proto.Enum): number=320382307, optional=True, ) + ipv6_network_tier: str = proto.Field( + proto.STRING, + number=383707307, + optional=True, + ) kind: str = proto.Field( proto.STRING, number=3292052, @@ -159360,12 +162684,15 @@ class LoadBalancingScheme(proto.Enum): No description available. INTERNAL_MANAGED (37350397): No description available. + LOAD_BALANCING_SCHEME_UNSPECIFIED (526507452): + No description available. """ UNDEFINED_LOAD_BALANCING_SCHEME = 0 EXTERNAL = 35607499 EXTERNAL_MANAGED = 512006923 INTERNAL_MANAGED = 37350397 + LOAD_BALANCING_SCHEME_UNSPECIFIED = 526507452 class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to @@ -162748,6 +166075,38 @@ class TestPermissionsResponse(proto.Message): ) +class TimeZone(proto.Message): + r"""Represents a time zone from the `IANA Time Zone + Database `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + IANA Time Zone Database time zone. For example + "America/New_York". + + This field is a member of `oneof`_ ``_id``. + version (str): + Optional. IANA Time Zone Database version + number. For example "2019a". + + This field is a member of `oneof`_ ``_version``. + """ + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + version: str = proto.Field( + proto.STRING, + number=351608024, + optional=True, + ) + + class Uint128(proto.Message): r""" @@ -166581,6 +169940,13 @@ class UrlRewrite(proto.Message): be specified. This field is a member of `oneof`_ ``_path_template_rewrite``. + regex_rewrite (google.cloud.compute_v1beta.types.RegexRewrite): + The regex rewrite to be applied to the URL. + Only one ofpathPrefixRewrite, + pathTemplateRewrite, orregexRewrite may be + specified. + + This field is a member of `oneof`_ ``_regex_rewrite``. """ host_rewrite: str = proto.Field( @@ -166598,6 +169964,12 @@ class UrlRewrite(proto.Message): number=423409569, optional=True, ) + regex_rewrite: "RegexRewrite" = proto.Field( + proto.MESSAGE, + number=380801428, + optional=True, + message="RegexRewrite", + ) class UsableSubnetwork(proto.Message): @@ -170900,6 +174272,9 @@ class Zone(proto.Message): the zone. This field is a member of `oneof`_ ``_region``. + resource_status (google.cloud.compute_v1beta.types.ZoneResourceStatus): + + This field is a member of `oneof`_ ``_resource_status``. self_link (str): [Output Only] Server-defined URL for the resource. @@ -170972,6 +174347,12 @@ class Status(proto.Enum): number=138946292, optional=True, ) + resource_status: "ZoneResourceStatus" = proto.Field( + proto.MESSAGE, + number=249429315, + optional=True, + message="ZoneResourceStatus", + ) self_link: str = proto.Field( proto.STRING, number=456214797, @@ -171063,6 +174444,24 @@ def raw_page(self): ) +class ZoneResourceStatus(proto.Message): + r""" + + Attributes: + upcoming_maintenances (MutableSequence[google.cloud.compute_v1beta.types.PeriodicPartialMaintenanceSchedule]): + Output only. [Output Only] The upcoming maintenance + schedule. + """ + + upcoming_maintenances: MutableSequence["PeriodicPartialMaintenanceSchedule"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=68484611, + message="PeriodicPartialMaintenanceSchedule", + ) + ) + + class ZoneSetLabelsRequest(proto.Message): r""" diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_get_sync.py new file mode 100644 index 000000000000..c02a014997b1 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_get_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_Hosts_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.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetHostRequest( + association="association_value", + host="host_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_Hosts_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_get_version_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_get_version_sync.py new file mode 100644 index 000000000000..2b29ca57764f --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_get_version_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetVersion +# 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_Hosts_GetVersion_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_version(): + # Create a client + client = compute_v1beta.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetVersionHostRequest( + association="association_value", + host="host_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + response = client.get_version(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_Hosts_GetVersion_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_list_sync.py new file mode 100644 index 000000000000..38222b769919 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_hosts_list_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_Hosts_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.HostsClient() + + # Initialize request argument(s) + request = compute_v1beta.ListHostsRequest( + association="association_value", + project="project_value", + zone="zone_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1beta_generated_Hosts_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_image_views_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_image_views_get_sync.py new file mode 100644 index 000000000000..703da309f700 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_image_views_get_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_ImageViews_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.ImageViewsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetImageViewRequest( + project="project_value", + region="region_value", + resource_id="resource_id_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_ImageViews_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_delete_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_delete_sync.py new file mode 100644 index 000000000000..aa7777893c1d --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Delete +# 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_OrganizationRolloutPlans_Delete_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_delete(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteOrganizationRolloutPlanRequest( + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRolloutPlans_Delete_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_get_sync.py new file mode 100644 index 000000000000..8506b6ed2977 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_OrganizationRolloutPlans_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.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.GetOrganizationRolloutPlanRequest( + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRolloutPlans_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_insert_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_insert_sync.py new file mode 100644 index 000000000000..91d12bb72b55 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_insert_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Insert +# 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_OrganizationRolloutPlans_Insert_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_insert(): + # Create a client + client = compute_v1beta.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.InsertOrganizationRolloutPlanRequest( + organization="organization_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRolloutPlans_Insert_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_list_sync.py new file mode 100644 index 000000000000..71687d9f3ba9 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollout_plans_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_OrganizationRolloutPlans_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.OrganizationRolloutPlansClient() + + # Initialize request argument(s) + request = compute_v1beta.ListOrganizationRolloutPlansRequest( + organization="organization_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1beta_generated_OrganizationRolloutPlans_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_advance_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_advance_sync.py new file mode 100644 index 000000000000..34abcd1c05f1 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_advance_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Advance +# 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_OrganizationRollouts_Advance_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_advance(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.AdvanceOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_Advance_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_cancel_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_cancel_sync.py new file mode 100644 index 000000000000..96c3808a6d0a --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_cancel_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Cancel +# 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_OrganizationRollouts_Cancel_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_cancel(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.CancelOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.cancel(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_Cancel_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_delete_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_delete_sync.py new file mode 100644 index 000000000000..32a11959e497 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_delete_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Delete +# 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_OrganizationRollouts_Delete_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_delete(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.DeleteOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.delete(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_Delete_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_get_sync.py new file mode 100644 index 000000000000..7f2f0ccac457 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_OrganizationRollouts_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.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_list_sync.py new file mode 100644 index 000000000000..e758844944c3 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_OrganizationRollouts_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.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ListOrganizationRolloutsRequest( + organization="organization_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_pause_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_pause_sync.py new file mode 100644 index 000000000000..741d738d14f0 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_pause_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Pause +# 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_OrganizationRollouts_Pause_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_pause(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.PauseOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_Pause_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_resume_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_resume_sync.py new file mode 100644 index 000000000000..d6f58499fb88 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_organization_rollouts_resume_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Resume +# 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_OrganizationRollouts_Resume_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_resume(): + # Create a client + client = compute_v1beta.OrganizationRolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ResumeOrganizationRolloutRequest( + organization="organization_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_OrganizationRollouts_Resume_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_project_views_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_project_views_get_sync.py new file mode 100644 index 000000000000..9bcc67b88eb4 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_project_views_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_ProjectViews_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.ProjectViewsClient() + + # Initialize request argument(s) + request = compute_v1beta.GetProjectViewRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_ProjectViews_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reliability_risks_get_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reliability_risks_get_sync.py new file mode 100644 index 000000000000..6f14d5e58ded --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reliability_risks_get_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_ReliabilityRisks_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.ReliabilityRisksClient() + + # Initialize request argument(s) + request = compute_v1beta.GetReliabilityRiskRequest( + project="project_value", + reliability_risk="reliability_risk_value", + ) + + # Make the request + response = client.get(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_ReliabilityRisks_Get_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reliability_risks_list_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reliability_risks_list_sync.py new file mode 100644 index 000000000000..fe10d6b5e0e0 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_reliability_risks_list_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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_ReliabilityRisks_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.ReliabilityRisksClient() + + # Initialize request argument(s) + request = compute_v1beta.ListReliabilityRisksRequest( + project="project_value", + ) + + # Make the request + page_result = client.list(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1beta_generated_ReliabilityRisks_List_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_advance_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_advance_sync.py new file mode 100644 index 000000000000..1bc5c1598878 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_advance_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Advance +# 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_Rollouts_Advance_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_advance(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.AdvanceRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_Rollouts_Advance_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_pause_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_pause_sync.py new file mode 100644 index 000000000000..009826f95565 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_pause_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Pause +# 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_Rollouts_Pause_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_pause(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.PauseRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_Rollouts_Pause_sync] diff --git a/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_resume_sync.py b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_resume_sync.py new file mode 100644 index 000000000000..f0dfe4e5bbbb --- /dev/null +++ b/packages/google-cloud-compute-v1beta/samples/generated_samples/compute_v1beta_generated_rollouts_resume_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Resume +# 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_Rollouts_Resume_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_resume(): + # Create a client + client = compute_v1beta.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1beta.ResumeRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + +# [END compute_v1beta_generated_Rollouts_Resume_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 ff8d251ae2f2..b22598cc025d 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 @@ -15627,22 +15627,22 @@ "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.ImageFamilyViewsClient", - "shortName": "ImageFamilyViewsClient" + "fullName": "google.cloud.compute_v1beta.HostsClient", + "shortName": "HostsClient" }, - "fullName": "google.cloud.compute_v1beta.ImageFamilyViewsClient.get", + "fullName": "google.cloud.compute_v1beta.HostsClient.get_version", "method": { - "fullName": "google.cloud.compute.v1beta.ImageFamilyViews.Get", + "fullName": "google.cloud.compute.v1beta.Hosts.GetVersion", "service": { - "fullName": "google.cloud.compute.v1beta.ImageFamilyViews", - "shortName": "ImageFamilyViews" + "fullName": "google.cloud.compute.v1beta.Hosts", + "shortName": "Hosts" }, - "shortName": "Get" + "shortName": "GetVersion" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetImageFamilyViewRequest" + "type": "google.cloud.compute_v1beta.types.GetVersionHostRequest" }, { "name": "project", @@ -15653,9 +15653,17 @@ "type": "str" }, { - "name": "family", + "name": "association", "type": "str" }, + { + "name": "host", + "type": "str" + }, + { + "name": "hosts_get_version_request_resource", + "type": "google.cloud.compute_v1beta.types.HostsGetVersionRequest" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -15669,22 +15677,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.ImageFamilyView", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "get_version" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_image_family_views_get_sync.py", + "description": "Sample for GetVersion", + "file": "compute_v1beta_generated_hosts_get_version_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_ImageFamilyViews_Get_sync", + "regionTag": "compute_v1beta_generated_Hosts_GetVersion_sync", "segments": [ { - "end": 53, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 54, "start": 27, "type": "SHORT" }, @@ -15694,50 +15702,58 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 54, - "start": 51, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_image_family_views_get_sync.py" + "title": "compute_v1beta_generated_hosts_get_version_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.ImagesClient", - "shortName": "ImagesClient" + "fullName": "google.cloud.compute_v1beta.HostsClient", + "shortName": "HostsClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.delete", + "fullName": "google.cloud.compute_v1beta.HostsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.Images.Delete", + "fullName": "google.cloud.compute.v1beta.Hosts.Get", "service": { - "fullName": "google.cloud.compute.v1beta.Images", - "shortName": "Images" + "fullName": "google.cloud.compute.v1beta.Hosts", + "shortName": "Hosts" }, - "shortName": "Delete" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteImageRequest" + "type": "google.cloud.compute_v1beta.types.GetHostRequest" }, { "name": "project", "type": "str" }, { - "name": "image", + "name": "zone", + "type": "str" + }, + { + "name": "association", + "type": "str" + }, + { + "name": "host", "type": "str" }, { @@ -15753,22 +15769,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1beta.types.Host", + "shortName": "get" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_images_delete_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_hosts_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_Delete_sync", + "regionTag": "compute_v1beta_generated_Hosts_Get_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -15778,55 +15794,55 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 48, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 51, + "start": 49, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_delete_sync.py" + "title": "compute_v1beta_generated_hosts_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.ImagesClient", - "shortName": "ImagesClient" + "fullName": "google.cloud.compute_v1beta.HostsClient", + "shortName": "HostsClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.deprecate", + "fullName": "google.cloud.compute_v1beta.HostsClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.Images.Deprecate", + "fullName": "google.cloud.compute.v1beta.Hosts.List", "service": { - "fullName": "google.cloud.compute.v1beta.Images", - "shortName": "Images" + "fullName": "google.cloud.compute.v1beta.Hosts", + "shortName": "Hosts" }, - "shortName": "Deprecate" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeprecateImageRequest" + "type": "google.cloud.compute_v1beta.types.ListHostsRequest" }, { "name": "project", "type": "str" }, { - "name": "image", + "name": "zone", "type": "str" }, { - "name": "deprecation_status_resource", - "type": "google.cloud.compute_v1beta.types.DeprecationStatus" + "name": "association", + "type": "str" }, { "name": "retry", @@ -15841,22 +15857,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "deprecate" + "resultType": "google.cloud.compute_v1beta.services.hosts.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Deprecate", - "file": "compute_v1beta_generated_images_deprecate_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_hosts_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_Deprecate_sync", + "regionTag": "compute_v1beta_generated_Hosts_List_sync", "segments": [ { - "end": 52, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 54, "start": 27, "type": "SHORT" }, @@ -15866,48 +15882,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 55, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_deprecate_sync.py" + "title": "compute_v1beta_generated_hosts_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.ImagesClient", - "shortName": "ImagesClient" + "fullName": "google.cloud.compute_v1beta.ImageFamilyViewsClient", + "shortName": "ImageFamilyViewsClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.get_from_family", + "fullName": "google.cloud.compute_v1beta.ImageFamilyViewsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.Images.GetFromFamily", + "fullName": "google.cloud.compute.v1beta.ImageFamilyViews.Get", "service": { - "fullName": "google.cloud.compute.v1beta.Images", - "shortName": "Images" + "fullName": "google.cloud.compute.v1beta.ImageFamilyViews", + "shortName": "ImageFamilyViews" }, - "shortName": "GetFromFamily" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetFromFamilyImageRequest" + "type": "google.cloud.compute_v1beta.types.GetImageFamilyViewRequest" }, { "name": "project", "type": "str" }, + { + "name": "zone", + "type": "str" + }, { "name": "family", "type": "str" @@ -15925,22 +15945,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Image", - "shortName": "get_from_family" + "resultType": "google.cloud.compute_v1beta.types.ImageFamilyView", + "shortName": "get" }, - "description": "Sample for GetFromFamily", - "file": "compute_v1beta_generated_images_get_from_family_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_image_family_views_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_GetFromFamily_sync", + "regionTag": "compute_v1beta_generated_ImageFamilyViews_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -15950,50 +15970,54 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_get_from_family_sync.py" + "title": "compute_v1beta_generated_image_family_views_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.ImagesClient", - "shortName": "ImagesClient" + "fullName": "google.cloud.compute_v1beta.ImageViewsClient", + "shortName": "ImageViewsClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.get_iam_policy", + "fullName": "google.cloud.compute_v1beta.ImageViewsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.Images.GetIamPolicy", + "fullName": "google.cloud.compute.v1beta.ImageViews.Get", "service": { - "fullName": "google.cloud.compute.v1beta.Images", - "shortName": "Images" + "fullName": "google.cloud.compute.v1beta.ImageViews", + "shortName": "ImageViews" }, - "shortName": "GetIamPolicy" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetIamPolicyImageRequest" + "type": "google.cloud.compute_v1beta.types.GetImageViewRequest" }, { "name": "project", "type": "str" }, { - "name": "resource", + "name": "region", + "type": "str" + }, + { + "name": "resource_id", "type": "str" }, { @@ -16009,22 +16033,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Policy", - "shortName": "get_iam_policy" + "resultType": "google.cloud.compute_v1beta.types.ImageView", + "shortName": "get" }, - "description": "Sample for GetIamPolicy", - "file": "compute_v1beta_generated_images_get_iam_policy_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_image_views_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_GetIamPolicy_sync", + "regionTag": "compute_v1beta_generated_ImageViews_Get_sync", "segments": [ { - "end": 52, + "end": 53, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 53, "start": 27, "type": "SHORT" }, @@ -16034,22 +16058,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 47, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 50, + "start": 48, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 54, + "start": 51, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_get_iam_policy_sync.py" + "title": "compute_v1beta_generated_image_views_get_sync.py" }, { "canonical": true, @@ -16058,19 +16082,19 @@ "fullName": "google.cloud.compute_v1beta.ImagesClient", "shortName": "ImagesClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.get", + "fullName": "google.cloud.compute_v1beta.ImagesClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.Images.Get", + "fullName": "google.cloud.compute.v1beta.Images.Delete", "service": { "fullName": "google.cloud.compute.v1beta.Images", "shortName": "Images" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetImageRequest" + "type": "google.cloud.compute_v1beta.types.DeleteImageRequest" }, { "name": "project", @@ -16093,14 +16117,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Image", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_images_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_images_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_Get_sync", + "regionTag": "compute_v1beta_generated_Images_Delete_sync", "segments": [ { "end": 52, @@ -16133,7 +16157,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_get_sync.py" + "title": "compute_v1beta_generated_images_delete_sync.py" }, { "canonical": true, @@ -16142,27 +16166,31 @@ "fullName": "google.cloud.compute_v1beta.ImagesClient", "shortName": "ImagesClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.insert", + "fullName": "google.cloud.compute_v1beta.ImagesClient.deprecate", "method": { - "fullName": "google.cloud.compute.v1beta.Images.Insert", + "fullName": "google.cloud.compute.v1beta.Images.Deprecate", "service": { "fullName": "google.cloud.compute.v1beta.Images", "shortName": "Images" }, - "shortName": "Insert" + "shortName": "Deprecate" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertImageRequest" + "type": "google.cloud.compute_v1beta.types.DeprecateImageRequest" }, { "name": "project", "type": "str" }, { - "name": "image_resource", - "type": "google.cloud.compute_v1beta.types.Image" + "name": "image", + "type": "str" + }, + { + "name": "deprecation_status_resource", + "type": "google.cloud.compute_v1beta.types.DeprecationStatus" }, { "name": "retry", @@ -16178,21 +16206,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "shortName": "deprecate" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_images_insert_sync.py", + "description": "Sample for Deprecate", + "file": "compute_v1beta_generated_images_deprecate_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_Insert_sync", + "regionTag": "compute_v1beta_generated_Images_Deprecate_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -16202,22 +16230,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_insert_sync.py" + "title": "compute_v1beta_generated_images_deprecate_sync.py" }, { "canonical": true, @@ -16226,24 +16254,28 @@ "fullName": "google.cloud.compute_v1beta.ImagesClient", "shortName": "ImagesClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.list", + "fullName": "google.cloud.compute_v1beta.ImagesClient.get_from_family", "method": { - "fullName": "google.cloud.compute.v1beta.Images.List", + "fullName": "google.cloud.compute.v1beta.Images.GetFromFamily", "service": { "fullName": "google.cloud.compute.v1beta.Images", "shortName": "Images" }, - "shortName": "List" + "shortName": "GetFromFamily" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListImagesRequest" + "type": "google.cloud.compute_v1beta.types.GetFromFamilyImageRequest" }, { "name": "project", "type": "str" }, + { + "name": "family", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16257,14 +16289,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.images.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1beta.types.Image", + "shortName": "get_from_family" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_images_list_sync.py", + "description": "Sample for GetFromFamily", + "file": "compute_v1beta_generated_images_get_from_family_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_List_sync", + "regionTag": "compute_v1beta_generated_Images_GetFromFamily_sync", "segments": [ { "end": 52, @@ -16282,22 +16314,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_images_list_sync.py" + "title": "compute_v1beta_generated_images_get_from_family_sync.py" }, { "canonical": true, @@ -16306,32 +16338,28 @@ "fullName": "google.cloud.compute_v1beta.ImagesClient", "shortName": "ImagesClient" }, - "fullName": "google.cloud.compute_v1beta.ImagesClient.patch", + "fullName": "google.cloud.compute_v1beta.ImagesClient.get_iam_policy", "method": { - "fullName": "google.cloud.compute.v1beta.Images.Patch", + "fullName": "google.cloud.compute.v1beta.Images.GetIamPolicy", "service": { "fullName": "google.cloud.compute.v1beta.Images", "shortName": "Images" }, - "shortName": "Patch" + "shortName": "GetIamPolicy" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchImageRequest" + "type": "google.cloud.compute_v1beta.types.GetIamPolicyImageRequest" }, { "name": "project", "type": "str" }, { - "name": "image", + "name": "resource", "type": "str" }, - { - "name": "image_resource", - "type": "google.cloud.compute_v1beta.types.Image" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -16345,14 +16373,350 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" + "resultType": "google.cloud.compute_v1beta.types.Policy", + "shortName": "get_iam_policy" }, - "description": "Sample for Patch", - "file": "compute_v1beta_generated_images_patch_sync.py", + "description": "Sample for GetIamPolicy", + "file": "compute_v1beta_generated_images_get_iam_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Images_Patch_sync", + "regionTag": "compute_v1beta_generated_Images_GetIamPolicy_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_images_get_iam_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ImagesClient", + "shortName": "ImagesClient" + }, + "fullName": "google.cloud.compute_v1beta.ImagesClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.Images.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.Images", + "shortName": "Images" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "image", + "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.Image", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_images_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Images_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_images_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ImagesClient", + "shortName": "ImagesClient" + }, + "fullName": "google.cloud.compute_v1beta.ImagesClient.insert", + "method": { + "fullName": "google.cloud.compute.v1beta.Images.Insert", + "service": { + "fullName": "google.cloud.compute.v1beta.Images", + "shortName": "Images" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.InsertImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "image_resource", + "type": "google.cloud.compute_v1beta.types.Image" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1beta_generated_images_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Images_Insert_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_images_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ImagesClient", + "shortName": "ImagesClient" + }, + "fullName": "google.cloud.compute_v1beta.ImagesClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.Images.List", + "service": { + "fullName": "google.cloud.compute.v1beta.Images", + "shortName": "Images" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListImagesRequest" + }, + { + "name": "project", + "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.images.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_images_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Images_List_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_images_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ImagesClient", + "shortName": "ImagesClient" + }, + "fullName": "google.cloud.compute_v1beta.ImagesClient.patch", + "method": { + "fullName": "google.cloud.compute.v1beta.Images.Patch", + "service": { + "fullName": "google.cloud.compute.v1beta.Images", + "shortName": "Images" + }, + "shortName": "Patch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.PatchImageRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "image", + "type": "str" + }, + { + "name": "image_resource", + "type": "google.cloud.compute_v1beta.types.Image" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" + }, + "description": "Sample for Patch", + "file": "compute_v1beta_generated_images_patch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Images_Patch_sync", "segments": [ { "end": 52, @@ -40875,30 +41239,30 @@ "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient", + "shortName": "OrganizationRolloutPlansClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.add_association", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.AddAssociation", + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "shortName": "OrganizationRolloutPlans" }, - "shortName": "AddAssociation" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.AddAssociationOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.DeleteOrganizationRolloutPlanRequest" }, { - "name": "security_policy", + "name": "organization", "type": "str" }, { - "name": "security_policy_association_resource", - "type": "google.cloud.compute_v1beta.types.SecurityPolicyAssociation" + "name": "rollout_plan", + "type": "str" }, { "name": "retry", @@ -40914,21 +41278,21 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_association" + "shortName": "delete" }, - "description": "Sample for AddAssociation", - "file": "compute_v1beta_generated_organization_security_policies_add_association_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_organization_rollout_plans_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_AddAssociation_sync", + "regionTag": "compute_v1beta_generated_OrganizationRolloutPlans_Delete_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -40938,51 +41302,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_add_association_sync.py" + "title": "compute_v1beta_generated_organization_rollout_plans_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient", + "shortName": "OrganizationRolloutPlansClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.add_rule", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.AddRule", + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans.Get", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "shortName": "OrganizationRolloutPlans" }, - "shortName": "AddRule" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.AddRuleOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.GetOrganizationRolloutPlanRequest" }, { - "name": "security_policy", + "name": "organization", "type": "str" }, { - "name": "security_policy_rule_resource", - "type": "google.cloud.compute_v1beta.types.SecurityPolicyRule" + "name": "rollout_plan", + "type": "str" }, { "name": "retry", @@ -40997,22 +41361,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "add_rule" + "resultType": "google.cloud.compute_v1beta.types.RolloutPlan", + "shortName": "get" }, - "description": "Sample for AddRule", - "file": "compute_v1beta_generated_organization_security_policies_add_rule_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_organization_rollout_plans_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_AddRule_sync", + "regionTag": "compute_v1beta_generated_OrganizationRolloutPlans_Get_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41022,48 +41386,52 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_add_rule_sync.py" + "title": "compute_v1beta_generated_organization_rollout_plans_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient", + "shortName": "OrganizationRolloutPlansClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.copy_rules", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.CopyRules", + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans.Insert", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "shortName": "OrganizationRolloutPlans" }, - "shortName": "CopyRules" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.CopyRulesOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.InsertOrganizationRolloutPlanRequest" }, { - "name": "security_policy", + "name": "organization", "type": "str" }, + { + "name": "rollout_plan_resource", + "type": "google.cloud.compute_v1beta.types.RolloutPlan" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -41078,13 +41446,13 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "copy_rules" + "shortName": "insert" }, - "description": "Sample for CopyRules", - "file": "compute_v1beta_generated_organization_security_policies_copy_rules_sync.py", + "description": "Sample for Insert", + "file": "compute_v1beta_generated_organization_rollout_plans_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_CopyRules_sync", + "regionTag": "compute_v1beta_generated_OrganizationRolloutPlans_Insert_sync", "segments": [ { "end": 51, @@ -41117,31 +41485,31 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_copy_rules_sync.py" + "title": "compute_v1beta_generated_organization_rollout_plans_insert_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient", + "shortName": "OrganizationRolloutPlansClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.delete", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutPlansClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Delete", + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans.List", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRolloutPlans", + "shortName": "OrganizationRolloutPlans" }, - "shortName": "Delete" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.DeleteOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.ListOrganizationRolloutPlansRequest" }, { - "name": "security_policy", + "name": "organization", "type": "str" }, { @@ -41157,22 +41525,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1beta.services.organization_rollout_plans.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_organization_security_policies_delete_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_organization_rollout_plans_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Delete_sync", + "regionTag": "compute_v1beta_generated_OrganizationRolloutPlans_List_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41192,36 +41560,40 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_delete_sync.py" + "title": "compute_v1beta_generated_organization_rollout_plans_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.get_association", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.advance", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.GetAssociation", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.Advance", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "GetAssociation" + "shortName": "Advance" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetAssociationOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.AdvanceOrganizationRolloutRequest" }, { - "name": "security_policy", + "name": "organization", + "type": "str" + }, + { + "name": "rollout", "type": "str" }, { @@ -41237,22 +41609,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.SecurityPolicyAssociation", - "shortName": "get_association" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "advance" }, - "description": "Sample for GetAssociation", - "file": "compute_v1beta_generated_organization_security_policies_get_association_sync.py", + "description": "Sample for Advance", + "file": "compute_v1beta_generated_organization_rollouts_advance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_GetAssociation_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_Advance_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41262,46 +41634,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_get_association_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_advance_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.get_rule", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.cancel", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.GetRule", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.Cancel", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "GetRule" + "shortName": "Cancel" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRuleOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.CancelOrganizationRolloutRequest" }, { - "name": "security_policy", + "name": "organization", + "type": "str" + }, + { + "name": "rollout", "type": "str" }, { @@ -41317,22 +41693,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.SecurityPolicyRule", - "shortName": "get_rule" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "cancel" }, - "description": "Sample for GetRule", - "file": "compute_v1beta_generated_organization_security_policies_get_rule_sync.py", + "description": "Sample for Cancel", + "file": "compute_v1beta_generated_organization_rollouts_cancel_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_GetRule_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_Cancel_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41342,46 +41718,50 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_get_rule_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_cancel_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.get", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.delete", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Get", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.Delete", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "Get" + "shortName": "Delete" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.DeleteOrganizationRolloutRequest" }, { - "name": "security_policy", + "name": "organization", + "type": "str" + }, + { + "name": "rollout", "type": "str" }, { @@ -41397,22 +41777,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.SecurityPolicy", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_organization_security_policies_get_sync.py", + "description": "Sample for Delete", + "file": "compute_v1beta_generated_organization_rollouts_delete_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Get_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_Delete_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41422,47 +41802,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_get_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_delete_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.insert", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Insert", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.Get", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "Insert" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.GetOrganizationRolloutRequest" }, { - "name": "security_policy_resource", - "type": "google.cloud.compute_v1beta.types.SecurityPolicy" + "name": "organization", + "type": "str" + }, + { + "name": "rollout", + "type": "str" }, { "name": "retry", @@ -41477,22 +41861,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1beta.types.Rollout", + "shortName": "get" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_organization_security_policies_insert_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_organization_rollouts_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Insert_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_Get_sync", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41502,43 +41886,47 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_insert_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.list_associations", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.ListAssociations", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.List", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "ListAssociations" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListAssociationsOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.ListOrganizationRolloutsRequest" + }, + { + "name": "organization", + "type": "str" }, { "name": "retry", @@ -41553,22 +41941,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.OrganizationSecurityPoliciesListAssociationsResponse", - "shortName": "list_associations" + "resultType": "google.cloud.compute_v1beta.services.organization_rollouts.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for ListAssociations", - "file": "compute_v1beta_generated_organization_security_policies_list_associations_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_organization_rollouts_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_ListAssociations_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_List_sync", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41578,43 +41966,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_list_associations_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.list_preconfigured_expression_sets", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.pause", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.ListPreconfiguredExpressionSets", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.Pause", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "ListPreconfiguredExpressionSets" + "shortName": "Pause" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest" + "type": "google.cloud.compute_v1beta.types.PauseOrganizationRolloutRequest" + }, + { + "name": "organization", + "type": "str" + }, + { + "name": "rollout", + "type": "str" }, { "name": "retry", @@ -41629,22 +42025,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.SecurityPoliciesListPreconfiguredExpressionSetsResponse", - "shortName": "list_preconfigured_expression_sets" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "pause" }, - "description": "Sample for ListPreconfiguredExpressionSets", - "file": "compute_v1beta_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py", + "description": "Sample for Pause", + "file": "compute_v1beta_generated_organization_rollouts_pause_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_ListPreconfiguredExpressionSets_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_Pause_sync", "segments": [ { - "end": 50, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 50, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41654,43 +42050,51 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 51, - "start": 48, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_pause_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", - "shortName": "OrganizationSecurityPoliciesClient" + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient", + "shortName": "OrganizationRolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.list", + "fullName": "google.cloud.compute_v1beta.OrganizationRolloutsClient.resume", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.List", + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts.Resume", "service": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", - "shortName": "OrganizationSecurityPolicies" + "fullName": "google.cloud.compute.v1beta.OrganizationRollouts", + "shortName": "OrganizationRollouts" }, - "shortName": "List" + "shortName": "Resume" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListOrganizationSecurityPoliciesRequest" + "type": "google.cloud.compute_v1beta.types.ResumeOrganizationRolloutRequest" + }, + { + "name": "organization", + "type": "str" + }, + { + "name": "rollout", + "type": "str" }, { "name": "retry", @@ -41705,22 +42109,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.organization_security_policies.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "resume" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_organization_security_policies_list_sync.py", + "description": "Sample for Resume", + "file": "compute_v1beta_generated_organization_rollouts_resume_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_List_sync", + "regionTag": "compute_v1beta_generated_OrganizationRollouts_Resume_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -41730,22 +42134,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 44, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 47, - "start": 45, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 48, + "end": 53, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_organization_security_policies_list_sync.py" + "title": "compute_v1beta_generated_organization_rollouts_resume_sync.py" }, { "canonical": true, @@ -41754,24 +42158,28 @@ "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", "shortName": "OrganizationSecurityPoliciesClient" }, - "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.move", + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.add_association", "method": { - "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Move", + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.AddAssociation", "service": { "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", "shortName": "OrganizationSecurityPolicies" }, - "shortName": "Move" + "shortName": "AddAssociation" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.MoveOrganizationSecurityPolicyRequest" + "type": "google.cloud.compute_v1beta.types.AddAssociationOrganizationSecurityPolicyRequest" }, { "name": "security_policy", "type": "str" }, + { + "name": "security_policy_association_resource", + "type": "google.cloud.compute_v1beta.types.SecurityPolicyAssociation" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -41786,13 +42194,885 @@ } ], "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "move" + "shortName": "add_association" }, - "description": "Sample for Move", - "file": "compute_v1beta_generated_organization_security_policies_move_sync.py", + "description": "Sample for AddAssociation", + "file": "compute_v1beta_generated_organization_security_policies_add_association_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Move_sync", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_AddAssociation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_add_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.add_rule", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.AddRule", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "AddRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.AddRuleOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "type": "str" + }, + { + "name": "security_policy_rule_resource", + "type": "google.cloud.compute_v1beta.types.SecurityPolicyRule" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "add_rule" + }, + "description": "Sample for AddRule", + "file": "compute_v1beta_generated_organization_security_policies_add_rule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_AddRule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_add_rule_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.copy_rules", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.CopyRules", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "CopyRules" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.CopyRulesOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "copy_rules" + }, + "description": "Sample for CopyRules", + "file": "compute_v1beta_generated_organization_security_policies_copy_rules_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_CopyRules_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_copy_rules_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.delete", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Delete", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.DeleteOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" + }, + "description": "Sample for Delete", + "file": "compute_v1beta_generated_organization_security_policies_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Delete_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.get_association", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.GetAssociation", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "GetAssociation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetAssociationOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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.SecurityPolicyAssociation", + "shortName": "get_association" + }, + "description": "Sample for GetAssociation", + "file": "compute_v1beta_generated_organization_security_policies_get_association_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_GetAssociation_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_get_association_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.get_rule", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.GetRule", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "GetRule" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetRuleOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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.SecurityPolicyRule", + "shortName": "get_rule" + }, + "description": "Sample for GetRule", + "file": "compute_v1beta_generated_organization_security_policies_get_rule_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_GetRule_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_get_rule_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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.SecurityPolicy", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_organization_security_policies_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Get_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_get_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.insert", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Insert", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Insert" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.InsertOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy_resource", + "type": "google.cloud.compute_v1beta.types.SecurityPolicy" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" + }, + "description": "Sample for Insert", + "file": "compute_v1beta_generated_organization_security_policies_insert_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Insert_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.list_associations", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.ListAssociations", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "ListAssociations" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListAssociationsOrganizationSecurityPolicyRequest" + }, + { + "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.OrganizationSecurityPoliciesListAssociationsResponse", + "shortName": "list_associations" + }, + "description": "Sample for ListAssociations", + "file": "compute_v1beta_generated_organization_security_policies_list_associations_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_ListAssociations_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_list_associations_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.list_preconfigured_expression_sets", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.ListPreconfiguredExpressionSets", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "ListPreconfiguredExpressionSets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest" + }, + { + "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.SecurityPoliciesListPreconfiguredExpressionSetsResponse", + "shortName": "list_preconfigured_expression_sets" + }, + "description": "Sample for ListPreconfiguredExpressionSets", + "file": "compute_v1beta_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_ListPreconfiguredExpressionSets_sync", + "segments": [ + { + "end": 50, + "start": 27, + "type": "FULL" + }, + { + "end": 50, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 51, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_list_preconfigured_expression_sets_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.List", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListOrganizationSecurityPoliciesRequest" + }, + { + "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.organization_security_policies.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_organization_security_policies_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_List_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 44, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 47, + "start": 45, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 48, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_organization_security_policies_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient", + "shortName": "OrganizationSecurityPoliciesClient" + }, + "fullName": "google.cloud.compute_v1beta.OrganizationSecurityPoliciesClient.move", + "method": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies.Move", + "service": { + "fullName": "google.cloud.compute.v1beta.OrganizationSecurityPolicies", + "shortName": "OrganizationSecurityPolicies" + }, + "shortName": "Move" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.MoveOrganizationSecurityPolicyRequest" + }, + { + "name": "security_policy", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "move" + }, + "description": "Sample for Move", + "file": "compute_v1beta_generated_organization_security_policies_move_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_OrganizationSecurityPolicies_Move_sync", "segments": [ { "end": 51, @@ -42497,37 +43777,385 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_packet_mirrorings_insert_sync.py" + "title": "compute_v1beta_generated_packet_mirrorings_insert_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient.list", + "method": { + "fullName": "google.cloud.compute.v1beta.PacketMirrorings.List", + "service": { + "fullName": "google.cloud.compute.v1beta.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListPacketMirroringsRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "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.packet_mirrorings.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_packet_mirrorings_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_PacketMirrorings_List_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_packet_mirrorings_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient.patch", + "method": { + "fullName": "google.cloud.compute.v1beta.PacketMirrorings.Patch", + "service": { + "fullName": "google.cloud.compute.v1beta.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "Patch" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.PatchPacketMirroringRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "packet_mirroring", + "type": "str" + }, + { + "name": "packet_mirroring_resource", + "type": "google.cloud.compute_v1beta.types.PacketMirroring" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch" + }, + "description": "Sample for Patch", + "file": "compute_v1beta_generated_packet_mirrorings_patch_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_PacketMirrorings_Patch_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_packet_mirrorings_patch_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient", + "shortName": "PacketMirroringsClient" + }, + "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient.test_iam_permissions", + "method": { + "fullName": "google.cloud.compute.v1beta.PacketMirrorings.TestIamPermissions", + "service": { + "fullName": "google.cloud.compute.v1beta.PacketMirrorings", + "shortName": "PacketMirrorings" + }, + "shortName": "TestIamPermissions" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.TestIamPermissionsPacketMirroringRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "resource", + "type": "str" + }, + { + "name": "test_permissions_request_resource", + "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" + }, + { + "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.TestPermissionsResponse", + "shortName": "test_iam_permissions" + }, + "description": "Sample for TestIamPermissions", + "file": "compute_v1beta_generated_packet_mirrorings_test_iam_permissions_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_PacketMirrorings_TestIamPermissions_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_packet_mirrorings_test_iam_permissions_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient", + "shortName": "PreviewFeaturesClient" + }, + "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.PreviewFeatures.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.PreviewFeatures", + "shortName": "PreviewFeatures" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetPreviewFeatureRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "preview_feature", + "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.PreviewFeature", + "shortName": "get" + }, + "description": "Sample for Get", + "file": "compute_v1beta_generated_preview_features_get_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_PreviewFeatures_Get_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_preview_features_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" + "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient", + "shortName": "PreviewFeaturesClient" }, - "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient.list", + "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.PacketMirrorings.List", + "fullName": "google.cloud.compute.v1beta.PreviewFeatures.List", "service": { - "fullName": "google.cloud.compute.v1beta.PacketMirrorings", - "shortName": "PacketMirrorings" + "fullName": "google.cloud.compute.v1beta.PreviewFeatures", + "shortName": "PreviewFeatures" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListPacketMirroringsRequest" + "type": "google.cloud.compute_v1beta.types.ListPreviewFeaturesRequest" }, { "name": "project", "type": "str" }, - { - "name": "region", - "type": "str" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -42541,114 +44169,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.packet_mirrorings.pagers.ListPager", + "resultType": "google.cloud.compute_v1beta.services.preview_features.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1beta_generated_packet_mirrorings_list_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_PacketMirrorings_List_sync", - "segments": [ - { - "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 46, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 49, - "start": 47, - "type": "REQUEST_EXECUTION" - }, - { - "end": 54, - "start": 50, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1beta_generated_packet_mirrorings_list_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" - }, - "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient.patch", - "method": { - "fullName": "google.cloud.compute.v1beta.PacketMirrorings.Patch", - "service": { - "fullName": "google.cloud.compute.v1beta.PacketMirrorings", - "shortName": "PacketMirrorings" - }, - "shortName": "Patch" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1beta.types.PatchPacketMirroringRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "region", - "type": "str" - }, - { - "name": "packet_mirroring", - "type": "str" - }, - { - "name": "packet_mirroring_resource", - "type": "google.cloud.compute_v1beta.types.PacketMirroring" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" - }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "patch" - }, - "description": "Sample for Patch", - "file": "compute_v1beta_generated_packet_mirrorings_patch_sync.py", + "file": "compute_v1beta_generated_preview_features_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_PacketMirrorings_Patch_sync", + "regionTag": "compute_v1beta_generated_PreviewFeatures_List_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -42658,114 +44194,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, - { - "end": 54, - "start": 51, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1beta_generated_packet_mirrorings_patch_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient", - "shortName": "PacketMirroringsClient" - }, - "fullName": "google.cloud.compute_v1beta.PacketMirroringsClient.test_iam_permissions", - "method": { - "fullName": "google.cloud.compute.v1beta.PacketMirrorings.TestIamPermissions", - "service": { - "fullName": "google.cloud.compute.v1beta.PacketMirrorings", - "shortName": "PacketMirrorings" - }, - "shortName": "TestIamPermissions" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1beta.types.TestIamPermissionsPacketMirroringRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "region", - "type": "str" - }, - { - "name": "resource", - "type": "str" - }, - { - "name": "test_permissions_request_resource", - "type": "google.cloud.compute_v1beta.types.TestPermissionsRequest" - }, - { - "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.TestPermissionsResponse", - "shortName": "test_iam_permissions" - }, - "description": "Sample for TestIamPermissions", - "file": "compute_v1beta_generated_packet_mirrorings_test_iam_permissions_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_PacketMirrorings_TestIamPermissions_sync", - "segments": [ { "end": 53, - "start": 27, - "type": "FULL" - }, - { - "end": 53, - "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": 54, - "start": 51, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_packet_mirrorings_test_iam_permissions_sync.py" + "title": "compute_v1beta_generated_preview_features_list_sync.py" }, { "canonical": true, @@ -42774,19 +44218,19 @@ "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient", "shortName": "PreviewFeaturesClient" }, - "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient.get", + "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient.update", "method": { - "fullName": "google.cloud.compute.v1beta.PreviewFeatures.Get", + "fullName": "google.cloud.compute.v1beta.PreviewFeatures.Update", "service": { "fullName": "google.cloud.compute.v1beta.PreviewFeatures", "shortName": "PreviewFeatures" }, - "shortName": "Get" + "shortName": "Update" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetPreviewFeatureRequest" + "type": "google.cloud.compute_v1beta.types.UpdatePreviewFeatureRequest" }, { "name": "project", @@ -42796,6 +44240,10 @@ "name": "preview_feature", "type": "str" }, + { + "name": "preview_feature_resource", + "type": "google.cloud.compute_v1beta.types.PreviewFeature" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -42809,14 +44257,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.PreviewFeature", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_preview_features_get_sync.py", + "description": "Sample for Update", + "file": "compute_v1beta_generated_preview_features_update_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_PreviewFeatures_Get_sync", + "regionTag": "compute_v1beta_generated_PreviewFeatures_Update_sync", "segments": [ { "end": 52, @@ -42849,121 +44297,37 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_preview_features_get_sync.py" + "title": "compute_v1beta_generated_preview_features_update_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient", - "shortName": "PreviewFeaturesClient" + "fullName": "google.cloud.compute_v1beta.ProjectViewsClient", + "shortName": "ProjectViewsClient" }, - "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient.list", + "fullName": "google.cloud.compute_v1beta.ProjectViewsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.PreviewFeatures.List", + "fullName": "google.cloud.compute.v1beta.ProjectViews.Get", "service": { - "fullName": "google.cloud.compute.v1beta.PreviewFeatures", - "shortName": "PreviewFeatures" - }, - "shortName": "List" - }, - "parameters": [ - { - "name": "request", - "type": "google.cloud.compute_v1beta.types.ListPreviewFeaturesRequest" - }, - { - "name": "project", - "type": "str" - }, - { - "name": "retry", - "type": "google.api_core.retry.Retry" - }, - { - "name": "timeout", - "type": "float" + "fullName": "google.cloud.compute.v1beta.ProjectViews", + "shortName": "ProjectViews" }, - { - "name": "metadata", - "type": "Sequence[Tuple[str, Union[str, bytes]]]" - } - ], - "resultType": "google.cloud.compute_v1beta.services.preview_features.pagers.ListPager", - "shortName": "list" - }, - "description": "Sample for List", - "file": "compute_v1beta_generated_preview_features_list_sync.py", - "language": "PYTHON", - "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_PreviewFeatures_List_sync", - "segments": [ - { - "end": 52, - "start": 27, - "type": "FULL" - }, - { - "end": 52, - "start": 27, - "type": "SHORT" - }, - { - "end": 40, - "start": 38, - "type": "CLIENT_INITIALIZATION" - }, - { - "end": 45, - "start": 41, - "type": "REQUEST_INITIALIZATION" - }, - { - "end": 48, - "start": 46, - "type": "REQUEST_EXECUTION" - }, - { - "end": 53, - "start": 49, - "type": "RESPONSE_HANDLING" - } - ], - "title": "compute_v1beta_generated_preview_features_list_sync.py" - }, - { - "canonical": true, - "clientMethod": { - "client": { - "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient", - "shortName": "PreviewFeaturesClient" - }, - "fullName": "google.cloud.compute_v1beta.PreviewFeaturesClient.update", - "method": { - "fullName": "google.cloud.compute.v1beta.PreviewFeatures.Update", - "service": { - "fullName": "google.cloud.compute.v1beta.PreviewFeatures", - "shortName": "PreviewFeatures" - }, - "shortName": "Update" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.UpdatePreviewFeatureRequest" + "type": "google.cloud.compute_v1beta.types.GetProjectViewRequest" }, { "name": "project", "type": "str" }, { - "name": "preview_feature", + "name": "region", "type": "str" }, - { - "name": "preview_feature_resource", - "type": "google.cloud.compute_v1beta.types.PreviewFeature" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -42977,14 +44341,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "update" + "resultType": "google.cloud.compute_v1beta.types.ProjectView", + "shortName": "get" }, - "description": "Sample for Update", - "file": "compute_v1beta_generated_preview_features_update_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_project_views_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_PreviewFeatures_Update_sync", + "regionTag": "compute_v1beta_generated_ProjectViews_Get_sync", "segments": [ { "end": 52, @@ -43017,7 +44381,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_preview_features_update_sync.py" + "title": "compute_v1beta_generated_project_views_get_sync.py" }, { "canonical": true, @@ -69169,28 +70533,120 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_url_maps_update_sync.py" + "title": "compute_v1beta_generated_region_url_maps_update_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RegionUrlMapsClient", + "shortName": "RegionUrlMapsClient" + }, + "fullName": "google.cloud.compute_v1beta.RegionUrlMapsClient.validate", + "method": { + "fullName": "google.cloud.compute.v1beta.RegionUrlMaps.Validate", + "service": { + "fullName": "google.cloud.compute.v1beta.RegionUrlMaps", + "shortName": "RegionUrlMaps" + }, + "shortName": "Validate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ValidateRegionUrlMapRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "url_map", + "type": "str" + }, + { + "name": "region_url_maps_validate_request_resource", + "type": "google.cloud.compute_v1beta.types.RegionUrlMapsValidateRequest" + }, + { + "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.UrlMapsValidateResponse", + "shortName": "validate" + }, + "description": "Sample for Validate", + "file": "compute_v1beta_generated_region_url_maps_validate_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RegionUrlMaps_Validate_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_region_url_maps_validate_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionUrlMapsClient", - "shortName": "RegionUrlMapsClient" + "fullName": "google.cloud.compute_v1beta.RegionZonesClient", + "shortName": "RegionZonesClient" }, - "fullName": "google.cloud.compute_v1beta.RegionUrlMapsClient.validate", + "fullName": "google.cloud.compute_v1beta.RegionZonesClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RegionUrlMaps.Validate", + "fullName": "google.cloud.compute.v1beta.RegionZones.List", "service": { - "fullName": "google.cloud.compute.v1beta.RegionUrlMaps", - "shortName": "RegionUrlMaps" + "fullName": "google.cloud.compute.v1beta.RegionZones", + "shortName": "RegionZones" }, - "shortName": "Validate" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ValidateRegionUrlMapRequest" + "type": "google.cloud.compute_v1beta.types.ListRegionZonesRequest" }, { "name": "project", @@ -69200,14 +70656,6 @@ "name": "region", "type": "str" }, - { - "name": "url_map", - "type": "str" - }, - { - "name": "region_url_maps_validate_request_resource", - "type": "google.cloud.compute_v1beta.types.RegionUrlMapsValidateRequest" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -69221,14 +70669,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.UrlMapsValidateResponse", - "shortName": "validate" + "resultType": "google.cloud.compute_v1beta.services.region_zones.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Validate", - "file": "compute_v1beta_generated_region_url_maps_validate_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_region_zones_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionUrlMaps_Validate_sync", + "regionTag": "compute_v1beta_generated_RegionZones_List_sync", "segments": [ { "end": 53, @@ -69246,43 +70694,43 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 47, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 50, - "start": 48, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 54, - "start": 51, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_url_maps_validate_sync.py" + "title": "compute_v1beta_generated_region_zones_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionZonesClient", - "shortName": "RegionZonesClient" + "fullName": "google.cloud.compute_v1beta.RegionsClient", + "shortName": "RegionsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionZonesClient.list", + "fullName": "google.cloud.compute_v1beta.RegionsClient.get", "method": { - "fullName": "google.cloud.compute.v1beta.RegionZones.List", + "fullName": "google.cloud.compute.v1beta.Regions.Get", "service": { - "fullName": "google.cloud.compute.v1beta.RegionZones", - "shortName": "RegionZones" + "fullName": "google.cloud.compute.v1beta.Regions", + "shortName": "Regions" }, - "shortName": "List" + "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionZonesRequest" + "type": "google.cloud.compute_v1beta.types.GetRegionRequest" }, { "name": "project", @@ -69305,22 +70753,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.region_zones.pagers.ListPager", - "shortName": "list" + "resultType": "google.cloud.compute_v1beta.types.Region", + "shortName": "get" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_region_zones_list_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_regions_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RegionZones_List_sync", + "regionTag": "compute_v1beta_generated_Regions_Get_sync", "segments": [ { - "end": 53, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 53, + "end": 52, "start": 27, "type": "SHORT" }, @@ -69340,12 +70788,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 54, + "end": 53, "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_region_zones_list_sync.py" + "title": "compute_v1beta_generated_regions_get_sync.py" }, { "canonical": true, @@ -69354,26 +70802,106 @@ "fullName": "google.cloud.compute_v1beta.RegionsClient", "shortName": "RegionsClient" }, - "fullName": "google.cloud.compute_v1beta.RegionsClient.get", + "fullName": "google.cloud.compute_v1beta.RegionsClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.Regions.Get", + "fullName": "google.cloud.compute.v1beta.Regions.List", "service": { "fullName": "google.cloud.compute.v1beta.Regions", "shortName": "Regions" }, + "shortName": "List" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ListRegionsRequest" + }, + { + "name": "project", + "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.regions.pagers.ListPager", + "shortName": "list" + }, + "description": "Sample for List", + "file": "compute_v1beta_generated_regions_list_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Regions_List_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_regions_list_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.ReliabilityRisksClient", + "shortName": "ReliabilityRisksClient" + }, + "fullName": "google.cloud.compute_v1beta.ReliabilityRisksClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.ReliabilityRisks.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.ReliabilityRisks", + "shortName": "ReliabilityRisks" + }, "shortName": "Get" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRegionRequest" + "type": "google.cloud.compute_v1beta.types.GetReliabilityRiskRequest" }, { "name": "project", "type": "str" }, { - "name": "region", + "name": "reliability_risk", "type": "str" }, { @@ -69389,14 +70917,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.Region", + "resultType": "google.cloud.compute_v1beta.types.ReliabilityRisk", "shortName": "get" }, "description": "Sample for Get", - "file": "compute_v1beta_generated_regions_get_sync.py", + "file": "compute_v1beta_generated_reliability_risks_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Regions_Get_sync", + "regionTag": "compute_v1beta_generated_ReliabilityRisks_Get_sync", "segments": [ { "end": 52, @@ -69429,28 +70957,28 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_regions_get_sync.py" + "title": "compute_v1beta_generated_reliability_risks_get_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RegionsClient", - "shortName": "RegionsClient" + "fullName": "google.cloud.compute_v1beta.ReliabilityRisksClient", + "shortName": "ReliabilityRisksClient" }, - "fullName": "google.cloud.compute_v1beta.RegionsClient.list", + "fullName": "google.cloud.compute_v1beta.ReliabilityRisksClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.Regions.List", + "fullName": "google.cloud.compute.v1beta.ReliabilityRisks.List", "service": { - "fullName": "google.cloud.compute.v1beta.Regions", - "shortName": "Regions" + "fullName": "google.cloud.compute.v1beta.ReliabilityRisks", + "shortName": "ReliabilityRisks" }, "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRegionsRequest" + "type": "google.cloud.compute_v1beta.types.ListReliabilityRisksRequest" }, { "name": "project", @@ -69469,14 +70997,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.regions.pagers.ListPager", + "resultType": "google.cloud.compute_v1beta.services.reliability_risks.pagers.ListPager", "shortName": "list" }, "description": "Sample for List", - "file": "compute_v1beta_generated_regions_list_sync.py", + "file": "compute_v1beta_generated_reliability_risks_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_Regions_List_sync", + "regionTag": "compute_v1beta_generated_ReliabilityRisks_List_sync", "segments": [ { "end": 52, @@ -69509,7 +71037,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_regions_list_sync.py" + "title": "compute_v1beta_generated_reliability_risks_list_sync.py" }, { "canonical": true, @@ -73001,14 +74529,98 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" + }, + "description": "Sample for Delete", + "file": "compute_v1beta_generated_rollout_plans_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_RolloutPlans_Delete_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_rollout_plans_delete_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RolloutPlansClient", + "shortName": "RolloutPlansClient" + }, + "fullName": "google.cloud.compute_v1beta.RolloutPlansClient.get", + "method": { + "fullName": "google.cloud.compute.v1beta.RolloutPlans.Get", + "service": { + "fullName": "google.cloud.compute.v1beta.RolloutPlans", + "shortName": "RolloutPlans" + }, + "shortName": "Get" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.GetRolloutPlanRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "rollout_plan", + "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.RolloutPlan", + "shortName": "get" }, - "description": "Sample for Delete", - "file": "compute_v1beta_generated_rollout_plans_delete_sync.py", + "description": "Sample for Get", + "file": "compute_v1beta_generated_rollout_plans_get_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RolloutPlans_Delete_sync", + "regionTag": "compute_v1beta_generated_RolloutPlans_Get_sync", "segments": [ { "end": 52, @@ -73041,7 +74653,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_rollout_plans_delete_sync.py" + "title": "compute_v1beta_generated_rollout_plans_get_sync.py" }, { "canonical": true, @@ -73050,27 +74662,27 @@ "fullName": "google.cloud.compute_v1beta.RolloutPlansClient", "shortName": "RolloutPlansClient" }, - "fullName": "google.cloud.compute_v1beta.RolloutPlansClient.get", + "fullName": "google.cloud.compute_v1beta.RolloutPlansClient.insert", "method": { - "fullName": "google.cloud.compute.v1beta.RolloutPlans.Get", + "fullName": "google.cloud.compute.v1beta.RolloutPlans.Insert", "service": { "fullName": "google.cloud.compute.v1beta.RolloutPlans", "shortName": "RolloutPlans" }, - "shortName": "Get" + "shortName": "Insert" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.GetRolloutPlanRequest" + "type": "google.cloud.compute_v1beta.types.InsertRolloutPlanRequest" }, { "name": "project", "type": "str" }, { - "name": "rollout_plan", - "type": "str" + "name": "rollout_plan_resource", + "type": "google.cloud.compute_v1beta.types.RolloutPlan" }, { "name": "retry", @@ -73085,22 +74697,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.types.RolloutPlan", - "shortName": "get" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "insert" }, - "description": "Sample for Get", - "file": "compute_v1beta_generated_rollout_plans_get_sync.py", + "description": "Sample for Insert", + "file": "compute_v1beta_generated_rollout_plans_insert_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RolloutPlans_Get_sync", + "regionTag": "compute_v1beta_generated_RolloutPlans_Insert_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -73110,22 +74722,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 46, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 49, - "start": 47, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 50, + "end": 52, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_rollout_plans_get_sync.py" + "title": "compute_v1beta_generated_rollout_plans_insert_sync.py" }, { "canonical": true, @@ -73134,28 +74746,24 @@ "fullName": "google.cloud.compute_v1beta.RolloutPlansClient", "shortName": "RolloutPlansClient" }, - "fullName": "google.cloud.compute_v1beta.RolloutPlansClient.insert", + "fullName": "google.cloud.compute_v1beta.RolloutPlansClient.list", "method": { - "fullName": "google.cloud.compute.v1beta.RolloutPlans.Insert", + "fullName": "google.cloud.compute.v1beta.RolloutPlans.List", "service": { "fullName": "google.cloud.compute.v1beta.RolloutPlans", "shortName": "RolloutPlans" }, - "shortName": "Insert" + "shortName": "List" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.InsertRolloutPlanRequest" + "type": "google.cloud.compute_v1beta.types.ListRolloutPlansRequest" }, { "name": "project", "type": "str" }, - { - "name": "rollout_plan_resource", - "type": "google.cloud.compute_v1beta.types.RolloutPlan" - }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -73169,22 +74777,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "insert" + "resultType": "google.cloud.compute_v1beta.services.rollout_plans.pagers.ListPager", + "shortName": "list" }, - "description": "Sample for Insert", - "file": "compute_v1beta_generated_rollout_plans_insert_sync.py", + "description": "Sample for List", + "file": "compute_v1beta_generated_rollout_plans_list_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RolloutPlans_Insert_sync", + "regionTag": "compute_v1beta_generated_RolloutPlans_List_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -73204,38 +74812,42 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_rollout_plans_insert_sync.py" + "title": "compute_v1beta_generated_rollout_plans_list_sync.py" }, { "canonical": true, "clientMethod": { "client": { - "fullName": "google.cloud.compute_v1beta.RolloutPlansClient", - "shortName": "RolloutPlansClient" + "fullName": "google.cloud.compute_v1beta.RolloutsClient", + "shortName": "RolloutsClient" }, - "fullName": "google.cloud.compute_v1beta.RolloutPlansClient.list", + "fullName": "google.cloud.compute_v1beta.RolloutsClient.advance", "method": { - "fullName": "google.cloud.compute.v1beta.RolloutPlans.List", + "fullName": "google.cloud.compute.v1beta.Rollouts.Advance", "service": { - "fullName": "google.cloud.compute.v1beta.RolloutPlans", - "shortName": "RolloutPlans" + "fullName": "google.cloud.compute.v1beta.Rollouts", + "shortName": "Rollouts" }, - "shortName": "List" + "shortName": "Advance" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1beta.types.ListRolloutPlansRequest" + "type": "google.cloud.compute_v1beta.types.AdvanceRolloutRequest" }, { "name": "project", "type": "str" }, + { + "name": "rollout", + "type": "str" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -73249,14 +74861,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.compute_v1beta.services.rollout_plans.pagers.ListPager", - "shortName": "list" + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "advance" }, - "description": "Sample for List", - "file": "compute_v1beta_generated_rollout_plans_list_sync.py", + "description": "Sample for Advance", + "file": "compute_v1beta_generated_rollouts_advance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1beta_generated_RolloutPlans_List_sync", + "regionTag": "compute_v1beta_generated_Rollouts_Advance_sync", "segments": [ { "end": 52, @@ -73274,22 +74886,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 49, + "start": 47, "type": "REQUEST_EXECUTION" }, { "end": 53, - "start": 49, + "start": 50, "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1beta_generated_rollout_plans_list_sync.py" + "title": "compute_v1beta_generated_rollouts_advance_sync.py" }, { "canonical": true, @@ -73623,6 +75235,174 @@ ], "title": "compute_v1beta_generated_rollouts_list_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RolloutsClient", + "shortName": "RolloutsClient" + }, + "fullName": "google.cloud.compute_v1beta.RolloutsClient.pause", + "method": { + "fullName": "google.cloud.compute.v1beta.Rollouts.Pause", + "service": { + "fullName": "google.cloud.compute.v1beta.Rollouts", + "shortName": "Rollouts" + }, + "shortName": "Pause" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.PauseRolloutRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "rollout", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "pause" + }, + "description": "Sample for Pause", + "file": "compute_v1beta_generated_rollouts_pause_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Rollouts_Pause_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_rollouts_pause_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1beta.RolloutsClient", + "shortName": "RolloutsClient" + }, + "fullName": "google.cloud.compute_v1beta.RolloutsClient.resume", + "method": { + "fullName": "google.cloud.compute.v1beta.Rollouts.Resume", + "service": { + "fullName": "google.cloud.compute.v1beta.Rollouts", + "shortName": "Rollouts" + }, + "shortName": "Resume" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1beta.types.ResumeRolloutRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "rollout", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "resume" + }, + "description": "Sample for Resume", + "file": "compute_v1beta_generated_rollouts_resume_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1beta_generated_Rollouts_Resume_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1beta_generated_rollouts_resume_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_backend_services.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_backend_services.py index f5ecd2d39364..3dd88c4d516d 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_backend_services.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_backend_services.py @@ -8160,6 +8160,8 @@ def test_insert_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -8878,6 +8880,8 @@ def test_patch_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -10290,6 +10294,8 @@ def test_update_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py index 9fc66d7281c9..23d2b4f8e4ce 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_disks.py @@ -9976,6 +9976,9 @@ def test_get_rest_call_success(request_type): source_image_id="source_image_id_value", source_instant_snapshot="source_instant_snapshot_value", source_instant_snapshot_id="source_instant_snapshot_id_value", + source_machine_image="source_machine_image_value", + source_machine_image_disk_device_name="source_machine_image_disk_device_name_value", + source_machine_image_id="source_machine_image_id_value", source_snapshot="source_snapshot_value", source_snapshot_id="source_snapshot_id_value", source_storage_object="source_storage_object_value", @@ -10045,6 +10048,12 @@ def test_get_rest_call_success(request_type): assert response.source_image_id == "source_image_id_value" assert response.source_instant_snapshot == "source_instant_snapshot_value" assert response.source_instant_snapshot_id == "source_instant_snapshot_id_value" + assert response.source_machine_image == "source_machine_image_value" + assert ( + response.source_machine_image_disk_device_name + == "source_machine_image_disk_device_name_value" + ) + assert response.source_machine_image_id == "source_machine_image_id_value" assert response.source_snapshot == "source_snapshot_value" assert response.source_snapshot_id == "source_snapshot_id_value" assert response.source_storage_object == "source_storage_object_value" @@ -10339,6 +10348,10 @@ def test_insert_rest_call_success(request_type): "source_image_id": "source_image_id_value", "source_instant_snapshot": "source_instant_snapshot_value", "source_instant_snapshot_id": "source_instant_snapshot_id_value", + "source_machine_image": "source_machine_image_value", + "source_machine_image_disk_device_name": "source_machine_image_disk_device_name_value", + "source_machine_image_encryption_key": {}, + "source_machine_image_id": "source_machine_image_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -12633,6 +12646,10 @@ def test_update_rest_call_success(request_type): "source_image_id": "source_image_id_value", "source_instant_snapshot": "source_instant_snapshot_value", "source_instant_snapshot_id": "source_instant_snapshot_id_value", + "source_machine_image": "source_machine_image_value", + "source_machine_image_disk_device_name": "source_machine_image_disk_device_name_value", + "source_machine_image_encryption_key": {}, + "source_machine_image_id": "source_machine_image_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py index bd52218b4096..55edec5a34a7 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_future_reservations.py @@ -4514,6 +4514,7 @@ def test_insert_rest_call_success(request_type): "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", @@ -5013,6 +5014,7 @@ def test_update_rest_call_success(request_type): "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_hosts.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_hosts.py new file mode 100644 index 000000000000..46d1aef1e8e6 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_hosts.py @@ -0,0 +1,3086 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +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 + +import google.api_core.extended_operation as extended_operation # type: ignore +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.hosts import HostsClient, 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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert HostsClient._get_default_mtls_endpoint(None) is None + assert HostsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + assert ( + HostsClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint + ) + assert ( + HostsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + HostsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert HostsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert HostsClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + + +def test__read_environment_variables(): + assert HostsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert HostsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert HostsClient._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: + HostsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert HostsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert HostsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert HostsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert HostsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._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): + HostsClient._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 HostsClient._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 HostsClient._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 HostsClient._get_client_cert_source(None, False) is None + assert HostsClient._get_client_cert_source(mock_provided_cert_source, False) is None + assert ( + HostsClient._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 ( + HostsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + HostsClient._get_client_cert_source(mock_provided_cert_source, "true") + is mock_provided_cert_source + ) + + +@mock.patch.object( + HostsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HostsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = HostsClient._DEFAULT_UNIVERSE + default_endpoint = HostsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = HostsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + HostsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + HostsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == HostsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HostsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + HostsClient._get_api_endpoint(None, None, default_universe, "always") + == HostsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HostsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == HostsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + HostsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + HostsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + HostsClient._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 ( + HostsClient._get_universe_domain(client_universe_domain, universe_domain_env) + == client_universe_domain + ) + assert ( + HostsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert HostsClient._get_universe_domain(None, None) == HostsClient._DEFAULT_UNIVERSE + + with pytest.raises(ValueError) as excinfo: + HostsClient._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 = HostsClient(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 = HostsClient(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", + [ + (HostsClient, "rest"), + ], +) +def test_hosts_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.HostsRestTransport, "rest"), + ], +) +def test_hosts_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", + [ + (HostsClient, "rest"), + ], +) +def test_hosts_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_hosts_client_get_transport_class(): + transport = HostsClient.get_transport_class() + available_transports = [ + transports.HostsRestTransport, + ] + assert transport in available_transports + + transport = HostsClient.get_transport_class("rest") + assert transport == transports.HostsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (HostsClient, transports.HostsRestTransport, "rest"), + ], +) +@mock.patch.object( + HostsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HostsClient), +) +def test_hosts_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(HostsClient, "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(HostsClient, "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", + [ + (HostsClient, transports.HostsRestTransport, "rest", "true"), + (HostsClient, transports.HostsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + HostsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HostsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_hosts_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", [HostsClient]) +@mock.patch.object( + HostsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(HostsClient) +) +def test_hosts_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", [HostsClient]) +@mock.patch.object( + HostsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(HostsClient), +) +def test_hosts_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = HostsClient._DEFAULT_UNIVERSE + default_endpoint = HostsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = HostsClient._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", + [ + (HostsClient, transports.HostsRestTransport, "rest"), + ], +) +def test_hosts_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", + [ + (HostsClient, transports.HostsRestTransport, "rest", None), + ], +) +def test_hosts_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 = HostsClient( + 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.GetHostRequest): + transport_class = transports.HostsRestTransport + + request_init = {} + request_init["association"] = "" + request_init["host"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["association"] = "association_value" + jsonified_request["host"] = "host_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "association" in jsonified_request + assert jsonified_request["association"] == "association_value" + assert "host" in jsonified_request + assert jsonified_request["host"] == "host_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Host() + # 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.Host.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "association", + "host", + "project", + "zone", + ) + ) + ) + + +def test_get_rest_flattened(): + client = HostsClient( + 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.Host() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + association="association_value", + host="host_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.Host.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.get(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/zones/{zone}/{association}/hosts/{host}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = HostsClient( + 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.GetHostRequest(), + project="project_value", + zone="zone_value", + association="association_value", + host="host_value", + ) + + +def test_get_version_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 = HostsClient( + 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_version 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_version] = mock_rpc + + request = {} + client.get_version(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.get_version(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_version_rest_required_fields(request_type=compute.GetVersionHostRequest): + transport_class = transports.HostsRestTransport + + request_init = {} + request_init["association"] = "" + request_init["host"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["association"] = "association_value" + jsonified_request["host"] = "host_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "association" in jsonified_request + assert jsonified_request["association"] == "association_value" + assert "host" in jsonified_request + assert jsonified_request["host"] == "host_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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_version(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_version_rest_unset_required_fields(): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "association", + "host", + "hostsGetVersionRequestResource", + "project", + "zone", + ) + ) + ) + + +def test_get_version_rest_flattened(): + client = HostsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + association="association_value", + host="host_value", + hosts_get_version_request_resource=compute.HostsGetVersionRequest( + sbom_selections=["sbom_selections_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.Operation.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_version(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/zones/{zone}/{association}/hosts/{host}/getVersion" + % client.transport._host, + args[1], + ) + + +def test_get_version_rest_flattened_error(transport: str = "rest"): + client = HostsClient( + 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_version( + compute.GetVersionHostRequest(), + project="project_value", + zone="zone_value", + association="association_value", + host="host_value", + hosts_get_version_request_resource=compute.HostsGetVersionRequest( + sbom_selections=["sbom_selections_value"] + ), + ) + + +def test_get_version_unary_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 = HostsClient( + 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_version 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_version] = mock_rpc + + request = {} + client.get_version_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.get_version_unary(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_version_unary_rest_required_fields( + request_type=compute.GetVersionHostRequest, +): + transport_class = transports.HostsRestTransport + + request_init = {} + request_init["association"] = "" + request_init["host"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_version._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["association"] = "association_value" + jsonified_request["host"] = "host_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_version._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "association" in jsonified_request + assert jsonified_request["association"] == "association_value" + assert "host" in jsonified_request + assert jsonified_request["host"] == "host_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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_version_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_version_unary_rest_unset_required_fields(): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "association", + "host", + "hostsGetVersionRequestResource", + "project", + "zone", + ) + ) + ) + + +def test_get_version_unary_rest_flattened(): + client = HostsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "sample4", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + association="association_value", + host="host_value", + hosts_get_version_request_resource=compute.HostsGetVersionRequest( + sbom_selections=["sbom_selections_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.Operation.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_version_unary(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/zones/{zone}/{association}/hosts/{host}/getVersion" + % client.transport._host, + args[1], + ) + + +def test_get_version_unary_rest_flattened_error(transport: str = "rest"): + client = HostsClient( + 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_version_unary( + compute.GetVersionHostRequest(), + project="project_value", + zone="zone_value", + association="association_value", + host="host_value", + hosts_get_version_request_resource=compute.HostsGetVersionRequest( + sbom_selections=["sbom_selections_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 = HostsClient( + 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.ListHostsRequest): + transport_class = transports.HostsRestTransport + + request_init = {} + request_init["association"] = "" + request_init["project"] = "" + request_init["zone"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["association"] = "association_value" + jsonified_request["project"] = "project_value" + jsonified_request["zone"] = "zone_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "order_by", + "page_token", + "return_partial_success", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "association" in jsonified_request + assert jsonified_request["association"] == "association_value" + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "zone" in jsonified_request + assert jsonified_request["zone"] == "zone_value" + + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.HostsListResponse() + # 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.HostsListResponse.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 sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set( + ( + "association", + "project", + "zone", + ) + ) + ) + + +def test_list_rest_flattened(): + client = HostsClient( + 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.HostsListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + zone="zone_value", + association="association_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.HostsListResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.list(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/compute/beta/projects/{project}/zones/{zone}/{association}/hosts" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = HostsClient( + 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.ListHostsRequest(), + project="project_value", + zone="zone_value", + association="association_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = HostsClient( + 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.HostsListResponse( + items=[ + compute.Host(), + compute.Host(), + compute.Host(), + ], + next_page_token="abc", + ), + compute.HostsListResponse( + items=[], + next_page_token="def", + ), + compute.HostsListResponse( + items=[ + compute.Host(), + ], + next_page_token="ghi", + ), + compute.HostsListResponse( + items=[ + compute.Host(), + compute.Host(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.HostsListResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + } + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.Host) 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.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HostsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = HostsClient( + 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 = HostsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = HostsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = HostsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.HostsRestTransport, + ], +) +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 = HostsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetHostRequest): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "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.GetHostRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "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.Host( + alias_links=["alias_links_value"], + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + name="name_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + state="state_value", + zone="zone_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.Host.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.Host) + assert response.alias_links == ["alias_links_value"] + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.state == "state_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HostsRestInterceptor(), + ) + client = HostsClient(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.HostsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.HostsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.HostsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetHostRequest.pb(compute.GetHostRequest()) + 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.Host.to_json(compute.Host()) + req.return_value.content = return_value + + request = compute.GetHostRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Host() + post_with_metadata.return_value = compute.Host(), 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_get_version_rest_bad_request(request_type=compute.GetVersionHostRequest): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "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_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetVersionHostRequest, + dict, + ], +) +def test_get_version_rest_call_success(request_type): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "project": "sample1", + "zone": "sample2", + "association": "sample3", + "host": "sample4", + } + request_init["hosts_get_version_request_resource"] = { + "sbom_selections": ["sbom_selections_value1", "sbom_selections_value2"] + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.GetVersionHostRequest.meta.fields[ + "hosts_get_version_request_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "hosts_get_version_request_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range( + 0, len(request_init["hosts_get_version_request_resource"][field]) + ): + del request_init["hosts_get_version_request_resource"][field][i][ + subfield + ] + else: + del request_init["hosts_get_version_request_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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_version(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_version_rest_interceptors(null_interceptor): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HostsRestInterceptor(), + ) + client = HostsClient(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.HostsRestInterceptor, "post_get_version") as post, + mock.patch.object( + transports.HostsRestInterceptor, "post_get_version_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.HostsRestInterceptor, "pre_get_version") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetVersionHostRequest.pb(compute.GetVersionHostRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.GetVersionHostRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.get_version( + 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.ListHostsRequest): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "association": "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.ListHostsRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "zone": "sample2", "association": "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.HostsListResponse( + etag="etag_value", + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_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.HostsListResponse.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.etag == "etag_value" + 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" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.HostsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.HostsRestInterceptor(), + ) + client = HostsClient(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.HostsRestInterceptor, "post_list") as post, + mock.patch.object( + transports.HostsRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.HostsRestInterceptor, "pre_list") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListHostsRequest.pb(compute.ListHostsRequest()) + 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.HostsListResponse.to_json(compute.HostsListResponse()) + req.return_value.content = return_value + + request = compute.ListHostsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.HostsListResponse() + post_with_metadata.return_value = compute.HostsListResponse(), 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 = HostsClient( + 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 = HostsClient( + 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.GetHostRequest() + 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_get_version_unary_empty_call_rest(): + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_version), "__call__") as call: + client.get_version_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetVersionHostRequest() + 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 = HostsClient( + 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.ListHostsRequest() + assert args[0] == request_msg + + +def test_hosts_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.HostsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_hosts_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.hosts.transports.HostsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.HostsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "get", + "get_version", + "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_hosts_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.hosts.transports.HostsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HostsTransport( + 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", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_hosts_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.hosts.transports.HostsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.HostsTransport() + adc.assert_called_once() + + +def test_hosts_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) + HostsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_hosts_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.HostsRestTransport( + 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_hosts_host_no_port(transport_name): + client = HostsClient( + 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_hosts_host_with_port(transport_name): + client = HostsClient( + 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_hosts_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = HostsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = HostsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.get_version._session + session2 = client2.transport.get_version._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 = HostsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = HostsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = HostsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = HostsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = HostsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = HostsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = HostsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = HostsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = HostsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = HostsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = HostsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = HostsClient.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 = HostsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = HostsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = HostsClient.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.HostsTransport, "_prep_wrapped_messages") as prep: + client = HostsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object(transports.HostsTransport, "_prep_wrapped_messages") as prep: + transport_class = HostsClient.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 = HostsClient( + 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 = HostsClient( + 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", + [ + (HostsClient, transports.HostsRestTransport), + ], +) +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_image_views.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_image_views.py new file mode 100644 index 000000000000..4b4f2960da36 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_image_views.py @@ -0,0 +1,1916 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +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 + +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.image_views import ( + ImageViewsClient, + 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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert ImageViewsClient._get_default_mtls_endpoint(None) is None + assert ( + ImageViewsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ImageViewsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ImageViewsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ImageViewsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ImageViewsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + ImageViewsClient._get_default_mtls_endpoint(custom_endpoint) == custom_endpoint + ) + + +def test__read_environment_variables(): + assert ImageViewsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ImageViewsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ImageViewsClient._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: + ImageViewsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ImageViewsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ImageViewsClient._read_environment_variables() == (False, "never", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ImageViewsClient._read_environment_variables() == (False, "always", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ImageViewsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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): + ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._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 ImageViewsClient._get_client_cert_source(None, False) is None + assert ( + ImageViewsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ImageViewsClient._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 ( + ImageViewsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ImageViewsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ImageViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ImageViewsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ImageViewsClient._DEFAULT_UNIVERSE + default_endpoint = ImageViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ImageViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ImageViewsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ImageViewsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ImageViewsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ImageViewsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ImageViewsClient._get_api_endpoint(None, None, default_universe, "always") + == ImageViewsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ImageViewsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ImageViewsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ImageViewsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ImageViewsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ImageViewsClient._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 ( + ImageViewsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ImageViewsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ImageViewsClient._get_universe_domain(None, None) + == ImageViewsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ImageViewsClient._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 = ImageViewsClient(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 = ImageViewsClient(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", + [ + (ImageViewsClient, "rest"), + ], +) +def test_image_views_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.ImageViewsRestTransport, "rest"), + ], +) +def test_image_views_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", + [ + (ImageViewsClient, "rest"), + ], +) +def test_image_views_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_image_views_client_get_transport_class(): + transport = ImageViewsClient.get_transport_class() + available_transports = [ + transports.ImageViewsRestTransport, + ] + assert transport in available_transports + + transport = ImageViewsClient.get_transport_class("rest") + assert transport == transports.ImageViewsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ImageViewsClient, transports.ImageViewsRestTransport, "rest"), + ], +) +@mock.patch.object( + ImageViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ImageViewsClient), +) +def test_image_views_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(ImageViewsClient, "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(ImageViewsClient, "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", + [ + (ImageViewsClient, transports.ImageViewsRestTransport, "rest", "true"), + (ImageViewsClient, transports.ImageViewsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ImageViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ImageViewsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_image_views_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", [ImageViewsClient]) +@mock.patch.object( + ImageViewsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ImageViewsClient) +) +def test_image_views_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", [ImageViewsClient]) +@mock.patch.object( + ImageViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ImageViewsClient), +) +def test_image_views_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ImageViewsClient._DEFAULT_UNIVERSE + default_endpoint = ImageViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ImageViewsClient._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", + [ + (ImageViewsClient, transports.ImageViewsRestTransport, "rest"), + ], +) +def test_image_views_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", + [ + (ImageViewsClient, transports.ImageViewsRestTransport, "rest", None), + ], +) +def test_image_views_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 = ImageViewsClient( + 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.GetImageViewRequest): + transport_class = transports.ImageViewsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["resource_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + 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["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["resourceId"] = "resource_id_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "resourceId" in jsonified_request + assert jsonified_request["resourceId"] == "resource_id_value" + + client = ImageViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ImageView() + # 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.ImageView.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "region", + "resourceId", + ) + ) + ) + + +def test_get_rest_flattened(): + client = ImageViewsClient( + 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.ImageView() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "resource_id": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + resource_id="resource_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = compute.ImageView.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}/imageViews/{resource_id}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ImageViewsClient( + 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.GetImageViewRequest(), + project="project_value", + region="region_value", + resource_id="resource_id_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageViewsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ImageViewsClient( + 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 = ImageViewsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ImageViewsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ImageViewsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ImageViewsRestTransport, + ], +) +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 = ImageViewsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetImageViewRequest): + client = ImageViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource_id": "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.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetImageViewRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ImageViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "resource_id": "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.ImageView() + + # 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.ImageView.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.ImageView) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ImageViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ImageViewsRestInterceptor(), + ) + client = ImageViewsClient(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.ImageViewsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.ImageViewsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ImageViewsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetImageViewRequest.pb(compute.GetImageViewRequest()) + 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.ImageView.to_json(compute.ImageView()) + req.return_value.content = return_value + + request = compute.GetImageViewRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ImageView() + post_with_metadata.return_value = compute.ImageView(), 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_initialize_client_w_rest(): + client = ImageViewsClient( + 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 = ImageViewsClient( + 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.GetImageViewRequest() + assert args[0] == request_msg + + +def test_image_views_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ImageViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_image_views_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.image_views.transports.ImageViewsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ImageViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("get",) + 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_image_views_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.image_views.transports.ImageViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageViewsTransport( + 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_image_views_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.image_views.transports.ImageViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ImageViewsTransport() + adc.assert_called_once() + + +def test_image_views_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) + ImageViewsClient() + 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_image_views_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.ImageViewsRestTransport( + 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_image_views_host_no_port(transport_name): + client = ImageViewsClient( + 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_image_views_host_with_port(transport_name): + client = ImageViewsClient( + 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_image_views_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ImageViewsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ImageViewsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ImageViewsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ImageViewsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ImageViewsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ImageViewsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ImageViewsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ImageViewsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ImageViewsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ImageViewsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ImageViewsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ImageViewsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ImageViewsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ImageViewsClient.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 = ImageViewsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ImageViewsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ImageViewsClient.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.ImageViewsTransport, "_prep_wrapped_messages" + ) as prep: + client = ImageViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ImageViewsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ImageViewsClient.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 = ImageViewsClient( + 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 = ImageViewsClient( + 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", + [ + (ImageViewsClient, transports.ImageViewsRestTransport), + ], +) +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_instance_group_managers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py index 3acef71cea5d..d367b1e61db9 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_instance_group_managers.py @@ -13642,6 +13642,7 @@ def test_apply_updates_to_instances_rest_call_success(request_type): } request_init["instance_group_managers_apply_updates_request_resource"] = { "all_instances": True, + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instances": ["instances_value1", "instances_value2"], "minimal_action": "minimal_action_value", "most_disruptive_allowed_action": "most_disruptive_allowed_action_value", @@ -15520,6 +15521,7 @@ def test_insert_rest_call_success(request_type): "recreating": 1060, "refreshing": 1069, "restarting": 1091, + "restarting_in_place": 2013, "resuming": 874, "starting": 876, "stopping": 884, @@ -15651,6 +15653,7 @@ def test_insert_rest_call_success(request_type): "target_stopped_size": 2047, "target_suspended_size": 2251, "update_policy": { + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instance_redistribution_type": "instance_redistribution_type_value", "max_surge": {"calculated": 1042, "fixed": 528, "percent": 753}, "max_unavailable": {}, @@ -16517,6 +16520,7 @@ def test_patch_rest_call_success(request_type): "recreating": 1060, "refreshing": 1069, "restarting": 1091, + "restarting_in_place": 2013, "resuming": 874, "starting": 876, "stopping": 884, @@ -16648,6 +16652,7 @@ def test_patch_rest_call_success(request_type): "target_stopped_size": 2047, "target_suspended_size": 2251, "update_policy": { + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instance_redistribution_type": "instance_redistribution_type_value", "max_surge": {"calculated": 1042, "fixed": 528, "percent": 753}, "max_unavailable": {}, @@ -20012,6 +20017,7 @@ def test_update_rest_call_success(request_type): "recreating": 1060, "refreshing": 1069, "restarting": 1091, + "restarting_in_place": 2013, "resuming": 874, "starting": 876, "stopping": 884, @@ -20143,6 +20149,7 @@ def test_update_rest_call_success(request_type): "target_stopped_size": 2047, "target_suspended_size": 2251, "update_policy": { + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instance_redistribution_type": "instance_redistribution_type_value", "max_surge": {"calculated": 1042, "fixed": 528, "percent": 753}, "max_unavailable": {}, 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 3d5ffbedd079..771d9f418d86 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 @@ -4122,6 +4122,7 @@ def test_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_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 268f6235b18d..22032c9bff87 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 @@ -24335,6 +24335,7 @@ def test_bulk_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -25404,6 +25405,7 @@ def test_get_rest_call_success(request_type): last_start_timestamp="last_start_timestamp_value", last_stop_timestamp="last_stop_timestamp_value", last_suspended_timestamp="last_suspended_timestamp_value", + local_ssd_encryption_mode="local_ssd_encryption_mode_value", machine_type="machine_type_value", min_cpu_platform="min_cpu_platform_value", name="name_value", @@ -25449,6 +25451,7 @@ def test_get_rest_call_success(request_type): assert response.last_start_timestamp == "last_start_timestamp_value" assert response.last_stop_timestamp == "last_stop_timestamp_value" assert response.last_suspended_timestamp == "last_suspended_timestamp_value" + assert response.local_ssd_encryption_mode == "local_ssd_encryption_mode_value" assert response.machine_type == "machine_type_value" assert response.min_cpu_platform == "min_cpu_platform_value" assert response.name == "name_value" @@ -26715,6 +26718,7 @@ def test_insert_rest_call_success(request_type): "last_start_timestamp": "last_start_timestamp_value", "last_stop_timestamp": "last_stop_timestamp_value", "last_suspended_timestamp": "last_suspended_timestamp_value", + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -26798,13 +26802,16 @@ def test_insert_rest_call_success(request_type): }, "physical_host": "physical_host_value", "physical_host_topology": { + "additional_attributes": {"accelerator_topology_ids": {}}, "block": "block_value", "cluster": "cluster_value", "host": "host_value", "subblock": "subblock_value", }, "reservation_consumption_info": { - "consumed_reservation": "consumed_reservation_value" + "consumed_reservation": "consumed_reservation_value", + "consumed_reservation_block": "consumed_reservation_block_value", + "consumed_reservation_sub_block": "consumed_reservation_sub_block_value", }, "scheduling": { "availability_domain": 2002, @@ -33703,6 +33710,7 @@ def test_update_rest_call_success(request_type): "last_start_timestamp": "last_start_timestamp_value", "last_stop_timestamp": "last_stop_timestamp_value", "last_suspended_timestamp": "last_suspended_timestamp_value", + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -33786,13 +33794,16 @@ def test_update_rest_call_success(request_type): }, "physical_host": "physical_host_value", "physical_host_topology": { + "additional_attributes": {"accelerator_topology_ids": {}}, "block": "block_value", "cluster": "cluster_value", "host": "host_value", "subblock": "subblock_value", }, "reservation_consumption_info": { - "consumed_reservation": "consumed_reservation_value" + "consumed_reservation": "consumed_reservation_value", + "consumed_reservation_block": "consumed_reservation_block_value", + "consumed_reservation_sub_block": "consumed_reservation_sub_block_value", }, "scheduling": { "availability_domain": 2002, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py index ab2e7c2fe113..ea2edbbd37c4 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_interconnects.py @@ -4089,6 +4089,7 @@ def test_get_rest_call_success(request_type): creation_timestamp="creation_timestamp_value", customer_name="customer_name_value", description="description_value", + effective_location="effective_location_value", google_ip_address="google_ip_address_value", google_reference_id="google_reference_id_value", id=205, @@ -4135,6 +4136,7 @@ def test_get_rest_call_success(request_type): assert response.creation_timestamp == "creation_timestamp_value" assert response.customer_name == "customer_name_value" assert response.description == "description_value" + assert response.effective_location == "effective_location_value" assert response.google_ip_address == "google_ip_address_value" assert response.google_reference_id == "google_reference_id_value" assert response.id == 205 @@ -4553,6 +4555,7 @@ def test_insert_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "customer_name": "customer_name_value", "description": "description_value", + "effective_location": "effective_location_value", "expected_outages": [ { "affected_circuits": [ @@ -5004,6 +5007,7 @@ def test_patch_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "customer_name": "customer_name_value", "description": "description_value", + "effective_location": "effective_location_value", "expected_outages": [ { "affected_circuits": [ 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 2597f9873e19..9952d2fe086a 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 @@ -4089,6 +4089,7 @@ def test_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -4214,7 +4215,11 @@ def test_insert_rest_call_success(request_type): "labels": {}, "machine_image_encryption_key": {}, "name": "name_value", - "params": {"resource_manager_tags": {}}, + "params": { + "excluded_disks": ["excluded_disks_value1", "excluded_disks_value2"], + "included_disks": ["included_disks_value1", "included_disks_value2"], + "resource_manager_tags": {}, + }, "satisfies_pzi": True, "satisfies_pzs": True, "saved_disks": [ diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_node_groups.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_node_groups.py index 2fd1de9cda9a..33280408a8e1 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_node_groups.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_node_groups.py @@ -7527,6 +7527,7 @@ def test_insert_rest_call_success(request_type): "node_template": "node_template_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", @@ -8052,6 +8053,7 @@ def test_patch_rest_call_success(request_type): "node_template": "node_template_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_organization_rollout_plans.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_organization_rollout_plans.py new file mode 100644 index 000000000000..b05e29ac3f85 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_organization_rollout_plans.py @@ -0,0 +1,3764 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +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 + +import google.api_core.extended_operation as extended_operation # type: ignore +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.organization_rollout_plans import ( + OrganizationRolloutPlansClient, + 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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert OrganizationRolloutPlansClient._get_default_mtls_endpoint(None) is None + assert ( + OrganizationRolloutPlansClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationRolloutPlansClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationRolloutPlansClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationRolloutPlansClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationRolloutPlansClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + OrganizationRolloutPlansClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert OrganizationRolloutPlansClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OrganizationRolloutPlansClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OrganizationRolloutPlansClient._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: + OrganizationRolloutPlansClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert OrganizationRolloutPlansClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert OrganizationRolloutPlansClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OrganizationRolloutPlansClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OrganizationRolloutPlansClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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): + OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._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 ( + OrganizationRolloutPlansClient._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 OrganizationRolloutPlansClient._get_client_cert_source(None, False) is None + assert ( + OrganizationRolloutPlansClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + OrganizationRolloutPlansClient._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 ( + OrganizationRolloutPlansClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + OrganizationRolloutPlansClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + OrganizationRolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutPlansClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OrganizationRolloutPlansClient._DEFAULT_UNIVERSE + default_endpoint = OrganizationRolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = OrganizationRolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == OrganizationRolloutPlansClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == OrganizationRolloutPlansClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == OrganizationRolloutPlansClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + None, None, mock_universe, "never" + ) + == mock_endpoint + ) + assert ( + OrganizationRolloutPlansClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationRolloutPlansClient._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 ( + OrganizationRolloutPlansClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + OrganizationRolloutPlansClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + OrganizationRolloutPlansClient._get_universe_domain(None, None) + == OrganizationRolloutPlansClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + OrganizationRolloutPlansClient._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 = OrganizationRolloutPlansClient(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 = OrganizationRolloutPlansClient(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", + [ + (OrganizationRolloutPlansClient, "rest"), + ], +) +def test_organization_rollout_plans_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.OrganizationRolloutPlansRestTransport, "rest"), + ], +) +def test_organization_rollout_plans_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", + [ + (OrganizationRolloutPlansClient, "rest"), + ], +) +def test_organization_rollout_plans_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_organization_rollout_plans_client_get_transport_class(): + transport = OrganizationRolloutPlansClient.get_transport_class() + available_transports = [ + transports.OrganizationRolloutPlansRestTransport, + ] + assert transport in available_transports + + transport = OrganizationRolloutPlansClient.get_transport_class("rest") + assert transport == transports.OrganizationRolloutPlansRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OrganizationRolloutPlansClient, + transports.OrganizationRolloutPlansRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + OrganizationRolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutPlansClient), +) +def test_organization_rollout_plans_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( + OrganizationRolloutPlansClient, "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( + OrganizationRolloutPlansClient, "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", + [ + ( + OrganizationRolloutPlansClient, + transports.OrganizationRolloutPlansRestTransport, + "rest", + "true", + ), + ( + OrganizationRolloutPlansClient, + transports.OrganizationRolloutPlansRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + OrganizationRolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutPlansClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_organization_rollout_plans_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", [OrganizationRolloutPlansClient]) +@mock.patch.object( + OrganizationRolloutPlansClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OrganizationRolloutPlansClient), +) +def test_organization_rollout_plans_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", [OrganizationRolloutPlansClient]) +@mock.patch.object( + OrganizationRolloutPlansClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutPlansClient), +) +def test_organization_rollout_plans_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OrganizationRolloutPlansClient._DEFAULT_UNIVERSE + default_endpoint = OrganizationRolloutPlansClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = OrganizationRolloutPlansClient._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", + [ + ( + OrganizationRolloutPlansClient, + transports.OrganizationRolloutPlansRestTransport, + "rest", + ), + ], +) +def test_organization_rollout_plans_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", + [ + ( + OrganizationRolloutPlansClient, + transports.OrganizationRolloutPlansRestTransport, + "rest", + None, + ), + ], +) +def test_organization_rollout_plans_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_delete_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 = OrganizationRolloutPlansClient( + 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.delete 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.delete] = mock_rpc + + request = {} + client.delete(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(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_delete_rest_required_fields( + request_type=compute.DeleteOrganizationRolloutPlanRequest, +): + transport_class = transports.OrganizationRolloutPlansRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout_plan"] = "" + 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() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rolloutPlan"] = "rollout_plan_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rolloutPlan" in jsonified_request + assert jsonified_request["rolloutPlan"] == "rollout_plan_value" + + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # 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": "delete", + "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.Operation.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.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_rest_unset_required_fields(): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "organization", + "rolloutPlan", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = OrganizationRolloutPlansClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "organization": "organizations/sample1", + "rollout_plan": "sample2", + } + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout_plan="rollout_plan_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.Operation.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.delete(**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/{organization=organizations/*}/global/rolloutPlans/{rollout_plan}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.delete( + compute.DeleteOrganizationRolloutPlanRequest(), + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + +def test_delete_unary_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 = OrganizationRolloutPlansClient( + 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.delete 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.delete] = mock_rpc + + request = {} + client.delete_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(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_delete_unary_rest_required_fields( + request_type=compute.DeleteOrganizationRolloutPlanRequest, +): + transport_class = transports.OrganizationRolloutPlansRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout_plan"] = "" + 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() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rolloutPlan"] = "rollout_plan_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rolloutPlan" in jsonified_request + assert jsonified_request["rolloutPlan"] == "rollout_plan_value" + + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # 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": "delete", + "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.Operation.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.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "organization", + "rolloutPlan", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = OrganizationRolloutPlansClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "organization": "organizations/sample1", + "rollout_plan": "sample2", + } + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout_plan="rollout_plan_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.Operation.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.delete_unary(**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/{organization=organizations/*}/global/rolloutPlans/{rollout_plan}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.delete_unary( + compute.DeleteOrganizationRolloutPlanRequest(), + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + +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 = OrganizationRolloutPlansClient( + 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.GetOrganizationRolloutPlanRequest, +): + transport_class = transports.OrganizationRolloutPlansRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout_plan"] = "" + 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["organization"] = "organization_value" + jsonified_request["rolloutPlan"] = "rollout_plan_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 "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rolloutPlan" in jsonified_request + assert jsonified_request["rolloutPlan"] == "rollout_plan_value" + + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlan() + # 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.RolloutPlan.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "organization", + "rolloutPlan", + ) + ) + ) + + +def test_get_rest_flattened(): + client = OrganizationRolloutPlansClient( + 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.RolloutPlan() + + # get arguments that satisfy an http rule for this method + sample_request = { + "organization": "organizations/sample1", + "rollout_plan": "sample2", + } + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout_plan="rollout_plan_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.RolloutPlan.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/{organization=organizations/*}/global/rolloutPlans/{rollout_plan}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.GetOrganizationRolloutPlanRequest(), + organization="organization_value", + rollout_plan="rollout_plan_value", + ) + + +def test_insert_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 = OrganizationRolloutPlansClient( + 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.insert 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.insert] = mock_rpc + + request = {} + client.insert(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert(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_insert_rest_required_fields( + request_type=compute.InsertOrganizationRolloutPlanRequest, +): + transport_class = transports.OrganizationRolloutPlansRestTransport + + request_init = {} + request_init["organization"] = "" + 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() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.insert(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_insert_rest_unset_required_fields(): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "organization", + "rolloutPlanResource", + ) + ) + ) + + +def test_insert_rest_flattened(): + client = OrganizationRolloutPlansClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_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.Operation.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.insert(**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/{organization=organizations/*}/global/rolloutPlans" + % client.transport._host, + args[1], + ) + + +def test_insert_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.insert( + compute.InsertOrganizationRolloutPlanRequest(), + organization="organization_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_value" + ), + ) + + +def test_insert_unary_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 = OrganizationRolloutPlansClient( + 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.insert 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.insert] = mock_rpc + + request = {} + client.insert_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert_unary(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_insert_unary_rest_required_fields( + request_type=compute.InsertOrganizationRolloutPlanRequest, +): + transport_class = transports.OrganizationRolloutPlansRestTransport + + request_init = {} + request_init["organization"] = "" + 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() + ).insert._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).insert._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.insert_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_insert_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.insert._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "organization", + "rolloutPlanResource", + ) + ) + ) + + +def test_insert_unary_rest_flattened(): + client = OrganizationRolloutPlansClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_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.Operation.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.insert_unary(**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/{organization=organizations/*}/global/rolloutPlans" + % client.transport._host, + args[1], + ) + + +def test_insert_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.insert_unary( + compute.InsertOrganizationRolloutPlanRequest(), + organization="organization_value", + rollout_plan_resource=compute.RolloutPlan( + creation_timestamp="creation_timestamp_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 = OrganizationRolloutPlansClient( + 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.ListOrganizationRolloutPlansRequest, +): + transport_class = transports.OrganizationRolloutPlansRestTransport + + request_init = {} + request_init["organization"] = "" + 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["organization"] = "organization_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 "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlansListResponse() + # 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.RolloutPlansListResponse.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 sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("organization",)) + ) + + +def test_list_rest_flattened(): + client = OrganizationRolloutPlansClient( + 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.RolloutPlansListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_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.RolloutPlansListResponse.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/{organization=organizations/*}/global/rolloutPlans" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.ListOrganizationRolloutPlansRequest(), + organization="organization_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = OrganizationRolloutPlansClient( + 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.RolloutPlansListResponse( + items=[ + compute.RolloutPlan(), + compute.RolloutPlan(), + compute.RolloutPlan(), + ], + next_page_token="abc", + ), + compute.RolloutPlansListResponse( + items=[], + next_page_token="def", + ), + compute.RolloutPlansListResponse( + items=[ + compute.RolloutPlan(), + ], + next_page_token="ghi", + ), + compute.RolloutPlansListResponse( + items=[ + compute.RolloutPlan(), + compute.RolloutPlan(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RolloutPlansListResponse.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 = {"organization": "organizations/sample1"} + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.RolloutPlan) 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.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationRolloutPlansClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationRolloutPlansClient( + 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 = OrganizationRolloutPlansClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationRolloutPlansClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OrganizationRolloutPlansClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationRolloutPlansRestTransport, + ], +) +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 = OrganizationRolloutPlansClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_delete_rest_bad_request( + request_type=compute.DeleteOrganizationRolloutPlanRequest, +): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteOrganizationRolloutPlanRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutPlansRestInterceptor(), + ) + client = OrganizationRolloutPlansClient(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.OrganizationRolloutPlansRestInterceptor, "post_delete" + ) as post, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, + "post_delete_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, "pre_delete" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteOrganizationRolloutPlanRequest.pb( + compute.DeleteOrganizationRolloutPlanRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteOrganizationRolloutPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetOrganizationRolloutPlanRequest): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.GetOrganizationRolloutPlanRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout_plan": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlan( + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + location_scope="location_scope_value", + name="name_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_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.RolloutPlan.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.RolloutPlan) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.location_scope == "location_scope_value" + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutPlansRestInterceptor(), + ) + client = OrganizationRolloutPlansClient(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.OrganizationRolloutPlansRestInterceptor, "post_get" + ) as post, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, "pre_get" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetOrganizationRolloutPlanRequest.pb( + compute.GetOrganizationRolloutPlanRequest() + ) + 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.RolloutPlan.to_json(compute.RolloutPlan()) + req.return_value.content = return_value + + request = compute.GetOrganizationRolloutPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RolloutPlan() + post_with_metadata.return_value = compute.RolloutPlan(), 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_insert_rest_bad_request( + request_type=compute.InsertOrganizationRolloutPlanRequest, +): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.insert(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertOrganizationRolloutPlanRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request_init["rollout_plan_resource"] = { + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "id": 205, + "kind": "kind_value", + "location_scope": "location_scope_value", + "name": "name_value", + "self_link": "self_link_value", + "self_link_with_id": "self_link_with_id_value", + "waves": [ + { + "display_name": "display_name_value", + "number": 649, + "orchestration_options": { + "delays": [ + { + "delimiter": "delimiter_value", + "duration": "duration_value", + "type_": "type__value", + } + ], + "max_concurrent_locations": 2579, + "max_concurrent_resources_per_location": 3968, + }, + "selectors": [ + { + "location_selector": { + "included_locations": [ + "included_locations_value1", + "included_locations_value2", + ] + }, + "resource_hierarchy_selector": { + "included_folders": [ + "included_folders_value1", + "included_folders_value2", + ], + "included_organizations": [ + "included_organizations_value1", + "included_organizations_value2", + ], + "included_projects": [ + "included_projects_value1", + "included_projects_value2", + ], + }, + } + ], + "validation": { + "time_based_validation_metadata": { + "wait_duration": "wait_duration_value" + }, + "type_": "type__value", + }, + } + ], + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertOrganizationRolloutPlanRequest.meta.fields[ + "rollout_plan_resource" + ] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init[ + "rollout_plan_resource" + ].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["rollout_plan_resource"][field])): + del request_init["rollout_plan_resource"][field][i][subfield] + else: + del request_init["rollout_plan_resource"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.insert(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_insert_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutPlansRestInterceptor(), + ) + client = OrganizationRolloutPlansClient(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.OrganizationRolloutPlansRestInterceptor, "post_insert" + ) as post, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, + "post_insert_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, "pre_insert" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.InsertOrganizationRolloutPlanRequest.pb( + compute.InsertOrganizationRolloutPlanRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.InsertOrganizationRolloutPlanRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.insert( + 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.ListOrganizationRolloutPlansRequest, +): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.ListOrganizationRolloutPlansRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RolloutPlansListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_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.RolloutPlansListResponse.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.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutPlansRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutPlansRestInterceptor(), + ) + client = OrganizationRolloutPlansClient(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.OrganizationRolloutPlansRestInterceptor, "post_list" + ) as post, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, + "post_list_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutPlansRestInterceptor, "pre_list" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListOrganizationRolloutPlansRequest.pb( + compute.ListOrganizationRolloutPlansRequest() + ) + 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.RolloutPlansListResponse.to_json( + compute.RolloutPlansListResponse() + ) + req.return_value.content = return_value + + request = compute.ListOrganizationRolloutPlansRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RolloutPlansListResponse() + post_with_metadata.return_value = compute.RolloutPlansListResponse(), 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 = OrganizationRolloutPlansClient( + 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_delete_unary_empty_call_rest(): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete), "__call__") as call: + client.delete_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.DeleteOrganizationRolloutPlanRequest() + 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_get_empty_call_rest(): + client = OrganizationRolloutPlansClient( + 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.GetOrganizationRolloutPlanRequest() + 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_insert_unary_empty_call_rest(): + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.insert), "__call__") as call: + client.insert_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.InsertOrganizationRolloutPlanRequest() + 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 = OrganizationRolloutPlansClient( + 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.ListOrganizationRolloutPlansRequest() + assert args[0] == request_msg + + +def test_organization_rollout_plans_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OrganizationRolloutPlansTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_organization_rollout_plans_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.organization_rollout_plans.transports.OrganizationRolloutPlansTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.OrganizationRolloutPlansTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "delete", + "get", + "insert", + "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_organization_rollout_plans_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.organization_rollout_plans.transports.OrganizationRolloutPlansTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationRolloutPlansTransport( + 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", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_organization_rollout_plans_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.organization_rollout_plans.transports.OrganizationRolloutPlansTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationRolloutPlansTransport() + adc.assert_called_once() + + +def test_organization_rollout_plans_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) + OrganizationRolloutPlansClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_organization_rollout_plans_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.OrganizationRolloutPlansRestTransport( + 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_organization_rollout_plans_host_no_port(transport_name): + client = OrganizationRolloutPlansClient( + 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_organization_rollout_plans_host_with_port(transport_name): + client = OrganizationRolloutPlansClient( + 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_organization_rollout_plans_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OrganizationRolloutPlansClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OrganizationRolloutPlansClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + session1 = client1.transport.insert._session + session2 = client2.transport.insert._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 = OrganizationRolloutPlansClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = OrganizationRolloutPlansClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutPlansClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = OrganizationRolloutPlansClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = OrganizationRolloutPlansClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutPlansClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = OrganizationRolloutPlansClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = OrganizationRolloutPlansClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutPlansClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = OrganizationRolloutPlansClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = OrganizationRolloutPlansClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutPlansClient.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 = OrganizationRolloutPlansClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = OrganizationRolloutPlansClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutPlansClient.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.OrganizationRolloutPlansTransport, "_prep_wrapped_messages" + ) as prep: + client = OrganizationRolloutPlansClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.OrganizationRolloutPlansTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = OrganizationRolloutPlansClient.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 = OrganizationRolloutPlansClient( + 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 = OrganizationRolloutPlansClient( + 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", + [ + ( + OrganizationRolloutPlansClient, + transports.OrganizationRolloutPlansRestTransport, + ), + ], +) +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_organization_rollouts.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_organization_rollouts.py new file mode 100644 index 000000000000..d361d1c2af44 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_organization_rollouts.py @@ -0,0 +1,5469 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +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 + +import google.api_core.extended_operation as extended_operation # type: ignore +import google.auth +from google.api_core import ( + client_options, + future, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.organization_rollouts import ( + OrganizationRolloutsClient, + 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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert OrganizationRolloutsClient._get_default_mtls_endpoint(None) is None + assert ( + OrganizationRolloutsClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationRolloutsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + OrganizationRolloutsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationRolloutsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + OrganizationRolloutsClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + OrganizationRolloutsClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert OrganizationRolloutsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert OrganizationRolloutsClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert OrganizationRolloutsClient._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: + OrganizationRolloutsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert OrganizationRolloutsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert OrganizationRolloutsClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert OrganizationRolloutsClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert OrganizationRolloutsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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): + OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._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 OrganizationRolloutsClient._get_client_cert_source(None, False) is None + assert ( + OrganizationRolloutsClient._get_client_cert_source( + mock_provided_cert_source, False + ) + is None + ) + assert ( + OrganizationRolloutsClient._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 ( + OrganizationRolloutsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + OrganizationRolloutsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + OrganizationRolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = OrganizationRolloutsClient._DEFAULT_UNIVERSE + default_endpoint = OrganizationRolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = OrganizationRolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + OrganizationRolloutsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + OrganizationRolloutsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == OrganizationRolloutsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationRolloutsClient._get_api_endpoint( + None, None, default_universe, "auto" + ) + == default_endpoint + ) + assert ( + OrganizationRolloutsClient._get_api_endpoint( + None, None, default_universe, "always" + ) + == OrganizationRolloutsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationRolloutsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == OrganizationRolloutsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + OrganizationRolloutsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + OrganizationRolloutsClient._get_api_endpoint( + None, None, default_universe, "never" + ) + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + OrganizationRolloutsClient._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 ( + OrganizationRolloutsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + OrganizationRolloutsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + OrganizationRolloutsClient._get_universe_domain(None, None) + == OrganizationRolloutsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + OrganizationRolloutsClient._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 = OrganizationRolloutsClient(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 = OrganizationRolloutsClient(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", + [ + (OrganizationRolloutsClient, "rest"), + ], +) +def test_organization_rollouts_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.OrganizationRolloutsRestTransport, "rest"), + ], +) +def test_organization_rollouts_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", + [ + (OrganizationRolloutsClient, "rest"), + ], +) +def test_organization_rollouts_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_organization_rollouts_client_get_transport_class(): + transport = OrganizationRolloutsClient.get_transport_class() + available_transports = [ + transports.OrganizationRolloutsRestTransport, + ] + assert transport in available_transports + + transport = OrganizationRolloutsClient.get_transport_class("rest") + assert transport == transports.OrganizationRolloutsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + OrganizationRolloutsClient, + transports.OrganizationRolloutsRestTransport, + "rest", + ), + ], +) +@mock.patch.object( + OrganizationRolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutsClient), +) +def test_organization_rollouts_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(OrganizationRolloutsClient, "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(OrganizationRolloutsClient, "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", + [ + ( + OrganizationRolloutsClient, + transports.OrganizationRolloutsRestTransport, + "rest", + "true", + ), + ( + OrganizationRolloutsClient, + transports.OrganizationRolloutsRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + OrganizationRolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_organization_rollouts_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", [OrganizationRolloutsClient]) +@mock.patch.object( + OrganizationRolloutsClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(OrganizationRolloutsClient), +) +def test_organization_rollouts_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", [OrganizationRolloutsClient]) +@mock.patch.object( + OrganizationRolloutsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(OrganizationRolloutsClient), +) +def test_organization_rollouts_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = OrganizationRolloutsClient._DEFAULT_UNIVERSE + default_endpoint = OrganizationRolloutsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = OrganizationRolloutsClient._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", + [ + ( + OrganizationRolloutsClient, + transports.OrganizationRolloutsRestTransport, + "rest", + ), + ], +) +def test_organization_rollouts_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", + [ + ( + OrganizationRolloutsClient, + transports.OrganizationRolloutsRestTransport, + "rest", + None, + ), + ], +) +def test_organization_rollouts_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_advance_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 = OrganizationRolloutsClient( + 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.advance 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.advance] = mock_rpc + + request = {} + client.advance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.advance(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_advance_rest_required_fields( + request_type=compute.AdvanceOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).advance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).advance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "current_wave_number", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.advance(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_advance_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.advance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "currentWaveNumber", + "requestId", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_advance_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.advance(**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/{organization=organizations/*}/global/rollouts/{rollout}/advance" + % client.transport._host, + args[1], + ) + + +def test_advance_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.advance( + compute.AdvanceOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_advance_unary_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 = OrganizationRolloutsClient( + 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.advance 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.advance] = mock_rpc + + request = {} + client.advance_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.advance_unary(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_advance_unary_rest_required_fields( + request_type=compute.AdvanceOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).advance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).advance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "current_wave_number", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.advance_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_advance_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.advance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "currentWaveNumber", + "requestId", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_advance_unary_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.advance_unary(**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/{organization=organizations/*}/global/rollouts/{rollout}/advance" + % client.transport._host, + args[1], + ) + + +def test_advance_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.advance_unary( + compute.AdvanceOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_cancel_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 = OrganizationRolloutsClient( + 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.cancel 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.cancel] = mock_rpc + + request = {} + client.cancel(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.cancel(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_cancel_rest_required_fields( + request_type=compute.CancelOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).cancel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.cancel(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "rollback", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_cancel_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.cancel(**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/{organization=organizations/*}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_cancel_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.cancel( + compute.CancelOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_cancel_unary_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 = OrganizationRolloutsClient( + 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.cancel 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.cancel] = mock_rpc + + request = {} + client.cancel_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.cancel_unary(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_cancel_unary_rest_required_fields( + request_type=compute.CancelOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).cancel._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).cancel._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.cancel_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_cancel_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.cancel._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "rollback", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_cancel_unary_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.cancel_unary(**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/{organization=organizations/*}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_cancel_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.cancel_unary( + compute.CancelOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_delete_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 = OrganizationRolloutsClient( + 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.delete 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.delete] = mock_rpc + + request = {} + client.delete(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(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_delete_rest_required_fields( + request_type=compute.DeleteOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # 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": "delete", + "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.Operation.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.delete(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_delete_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.delete(**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/{organization=organizations/*}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_delete_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.delete( + compute.DeleteOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_delete_unary_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 = OrganizationRolloutsClient( + 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.delete 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.delete] = mock_rpc + + request = {} + client.delete_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(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_delete_unary_rest_required_fields( + request_type=compute.DeleteOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).delete._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # 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": "delete", + "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.Operation.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.delete_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_delete_unary_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.delete_unary(**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/{organization=organizations/*}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_delete_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.delete_unary( + compute.DeleteOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +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 = OrganizationRolloutsClient( + 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.GetOrganizationRolloutRequest): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_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 "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Rollout() + # 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.Rollout.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_get_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Rollout() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Rollout.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/{organization=organizations/*}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.GetOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_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 = OrganizationRolloutsClient( + 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.ListOrganizationRolloutsRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + 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["organization"] = "organization_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 "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.OrganizationRolloutsListResponse() + # 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.OrganizationRolloutsListResponse.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 sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("organization",)) + ) + + +def test_list_rest_flattened(): + client = OrganizationRolloutsClient( + 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.OrganizationRolloutsListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_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.OrganizationRolloutsListResponse.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/{organization=organizations/*}/global/rollouts" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.ListOrganizationRolloutsRequest(), + organization="organization_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.OrganizationRolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + compute.Rollout(), + ], + next_page_token="abc", + ), + compute.OrganizationRolloutsListResponse( + items=[], + next_page_token="def", + ), + compute.OrganizationRolloutsListResponse( + items=[ + compute.Rollout(), + ], + next_page_token="ghi", + ), + compute.OrganizationRolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.OrganizationRolloutsListResponse.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 = {"organization": "organizations/sample1"} + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.Rollout) 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_pause_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 = OrganizationRolloutsClient( + 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.pause 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.pause] = mock_rpc + + request = {} + client.pause(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.pause(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_pause_rest_required_fields( + request_type=compute.PauseOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).pause._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.pause(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_pause_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.pause._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_pause_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.pause(**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/{organization=organizations/*}/global/rollouts/{rollout}/pause" + % client.transport._host, + args[1], + ) + + +def test_pause_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.pause( + compute.PauseOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_pause_unary_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 = OrganizationRolloutsClient( + 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.pause 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.pause] = mock_rpc + + request = {} + client.pause_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.pause_unary(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_pause_unary_rest_required_fields( + request_type=compute.PauseOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).pause._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.pause_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_pause_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.pause._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_pause_unary_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.pause_unary(**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/{organization=organizations/*}/global/rollouts/{rollout}/pause" + % client.transport._host, + args[1], + ) + + +def test_pause_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.pause_unary( + compute.PauseOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_resume_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 = OrganizationRolloutsClient( + 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.resume 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.resume] = mock_rpc + + request = {} + client.resume(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.resume(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_resume_rest_required_fields( + request_type=compute.ResumeOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).resume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.resume(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_resume_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resume._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_resume_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.resume(**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/{organization=organizations/*}/global/rollouts/{rollout}/resume" + % client.transport._host, + args[1], + ) + + +def test_resume_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.resume( + compute.ResumeOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_resume_unary_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 = OrganizationRolloutsClient( + 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.resume 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.resume] = mock_rpc + + request = {} + client.resume_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.resume_unary(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_resume_unary_rest_required_fields( + request_type=compute.ResumeOrganizationRolloutRequest, +): + transport_class = transports.OrganizationRolloutsRestTransport + + request_init = {} + request_init["organization"] = "" + request_init["rollout"] = "" + 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() + ).resume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["organization"] = "organization_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "organization" in jsonified_request + assert jsonified_request["organization"] == "organization_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.resume_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_resume_unary_rest_unset_required_fields(): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resume._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "organization", + "rollout", + ) + ) + ) + + +def test_resume_unary_rest_flattened(): + client = OrganizationRolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"organization": "organizations/sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + organization="organization_value", + rollout="rollout_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.Operation.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.resume_unary(**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/{organization=organizations/*}/global/rollouts/{rollout}/resume" + % client.transport._host, + args[1], + ) + + +def test_resume_unary_rest_flattened_error(transport: str = "rest"): + client = OrganizationRolloutsClient( + 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.resume_unary( + compute.ResumeOrganizationRolloutRequest(), + organization="organization_value", + rollout="rollout_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationRolloutsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = OrganizationRolloutsClient( + 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 = OrganizationRolloutsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = OrganizationRolloutsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = OrganizationRolloutsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.OrganizationRolloutsRestTransport, + ], +) +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 = OrganizationRolloutsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_advance_rest_bad_request( + request_type=compute.AdvanceOrganizationRolloutRequest, +): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.advance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AdvanceOrganizationRolloutRequest, + dict, + ], +) +def test_advance_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.advance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_advance_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_advance" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_advance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_advance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AdvanceOrganizationRolloutRequest.pb( + compute.AdvanceOrganizationRolloutRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.AdvanceOrganizationRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.advance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_cancel_rest_bad_request(request_type=compute.CancelOrganizationRolloutRequest): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.cancel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CancelOrganizationRolloutRequest, + dict, + ], +) +def test_cancel_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.cancel(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_cancel" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_cancel_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_cancel" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CancelOrganizationRolloutRequest.pb( + compute.CancelOrganizationRolloutRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.CancelOrganizationRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.cancel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_rest_bad_request(request_type=compute.DeleteOrganizationRolloutRequest): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteOrganizationRolloutRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_delete" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_delete" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteOrganizationRolloutRequest.pb( + compute.DeleteOrganizationRolloutRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteOrganizationRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetOrganizationRolloutRequest): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.GetOrganizationRolloutRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Rollout( + cancellation_time="cancellation_time_value", + completion_time="completion_time_value", + creation_timestamp="creation_timestamp_value", + current_wave_number=2045, + description="description_value", + etag="etag_value", + id=205, + kind="kind_value", + name="name_value", + pause_time="pause_time_value", + resume_time="resume_time_value", + rollout_plan="rollout_plan_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + state="state_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.Rollout.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.Rollout) + assert response.cancellation_time == "cancellation_time_value" + assert response.completion_time == "completion_time_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.current_wave_number == 2045 + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.pause_time == "pause_time_value" + assert response.resume_time == "resume_time_value" + assert response.rollout_plan == "rollout_plan_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.state == "state_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_get" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_get" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetOrganizationRolloutRequest.pb( + compute.GetOrganizationRolloutRequest() + ) + 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.Rollout.to_json(compute.Rollout()) + req.return_value.content = return_value + + request = compute.GetOrganizationRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Rollout() + post_with_metadata.return_value = compute.Rollout(), 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.ListOrganizationRolloutsRequest): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.ListOrganizationRolloutsRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.OrganizationRolloutsListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_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.OrganizationRolloutsListResponse.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.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_list" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_list" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListOrganizationRolloutsRequest.pb( + compute.ListOrganizationRolloutsRequest() + ) + 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.OrganizationRolloutsListResponse.to_json( + compute.OrganizationRolloutsListResponse() + ) + req.return_value.content = return_value + + request = compute.ListOrganizationRolloutsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.OrganizationRolloutsListResponse() + post_with_metadata.return_value = ( + compute.OrganizationRolloutsListResponse(), + 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_pause_rest_bad_request(request_type=compute.PauseOrganizationRolloutRequest): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.pause(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PauseOrganizationRolloutRequest, + dict, + ], +) +def test_pause_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.pause(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_pause_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_pause" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_pause_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_pause" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.PauseOrganizationRolloutRequest.pb( + compute.PauseOrganizationRolloutRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.PauseOrganizationRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.pause( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_resume_rest_bad_request(request_type=compute.ResumeOrganizationRolloutRequest): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.resume(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ResumeOrganizationRolloutRequest, + dict, + ], +) +def test_resume_rest_call_success(request_type): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"organization": "organizations/sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.resume(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_resume_rest_interceptors(null_interceptor): + transport = transports.OrganizationRolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.OrganizationRolloutsRestInterceptor(), + ) + client = OrganizationRolloutsClient(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.OrganizationRolloutsRestInterceptor, "post_resume" + ) as post, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "post_resume_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.OrganizationRolloutsRestInterceptor, "pre_resume" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ResumeOrganizationRolloutRequest.pb( + compute.ResumeOrganizationRolloutRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.ResumeOrganizationRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.resume( + 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 = OrganizationRolloutsClient( + 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_advance_unary_empty_call_rest(): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.advance), "__call__") as call: + client.advance_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AdvanceOrganizationRolloutRequest() + 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_cancel_unary_empty_call_rest(): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.cancel), "__call__") as call: + client.cancel_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.CancelOrganizationRolloutRequest() + 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_delete_unary_empty_call_rest(): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete), "__call__") as call: + client.delete_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.DeleteOrganizationRolloutRequest() + 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_get_empty_call_rest(): + client = OrganizationRolloutsClient( + 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.GetOrganizationRolloutRequest() + 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 = OrganizationRolloutsClient( + 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.ListOrganizationRolloutsRequest() + 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_pause_unary_empty_call_rest(): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause), "__call__") as call: + client.pause_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PauseOrganizationRolloutRequest() + 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_resume_unary_empty_call_rest(): + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume), "__call__") as call: + client.resume_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ResumeOrganizationRolloutRequest() + assert args[0] == request_msg + + +def test_organization_rollouts_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.OrganizationRolloutsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_organization_rollouts_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.organization_rollouts.transports.OrganizationRolloutsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.OrganizationRolloutsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "advance", + "cancel", + "delete", + "get", + "list", + "pause", + "resume", + ) + 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_organization_rollouts_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.organization_rollouts.transports.OrganizationRolloutsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationRolloutsTransport( + 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", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id="octopus", + ) + + +def test_organization_rollouts_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.organization_rollouts.transports.OrganizationRolloutsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.OrganizationRolloutsTransport() + adc.assert_called_once() + + +def test_organization_rollouts_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) + OrganizationRolloutsClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=( + "https://www.googleapis.com/auth/compute", + "https://www.googleapis.com/auth/cloud-platform", + ), + quota_project_id=None, + ) + + +def test_organization_rollouts_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.OrganizationRolloutsRestTransport( + 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_organization_rollouts_host_no_port(transport_name): + client = OrganizationRolloutsClient( + 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_organization_rollouts_host_with_port(transport_name): + client = OrganizationRolloutsClient( + 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_organization_rollouts_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = OrganizationRolloutsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = OrganizationRolloutsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.advance._session + session2 = client2.transport.advance._session + assert session1 != session2 + session1 = client1.transport.cancel._session + session2 = client2.transport.cancel._session + assert session1 != session2 + session1 = client1.transport.delete._session + session2 = client2.transport.delete._session + assert session1 != session2 + 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 + session1 = client1.transport.pause._session + session2 = client2.transport.pause._session + assert session1 != session2 + session1 = client1.transport.resume._session + session2 = client2.transport.resume._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = OrganizationRolloutsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = OrganizationRolloutsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = OrganizationRolloutsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = OrganizationRolloutsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = OrganizationRolloutsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = OrganizationRolloutsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = OrganizationRolloutsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = OrganizationRolloutsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutsClient.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 = OrganizationRolloutsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = OrganizationRolloutsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = OrganizationRolloutsClient.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.OrganizationRolloutsTransport, "_prep_wrapped_messages" + ) as prep: + client = OrganizationRolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.OrganizationRolloutsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = OrganizationRolloutsClient.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 = OrganizationRolloutsClient( + 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 = OrganizationRolloutsClient( + 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", + [ + (OrganizationRolloutsClient, transports.OrganizationRolloutsRestTransport), + ], +) +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_project_views.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_project_views.py new file mode 100644 index 000000000000..00ed3185b09b --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_project_views.py @@ -0,0 +1,1914 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +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 + +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.project_views import ( + ProjectViewsClient, + 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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert ProjectViewsClient._get_default_mtls_endpoint(None) is None + assert ( + ProjectViewsClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint + ) + assert ( + ProjectViewsClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ProjectViewsClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ProjectViewsClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ProjectViewsClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + assert ( + ProjectViewsClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert ProjectViewsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ProjectViewsClient._read_environment_variables() == (True, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ProjectViewsClient._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: + ProjectViewsClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ProjectViewsClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ProjectViewsClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ProjectViewsClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ProjectViewsClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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): + ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._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 ProjectViewsClient._get_client_cert_source(None, False) is None + assert ( + ProjectViewsClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ProjectViewsClient._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 ( + ProjectViewsClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ProjectViewsClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ProjectViewsClient._DEFAULT_UNIVERSE + default_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ProjectViewsClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ProjectViewsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ProjectViewsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ProjectViewsClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ProjectViewsClient._get_api_endpoint(None, None, default_universe, "always") + == ProjectViewsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ProjectViewsClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ProjectViewsClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ProjectViewsClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ProjectViewsClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ProjectViewsClient._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 ( + ProjectViewsClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ProjectViewsClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ProjectViewsClient._get_universe_domain(None, None) + == ProjectViewsClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ProjectViewsClient._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 = ProjectViewsClient(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 = ProjectViewsClient(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", + [ + (ProjectViewsClient, "rest"), + ], +) +def test_project_views_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.ProjectViewsRestTransport, "rest"), + ], +) +def test_project_views_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", + [ + (ProjectViewsClient, "rest"), + ], +) +def test_project_views_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_project_views_client_get_transport_class(): + transport = ProjectViewsClient.get_transport_class() + available_transports = [ + transports.ProjectViewsRestTransport, + ] + assert transport in available_transports + + transport = ProjectViewsClient.get_transport_class("rest") + assert transport == transports.ProjectViewsRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest"), + ], +) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test_project_views_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(ProjectViewsClient, "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(ProjectViewsClient, "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", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", "true"), + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", "false"), + ], +) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_project_views_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", [ProjectViewsClient]) +@mock.patch.object( + ProjectViewsClient, "DEFAULT_ENDPOINT", modify_default_endpoint(ProjectViewsClient) +) +def test_project_views_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", [ProjectViewsClient]) +@mock.patch.object( + ProjectViewsClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ProjectViewsClient), +) +def test_project_views_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ProjectViewsClient._DEFAULT_UNIVERSE + default_endpoint = ProjectViewsClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ProjectViewsClient._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", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest"), + ], +) +def test_project_views_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", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport, "rest", None), + ], +) +def test_project_views_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 = ProjectViewsClient( + 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.GetProjectViewRequest): + transport_class = transports.ProjectViewsRestTransport + + request_init = {} + 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["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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + # 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.ProjectView.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "region", + ) + ) + ) + + +def test_get_rest_flattened(): + client = ProjectViewsClient( + 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.ProjectView() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "region": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_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.ProjectView.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}/projectViews" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ProjectViewsClient( + 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.GetProjectViewRequest(), + project="project_value", + region="region_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ProjectViewsClient( + 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 = ProjectViewsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ProjectViewsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ProjectViewsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ProjectViewsRestTransport, + ], +) +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 = ProjectViewsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetProjectViewRequest): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.GetProjectViewRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ProjectView() + + # 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.ProjectView.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.ProjectView) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ProjectViewsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ProjectViewsRestInterceptor(), + ) + client = ProjectViewsClient(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.ProjectViewsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.ProjectViewsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ProjectViewsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetProjectViewRequest.pb(compute.GetProjectViewRequest()) + 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.ProjectView.to_json(compute.ProjectView()) + req.return_value.content = return_value + + request = compute.GetProjectViewRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ProjectView() + post_with_metadata.return_value = compute.ProjectView(), 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_initialize_client_w_rest(): + client = ProjectViewsClient( + 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 = ProjectViewsClient( + 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.GetProjectViewRequest() + assert args[0] == request_msg + + +def test_project_views_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ProjectViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_project_views_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.project_views.transports.ProjectViewsTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ProjectViewsTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("get",) + 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_project_views_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.project_views.transports.ProjectViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectViewsTransport( + 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_project_views_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.project_views.transports.ProjectViewsTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ProjectViewsTransport() + adc.assert_called_once() + + +def test_project_views_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) + ProjectViewsClient() + 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_project_views_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.ProjectViewsRestTransport( + 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_project_views_host_no_port(transport_name): + client = ProjectViewsClient( + 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_project_views_host_with_port(transport_name): + client = ProjectViewsClient( + 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_project_views_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ProjectViewsClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ProjectViewsClient( + credentials=creds2, + transport=transport_name, + ) + session1 = client1.transport.get._session + session2 = client2.transport.get._session + assert session1 != session2 + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = ProjectViewsClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ProjectViewsClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ProjectViewsClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ProjectViewsClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ProjectViewsClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ProjectViewsClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ProjectViewsClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ProjectViewsClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.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 = ProjectViewsClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ProjectViewsClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ProjectViewsClient.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.ProjectViewsTransport, "_prep_wrapped_messages" + ) as prep: + client = ProjectViewsClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ProjectViewsTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ProjectViewsClient.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 = ProjectViewsClient( + 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 = ProjectViewsClient( + 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", + [ + (ProjectViewsClient, transports.ProjectViewsRestTransport), + ], +) +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_backend_services.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_backend_services.py index ee085895921a..5e113671f431 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_backend_services.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_backend_services.py @@ -5926,6 +5926,8 @@ def test_insert_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -6655,6 +6657,8 @@ def test_patch_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -7834,6 +7838,8 @@ def test_update_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_commitments.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_commitments.py index 6a6e36bfdc96..bf0231431bce 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_commitments.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_commitments.py @@ -3924,6 +3924,13 @@ def test_insert_rest_call_success(request_type): ], "name": "name_value", "params": {"resource_manager_tags": {}}, + "persistent_disk_resources": [ + { + "amount": 660, + "dimension_type": "dimension_type_value", + "product_type": "product_type_value", + } + ], "plan": "plan_value", "region": "region_value", "reservations": [ @@ -4008,6 +4015,7 @@ def test_insert_rest_call_success(request_type): "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", @@ -4664,6 +4672,13 @@ def test_update_rest_call_success(request_type): ], "name": "name_value", "params": {"resource_manager_tags": {}}, + "persistent_disk_resources": [ + { + "amount": 660, + "dimension_type": "dimension_type_value", + "product_type": "product_type_value", + } + ], "plan": "plan_value", "region": "region_value", "reservations": [ @@ -4748,6 +4763,7 @@ def test_update_rest_call_success(request_type): "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", @@ -5120,6 +5136,7 @@ def test_update_reservations_rest_call_success(request_type): "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py index 0e8540f516aa..df2b80f3278a 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_disks.py @@ -8916,6 +8916,9 @@ def test_get_rest_call_success(request_type): source_image_id="source_image_id_value", source_instant_snapshot="source_instant_snapshot_value", source_instant_snapshot_id="source_instant_snapshot_id_value", + source_machine_image="source_machine_image_value", + source_machine_image_disk_device_name="source_machine_image_disk_device_name_value", + source_machine_image_id="source_machine_image_id_value", source_snapshot="source_snapshot_value", source_snapshot_id="source_snapshot_id_value", source_storage_object="source_storage_object_value", @@ -8985,6 +8988,12 @@ def test_get_rest_call_success(request_type): assert response.source_image_id == "source_image_id_value" assert response.source_instant_snapshot == "source_instant_snapshot_value" assert response.source_instant_snapshot_id == "source_instant_snapshot_id_value" + assert response.source_machine_image == "source_machine_image_value" + assert ( + response.source_machine_image_disk_device_name + == "source_machine_image_disk_device_name_value" + ) + assert response.source_machine_image_id == "source_machine_image_id_value" assert response.source_snapshot == "source_snapshot_value" assert response.source_snapshot_id == "source_snapshot_id_value" assert response.source_storage_object == "source_storage_object_value" @@ -9287,6 +9296,10 @@ def test_insert_rest_call_success(request_type): "source_image_id": "source_image_id_value", "source_instant_snapshot": "source_instant_snapshot_value", "source_instant_snapshot_id": "source_instant_snapshot_id_value", + "source_machine_image": "source_machine_image_value", + "source_machine_image_disk_device_name": "source_machine_image_disk_device_name_value", + "source_machine_image_encryption_key": {}, + "source_machine_image_id": "source_machine_image_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", @@ -11621,6 +11634,10 @@ def test_update_rest_call_success(request_type): "source_image_id": "source_image_id_value", "source_instant_snapshot": "source_instant_snapshot_value", "source_instant_snapshot_id": "source_instant_snapshot_id_value", + "source_machine_image": "source_machine_image_value", + "source_machine_image_disk_device_name": "source_machine_image_disk_device_name_value", + "source_machine_image_encryption_key": {}, + "source_machine_image_id": "source_machine_image_id_value", "source_snapshot": "source_snapshot_value", "source_snapshot_encryption_key": {}, "source_snapshot_id": "source_snapshot_id_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py index 52b96062e94d..d22f885e2e46 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_instance_group_managers.py @@ -13308,6 +13308,7 @@ def test_apply_updates_to_instances_rest_call_success(request_type): } request_init["region_instance_group_managers_apply_updates_request_resource"] = { "all_instances": True, + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instances": ["instances_value1", "instances_value2"], "minimal_action": "minimal_action_value", "most_disruptive_allowed_action": "most_disruptive_allowed_action_value", @@ -14778,6 +14779,7 @@ def test_insert_rest_call_success(request_type): "recreating": 1060, "refreshing": 1069, "restarting": 1091, + "restarting_in_place": 2013, "resuming": 874, "starting": 876, "stopping": 884, @@ -14909,6 +14911,7 @@ def test_insert_rest_call_success(request_type): "target_stopped_size": 2047, "target_suspended_size": 2251, "update_policy": { + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instance_redistribution_type": "instance_redistribution_type_value", "max_surge": {"calculated": 1042, "fixed": 528, "percent": 753}, "max_unavailable": {}, @@ -15788,6 +15791,7 @@ def test_patch_rest_call_success(request_type): "recreating": 1060, "refreshing": 1069, "restarting": 1091, + "restarting_in_place": 2013, "resuming": 874, "starting": 876, "stopping": 884, @@ -15919,6 +15923,7 @@ def test_patch_rest_call_success(request_type): "target_stopped_size": 2047, "target_suspended_size": 2251, "update_policy": { + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instance_redistribution_type": "instance_redistribution_type_value", "max_surge": {"calculated": 1042, "fixed": 528, "percent": 753}, "max_unavailable": {}, @@ -19307,6 +19312,7 @@ def test_update_rest_call_success(request_type): "recreating": 1060, "refreshing": 1069, "restarting": 1091, + "restarting_in_place": 2013, "resuming": 874, "starting": 876, "stopping": 884, @@ -19438,6 +19444,7 @@ def test_update_rest_call_success(request_type): "target_stopped_size": 2047, "target_suspended_size": 2251, "update_policy": { + "allowed_actions": ["allowed_actions_value1", "allowed_actions_value2"], "instance_redistribution_type": "instance_redistribution_type_value", "max_surge": {"calculated": 1042, "fixed": 528, "percent": 753}, "max_unavailable": {}, 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 e9f0f2a53557..9d35b7e6374d 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 @@ -3069,6 +3069,7 @@ def test_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_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 951921ea7bd1..6395e72637e7 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 @@ -1801,6 +1801,7 @@ def test_bulk_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py index 91b7b33850ca..1b22ee58e039 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_region_url_maps.py @@ -4677,6 +4677,9 @@ def test_insert_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -4695,6 +4698,10 @@ def test_insert_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -5526,6 +5533,9 @@ def test_patch_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -5544,6 +5554,10 @@ def test_patch_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -6203,6 +6217,9 @@ def test_update_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -6221,6 +6238,10 @@ def test_update_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -6673,6 +6694,9 @@ def test_validate_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -6691,6 +6715,10 @@ def test_validate_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reliability_risks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reliability_risks.py new file mode 100644 index 000000000000..62699f780283 --- /dev/null +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reliability_risks.py @@ -0,0 +1,2400 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 asyncio +import json +import math +import os +from collections.abc import AsyncIterable, Iterable, Mapping, Sequence +from unittest import mock +from unittest.mock import AsyncMock + +import grpc +import pytest +from google.api_core import api_core_version +from google.protobuf import json_format +from grpc.experimental import aio +from proto.marshal.rules import wrappers +from proto.marshal.rules.dates import DurationRule, TimestampRule +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 + +import google.auth +from google.api_core import ( + client_options, + gapic_v1, + grpc_helpers, + grpc_helpers_async, + path_template, +) +from google.api_core import exceptions as core_exceptions +from google.api_core import retry as retries +from google.auth import credentials as ga_credentials +from google.auth.exceptions import MutualTLSChannelError +from google.oauth2 import service_account + +from google.cloud.compute_v1beta.services.reliability_risks import ( + ReliabilityRisksClient, + 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 + ) + + +@pytest.fixture(autouse=True) +def set_event_loop(): + try: + asyncio.get_running_loop() + yield + except RuntimeError: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + yield + finally: + loop.close() + asyncio.set_event_loop(None) + + +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" + custom_endpoint = ".custom" + + assert ReliabilityRisksClient._get_default_mtls_endpoint(None) is None + assert ( + ReliabilityRisksClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + ReliabilityRisksClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + ReliabilityRisksClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ReliabilityRisksClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + ReliabilityRisksClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + assert ( + ReliabilityRisksClient._get_default_mtls_endpoint(custom_endpoint) + == custom_endpoint + ) + + +def test__read_environment_variables(): + assert ReliabilityRisksClient._read_environment_variables() == (False, "auto", None) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): + assert ReliabilityRisksClient._read_environment_variables() == ( + True, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): + assert ReliabilityRisksClient._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: + ReliabilityRisksClient._read_environment_variables() + assert ( + str(excinfo.value) + == "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" + ) + else: + assert ReliabilityRisksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + assert ReliabilityRisksClient._read_environment_variables() == ( + False, + "never", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + assert ReliabilityRisksClient._read_environment_variables() == ( + False, + "always", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}): + assert ReliabilityRisksClient._read_environment_variables() == ( + False, + "auto", + None, + ) + + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError) as excinfo: + ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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): + ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._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 ReliabilityRisksClient._get_client_cert_source(None, False) is None + assert ( + ReliabilityRisksClient._get_client_cert_source(mock_provided_cert_source, False) + is None + ) + assert ( + ReliabilityRisksClient._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 ( + ReliabilityRisksClient._get_client_cert_source(None, True) + is mock_default_cert_source + ) + assert ( + ReliabilityRisksClient._get_client_cert_source( + mock_provided_cert_source, "true" + ) + is mock_provided_cert_source + ) + + +@mock.patch.object( + ReliabilityRisksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReliabilityRisksClient), +) +def test__get_api_endpoint(): + api_override = "foo.com" + mock_client_cert_source = mock.Mock() + default_universe = ReliabilityRisksClient._DEFAULT_UNIVERSE + default_endpoint = ReliabilityRisksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ReliabilityRisksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=mock_universe + ) + + assert ( + ReliabilityRisksClient._get_api_endpoint( + api_override, mock_client_cert_source, default_universe, "always" + ) + == api_override + ) + assert ( + ReliabilityRisksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "auto" + ) + == ReliabilityRisksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ReliabilityRisksClient._get_api_endpoint(None, None, default_universe, "auto") + == default_endpoint + ) + assert ( + ReliabilityRisksClient._get_api_endpoint(None, None, default_universe, "always") + == ReliabilityRisksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ReliabilityRisksClient._get_api_endpoint( + None, mock_client_cert_source, default_universe, "always" + ) + == ReliabilityRisksClient.DEFAULT_MTLS_ENDPOINT + ) + assert ( + ReliabilityRisksClient._get_api_endpoint(None, None, mock_universe, "never") + == mock_endpoint + ) + assert ( + ReliabilityRisksClient._get_api_endpoint(None, None, default_universe, "never") + == default_endpoint + ) + + with pytest.raises(MutualTLSChannelError) as excinfo: + ReliabilityRisksClient._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 ( + ReliabilityRisksClient._get_universe_domain( + client_universe_domain, universe_domain_env + ) + == client_universe_domain + ) + assert ( + ReliabilityRisksClient._get_universe_domain(None, universe_domain_env) + == universe_domain_env + ) + assert ( + ReliabilityRisksClient._get_universe_domain(None, None) + == ReliabilityRisksClient._DEFAULT_UNIVERSE + ) + + with pytest.raises(ValueError) as excinfo: + ReliabilityRisksClient._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 = ReliabilityRisksClient(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 = ReliabilityRisksClient(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", + [ + (ReliabilityRisksClient, "rest"), + ], +) +def test_reliability_risks_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.ReliabilityRisksRestTransport, "rest"), + ], +) +def test_reliability_risks_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", + [ + (ReliabilityRisksClient, "rest"), + ], +) +def test_reliability_risks_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_reliability_risks_client_get_transport_class(): + transport = ReliabilityRisksClient.get_transport_class() + available_transports = [ + transports.ReliabilityRisksRestTransport, + ] + assert transport in available_transports + + transport = ReliabilityRisksClient.get_transport_class("rest") + assert transport == transports.ReliabilityRisksRestTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (ReliabilityRisksClient, transports.ReliabilityRisksRestTransport, "rest"), + ], +) +@mock.patch.object( + ReliabilityRisksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReliabilityRisksClient), +) +def test_reliability_risks_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(ReliabilityRisksClient, "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(ReliabilityRisksClient, "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", + [ + ( + ReliabilityRisksClient, + transports.ReliabilityRisksRestTransport, + "rest", + "true", + ), + ( + ReliabilityRisksClient, + transports.ReliabilityRisksRestTransport, + "rest", + "false", + ), + ], +) +@mock.patch.object( + ReliabilityRisksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReliabilityRisksClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_reliability_risks_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", [ReliabilityRisksClient]) +@mock.patch.object( + ReliabilityRisksClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(ReliabilityRisksClient), +) +def test_reliability_risks_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", [ReliabilityRisksClient]) +@mock.patch.object( + ReliabilityRisksClient, + "_DEFAULT_ENDPOINT_TEMPLATE", + modify_default_endpoint_template(ReliabilityRisksClient), +) +def test_reliability_risks_client_client_api_endpoint(client_class): + mock_client_cert_source = client_cert_source_callback + api_override = "foo.com" + default_universe = ReliabilityRisksClient._DEFAULT_UNIVERSE + default_endpoint = ReliabilityRisksClient._DEFAULT_ENDPOINT_TEMPLATE.format( + UNIVERSE_DOMAIN=default_universe + ) + mock_universe = "bar.com" + mock_endpoint = ReliabilityRisksClient._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", + [ + (ReliabilityRisksClient, transports.ReliabilityRisksRestTransport, "rest"), + ], +) +def test_reliability_risks_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", + [ + ( + ReliabilityRisksClient, + transports.ReliabilityRisksRestTransport, + "rest", + None, + ), + ], +) +def test_reliability_risks_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 = ReliabilityRisksClient( + 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.GetReliabilityRiskRequest): + transport_class = transports.ReliabilityRisksRestTransport + + request_init = {} + request_init["project"] = "" + request_init["reliability_risk"] = "" + 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["project"] = "project_value" + jsonified_request["reliabilityRisk"] = "reliability_risk_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "reliabilityRisk" in jsonified_request + assert jsonified_request["reliabilityRisk"] == "reliability_risk_value" + + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ReliabilityRisk() + # 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.ReliabilityRisk.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "reliabilityRisk", + ) + ) + ) + + +def test_get_rest_flattened(): + client = ReliabilityRisksClient( + 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.ReliabilityRisk() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "reliability_risk": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + reliability_risk="reliability_risk_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.ReliabilityRisk.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}/global/reliabilityRisks/{reliability_risk}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = ReliabilityRisksClient( + 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.GetReliabilityRiskRequest(), + project="project_value", + reliability_risk="reliability_risk_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 = ReliabilityRisksClient( + 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.ListReliabilityRisksRequest): + transport_class = transports.ReliabilityRisksRestTransport + + request_init = {} + request_init["project"] = "" + 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["project"] = "project_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.ReliabilityRisksListResponse() + # 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.ReliabilityRisksListResponse.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 sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = ReliabilityRisksClient( + 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.ReliabilityRisksListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_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.ReliabilityRisksListResponse.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}/global/reliabilityRisks" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = ReliabilityRisksClient( + 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.ListReliabilityRisksRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = ReliabilityRisksClient( + 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.ReliabilityRisksListResponse( + items=[ + compute.ReliabilityRisk(), + compute.ReliabilityRisk(), + compute.ReliabilityRisk(), + ], + next_page_token="abc", + ), + compute.ReliabilityRisksListResponse( + items=[], + next_page_token="def", + ), + compute.ReliabilityRisksListResponse( + items=[ + compute.ReliabilityRisk(), + ], + next_page_token="ghi", + ), + compute.ReliabilityRisksListResponse( + items=[ + compute.ReliabilityRisk(), + compute.ReliabilityRisk(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + compute.ReliabilityRisksListResponse.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"} + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.ReliabilityRisk) 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.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReliabilityRisksClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = ReliabilityRisksClient( + 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 = ReliabilityRisksClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = ReliabilityRisksClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = ReliabilityRisksClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.ReliabilityRisksRestTransport, + ], +) +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 = ReliabilityRisksClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_get_rest_bad_request(request_type=compute.GetReliabilityRiskRequest): + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "reliability_risk": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.GetReliabilityRiskRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "reliability_risk": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ReliabilityRisk( + creation_timestamp="creation_timestamp_value", + description="description_value", + id=205, + kind="kind_value", + name="name_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_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.ReliabilityRisk.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.ReliabilityRisk) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReliabilityRisksRestInterceptor(), + ) + client = ReliabilityRisksClient(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.ReliabilityRisksRestInterceptor, "post_get" + ) as post, + mock.patch.object( + transports.ReliabilityRisksRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.ReliabilityRisksRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetReliabilityRiskRequest.pb( + compute.GetReliabilityRiskRequest() + ) + 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.ReliabilityRisk.to_json(compute.ReliabilityRisk()) + req.return_value.content = return_value + + request = compute.GetReliabilityRiskRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ReliabilityRisk() + post_with_metadata.return_value = compute.ReliabilityRisk(), 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.ListReliabilityRisksRequest): + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.ListReliabilityRisksRequest, + dict, + ], +) +def test_list_rest_call_success(request_type): + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.ReliabilityRisksListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_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.ReliabilityRisksListResponse.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.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" + assert response.self_link == "self_link_value" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_rest_interceptors(null_interceptor): + transport = transports.ReliabilityRisksRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.ReliabilityRisksRestInterceptor(), + ) + client = ReliabilityRisksClient(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.ReliabilityRisksRestInterceptor, "post_list" + ) as post, + mock.patch.object( + transports.ReliabilityRisksRestInterceptor, "post_list_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.ReliabilityRisksRestInterceptor, "pre_list" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListReliabilityRisksRequest.pb( + compute.ListReliabilityRisksRequest() + ) + 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.ReliabilityRisksListResponse.to_json( + compute.ReliabilityRisksListResponse() + ) + req.return_value.content = return_value + + request = compute.ListReliabilityRisksRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.ReliabilityRisksListResponse() + post_with_metadata.return_value = ( + compute.ReliabilityRisksListResponse(), + 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 = ReliabilityRisksClient( + 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 = ReliabilityRisksClient( + 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.GetReliabilityRiskRequest() + 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 = ReliabilityRisksClient( + 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.ListReliabilityRisksRequest() + assert args[0] == request_msg + + +def test_reliability_risks_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.ReliabilityRisksTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_reliability_risks_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.compute_v1beta.services.reliability_risks.transports.ReliabilityRisksTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.ReliabilityRisksTransport( + 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_reliability_risks_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.reliability_risks.transports.ReliabilityRisksTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReliabilityRisksTransport( + 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_reliability_risks_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.reliability_risks.transports.ReliabilityRisksTransport._prep_wrapped_messages" + ) as Transport, + ): + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.ReliabilityRisksTransport() + adc.assert_called_once() + + +def test_reliability_risks_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) + ReliabilityRisksClient() + 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_reliability_risks_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.ReliabilityRisksRestTransport( + 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_reliability_risks_host_no_port(transport_name): + client = ReliabilityRisksClient( + 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_reliability_risks_host_with_port(transport_name): + client = ReliabilityRisksClient( + 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_reliability_risks_client_transport_session_collision(transport_name): + creds1 = ga_credentials.AnonymousCredentials() + creds2 = ga_credentials.AnonymousCredentials() + client1 = ReliabilityRisksClient( + credentials=creds1, + transport=transport_name, + ) + client2 = ReliabilityRisksClient( + 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 = ReliabilityRisksClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = ReliabilityRisksClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = ReliabilityRisksClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = ReliabilityRisksClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = ReliabilityRisksClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = ReliabilityRisksClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = ReliabilityRisksClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = ReliabilityRisksClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = ReliabilityRisksClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = ReliabilityRisksClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = ReliabilityRisksClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = ReliabilityRisksClient.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 = ReliabilityRisksClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = ReliabilityRisksClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = ReliabilityRisksClient.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.ReliabilityRisksTransport, "_prep_wrapped_messages" + ) as prep: + client = ReliabilityRisksClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.ReliabilityRisksTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = ReliabilityRisksClient.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 = ReliabilityRisksClient( + 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 = ReliabilityRisksClient( + 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", + [ + (ReliabilityRisksClient, transports.ReliabilityRisksRestTransport), + ], +) +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_reservation_slots.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_slots.py index 92c42e402280..cbc5974970c1 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_slots.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservation_slots.py @@ -3272,6 +3272,7 @@ def test_update_rest_call_success(request_type): "self_link": "self_link_value", "self_link_with_id": "self_link_with_id_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservations.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservations.py index 5924aba25405..2185ed941238 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservations.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_reservations.py @@ -5501,6 +5501,7 @@ def test_insert_rest_call_success(request_type): "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", @@ -6942,6 +6943,7 @@ def test_update_rest_call_success(request_type): "scheduling_type": "scheduling_type_value", "self_link": "self_link_value", "share_settings": { + "folder_map": {}, "project_map": {}, "projects": ["projects_value1", "projects_value2"], "share_type": "share_type_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_rollouts.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_rollouts.py index 86f417fc2d43..52757c85c501 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_rollouts.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_rollouts.py @@ -1125,7 +1125,7 @@ def test_rollouts_client_client_options_credentials_file( ) -def test_cancel_rest_use_cached_wrapped_rpc(): +def test_advance_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: @@ -1139,17 +1139,17 @@ def test_cancel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.cancel in client._transport._wrapped_methods + assert client._transport.advance 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.cancel] = mock_rpc + client._transport._wrapped_methods[client._transport.advance] = mock_rpc request = {} - client.cancel(request) + client.advance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1158,14 +1158,14 @@ def test_cancel_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.cancel(request) + client.advance(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_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): +def test_advance_rest_required_fields(request_type=compute.AdvanceRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1181,7 +1181,7 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1191,12 +1191,12 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "current_wave_number", "request_id", - "rollback", ) ) jsonified_request.update(unset_fields) @@ -1226,7 +1226,7 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1242,24 +1242,24 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.cancel(request) + response = client.advance(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_cancel_rest_unset_required_fields(): +def test_advance_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.cancel._get_unset_required_fields({}) + unset_fields = transport.advance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( + "currentWaveNumber", "requestId", - "rollback", ) ) & set( @@ -1271,7 +1271,7 @@ def test_cancel_rest_unset_required_fields(): ) -def test_cancel_rest_flattened(): +def test_advance_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1302,20 +1302,20 @@ def test_cancel_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel(**mock_args) + client.advance(**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}/global/rollouts/{rollout}" + "%s/compute/beta/projects/{project}/global/rollouts/{rollout}/advance" % client.transport._host, args[1], ) -def test_cancel_rest_flattened_error(transport: str = "rest"): +def test_advance_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1324,14 +1324,14 @@ def test_cancel_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.cancel( - compute.CancelRolloutRequest(), + client.advance( + compute.AdvanceRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_cancel_unary_rest_use_cached_wrapped_rpc(): +def test_advance_unary_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: @@ -1345,17 +1345,17 @@ def test_cancel_unary_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.cancel in client._transport._wrapped_methods + assert client._transport.advance 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.cancel] = mock_rpc + client._transport._wrapped_methods[client._transport.advance] = mock_rpc request = {} - client.cancel_unary(request) + client.advance_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1364,14 +1364,14 @@ def test_cancel_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.cancel_unary(request) + client.advance_unary(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_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutRequest): +def test_advance_unary_rest_required_fields(request_type=compute.AdvanceRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1387,7 +1387,7 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1397,12 +1397,12 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "current_wave_number", "request_id", - "rollback", ) ) jsonified_request.update(unset_fields) @@ -1432,7 +1432,7 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1448,24 +1448,24 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.cancel_unary(request) + response = client.advance_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_cancel_unary_rest_unset_required_fields(): +def test_advance_unary_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.cancel._get_unset_required_fields({}) + unset_fields = transport.advance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( + "currentWaveNumber", "requestId", - "rollback", ) ) & set( @@ -1477,7 +1477,7 @@ def test_cancel_unary_rest_unset_required_fields(): ) -def test_cancel_unary_rest_flattened(): +def test_advance_unary_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1508,20 +1508,20 @@ def test_cancel_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_unary(**mock_args) + client.advance_unary(**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}/global/rollouts/{rollout}" + "%s/compute/beta/projects/{project}/global/rollouts/{rollout}/advance" % client.transport._host, args[1], ) -def test_cancel_unary_rest_flattened_error(transport: str = "rest"): +def test_advance_unary_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1530,14 +1530,14 @@ def test_cancel_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.cancel_unary( - compute.CancelRolloutRequest(), + client.advance_unary( + compute.AdvanceRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_delete_rest_use_cached_wrapped_rpc(): +def test_cancel_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: @@ -1551,17 +1551,17 @@ def test_delete_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete in client._transport._wrapped_methods + assert client._transport.cancel 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.delete] = mock_rpc + client._transport._wrapped_methods[client._transport.cancel] = mock_rpc request = {} - client.delete(request) + client.cancel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1570,14 +1570,14 @@ def test_delete_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete(request) + client.cancel(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_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): +def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1593,7 +1593,7 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1603,9 +1603,14 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1633,7 +1638,7 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1649,21 +1654,26 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete(request) + response = client.cancel(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_rest_unset_required_fields(): +def test_cancel_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete._get_unset_required_fields({}) + unset_fields = transport.cancel._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "requestId", + "rollback", + ) + ) & set( ( "project", @@ -1673,7 +1683,7 @@ def test_delete_rest_unset_required_fields(): ) -def test_delete_rest_flattened(): +def test_cancel_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1704,7 +1714,7 @@ def test_delete_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete(**mock_args) + client.cancel(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -1717,7 +1727,7 @@ def test_delete_rest_flattened(): ) -def test_delete_rest_flattened_error(transport: str = "rest"): +def test_cancel_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1726,14 +1736,14 @@ def test_delete_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete( - compute.DeleteRolloutRequest(), + client.cancel( + compute.CancelRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_delete_unary_rest_use_cached_wrapped_rpc(): +def test_cancel_unary_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: @@ -1747,17 +1757,17 @@ def test_delete_unary_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete in client._transport._wrapped_methods + assert client._transport.cancel 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.delete] = mock_rpc + client._transport._wrapped_methods[client._transport.cancel] = mock_rpc request = {} - client.delete_unary(request) + client.cancel_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1766,14 +1776,14 @@ def test_delete_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_unary(request) + client.cancel_unary(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_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutRequest): +def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1789,7 +1799,7 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1799,9 +1809,14 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1829,7 +1844,7 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1845,21 +1860,26 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_unary(request) + response = client.cancel_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_unary_rest_unset_required_fields(): +def test_cancel_unary_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete._get_unset_required_fields({}) + unset_fields = transport.cancel._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "requestId", + "rollback", + ) + ) & set( ( "project", @@ -1869,7 +1889,7 @@ def test_delete_unary_rest_unset_required_fields(): ) -def test_delete_unary_rest_flattened(): +def test_cancel_unary_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1900,7 +1920,7 @@ def test_delete_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_unary(**mock_args) + client.cancel_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -1913,7 +1933,7 @@ def test_delete_unary_rest_flattened(): ) -def test_delete_unary_rest_flattened_error(transport: str = "rest"): +def test_cancel_unary_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1922,14 +1942,14 @@ def test_delete_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_unary( - compute.DeleteRolloutRequest(), + client.cancel_unary( + compute.CancelRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_get_rest_use_cached_wrapped_rpc(): +def test_delete_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: @@ -1943,29 +1963,33 @@ def test_get_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get in client._transport._wrapped_methods + assert client._transport.delete 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 + client._transport._wrapped_methods[client._transport.delete] = mock_rpc request = {} - client.get(request) + client.delete(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(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.GetRolloutRequest): +def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1981,7 +2005,7 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get._get_unset_required_fields(jsonified_request) + ).delete._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1991,7 +2015,9 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get._get_unset_required_fields(jsonified_request) + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2007,7 +2033,7 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Rollout() + return_value = compute.Operation() # 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 @@ -2019,7 +2045,7 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result @@ -2028,28 +2054,28 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Rollout.pb(return_value) + return_value = compute.Operation.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) + response = client.delete(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_rest_unset_required_fields(): +def test_delete_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get._get_unset_required_fields({}) + unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("requestId",)) & set( ( "project", @@ -2059,7 +2085,7 @@ def test_get_rest_unset_required_fields(): ) -def test_get_rest_flattened(): +def test_delete_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2068,7 +2094,7 @@ def test_get_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Rollout() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "rollout": "sample2"} @@ -2084,13 +2110,13 @@ def test_get_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Rollout.pb(return_value) + return_value = compute.Operation.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) + client.delete(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -2103,7 +2129,7 @@ def test_get_rest_flattened(): ) -def test_get_rest_flattened_error(transport: str = "rest"): +def test_delete_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2112,14 +2138,14 @@ def test_get_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get( - compute.GetRolloutRequest(), + client.delete( + compute.DeleteRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_list_rest_use_cached_wrapped_rpc(): +def test_delete_unary_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: @@ -2133,33 +2159,38 @@ def test_list_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list in client._transport._wrapped_methods + assert client._transport.delete 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 + client._transport._wrapped_methods[client._transport.delete] = mock_rpc request = {} - client.list(request) + client.delete_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(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.ListRolloutsRequest): +def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} request_init["project"] = "" + request_init["rollout"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -2170,31 +2201,26 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list._get_unset_required_fields(jsonified_request) + ).delete._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list._get_unset_required_fields(jsonified_request) + ).delete._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", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2203,7 +2229,7 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RolloutsListResponse() + return_value = compute.Operation() # 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 @@ -2215,7 +2241,7 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result @@ -2224,41 +2250,38 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RolloutsListResponse.pb(return_value) + return_value = compute.Operation.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) + response = client.delete_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_rest_unset_required_fields(): +def test_delete_unary_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list._get_unset_required_fields({}) + unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(("requestId",)) + & set( ( - "filter", - "maxResults", - "orderBy", - "pageToken", - "returnPartialSuccess", + "project", + "rollout", ) ) - & set(("project",)) ) -def test_list_rest_flattened(): +def test_delete_unary_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2267,14 +2290,15 @@ def test_list_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RolloutsListResponse() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method - sample_request = {"project": "sample1"} + sample_request = {"project": "sample1", "rollout": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", + rollout="rollout_value", ) mock_args.update(sample_request) @@ -2282,26 +2306,26 @@ def test_list_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RolloutsListResponse.pb(return_value) + return_value = compute.Operation.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) + client.delete_unary(**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}/global/rollouts" + "%s/compute/beta/projects/{project}/global/rollouts/{rollout}" % client.transport._host, args[1], ) -def test_list_rest_flattened_error(transport: str = "rest"): +def test_delete_unary_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2310,164 +2334,2010 @@ def test_list_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list( - compute.ListRolloutsRequest(), + client.delete_unary( + compute.DeleteRolloutRequest(), project="project_value", + rollout="rollout_value", ) -def test_list_rest_pager(transport: str = "rest"): +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 = RolloutsClient( + 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.GetRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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["project"] = "project_value" + jsonified_request["rollout"] = "rollout_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = compute.Rollout() # 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.RolloutsListResponse( - items=[ - compute.Rollout(), - compute.Rollout(), - compute.Rollout(), - ], - next_page_token="abc", - ), - compute.RolloutsListResponse( - items=[], - next_page_token="def", - ), - compute.RolloutsListResponse( - items=[ - compute.Rollout(), - ], - next_page_token="ghi", - ), - compute.RolloutsListResponse( - items=[ - compute.Rollout(), - compute.Rollout(), - ], - ), + # 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.Rollout.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "rollout", + ) ) - # Two responses for two calls - response = response + response + ) - # Wrap the values into proper Response objs - response = tuple(compute.RolloutsListResponse.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"} +def test_get_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - pager = client.list(request=sample_request) + # 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.Rollout() - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, compute.Rollout) for i in results) + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) - 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 + # 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.Rollout.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}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.GetRolloutRequest(), + project="project_value", + rollout="rollout_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 = RolloutsClient( + 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.ListRolloutsRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + 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["project"] = "project_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutsListResponse() + # 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.RolloutsListResponse.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 sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = RolloutsClient( + 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.RolloutsListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_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.RolloutsListResponse.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}/global/rollouts" + % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.ListRolloutsRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RolloutsClient( + 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.RolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + compute.Rollout(), + ], + next_page_token="abc", + ), + compute.RolloutsListResponse( + items=[], + next_page_token="def", + ), + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + ], + next_page_token="ghi", + ), + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RolloutsListResponse.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"} + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.Rollout) 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_pause_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 = RolloutsClient( + 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.pause 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.pause] = mock_rpc + + request = {} + client.pause(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.pause(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_pause_rest_required_fields(request_type=compute.PauseRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).pause._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.pause(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_pause_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.pause._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_pause_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.pause(**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}/global/rollouts/{rollout}/pause" + % client.transport._host, + args[1], + ) + + +def test_pause_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.pause( + compute.PauseRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_pause_unary_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 = RolloutsClient( + 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.pause 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.pause] = mock_rpc + + request = {} + client.pause_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.pause_unary(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_pause_unary_rest_required_fields(request_type=compute.PauseRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).pause._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.pause_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_pause_unary_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.pause._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_pause_unary_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.pause_unary(**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}/global/rollouts/{rollout}/pause" + % client.transport._host, + args[1], + ) + + +def test_pause_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.pause_unary( + compute.PauseRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_resume_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 = RolloutsClient( + 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.resume 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.resume] = mock_rpc + + request = {} + client.resume(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.resume(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_resume_rest_required_fields(request_type=compute.ResumeRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).resume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.resume(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_resume_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resume._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_resume_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.resume(**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}/global/rollouts/{rollout}/resume" + % client.transport._host, + args[1], + ) + + +def test_resume_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.resume( + compute.ResumeRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_resume_unary_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 = RolloutsClient( + 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.resume 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.resume] = mock_rpc + + request = {} + client.resume_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.resume_unary(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_resume_unary_rest_required_fields(request_type=compute.ResumeRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).resume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.resume_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_resume_unary_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resume._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_resume_unary_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.resume_unary(**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}/global/rollouts/{rollout}/resume" + % client.transport._host, + args[1], + ) + + +def test_resume_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.resume_unary( + compute.ResumeRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RolloutsClient( + 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 = RolloutsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RolloutsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RolloutsRestTransport, + ], +) +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 = RolloutsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_advance_rest_bad_request(request_type=compute.AdvanceRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.advance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AdvanceRolloutRequest, + dict, + ], +) +def test_advance_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.advance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_advance_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(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.RolloutsRestInterceptor, "post_advance") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_advance_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_advance") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AdvanceRolloutRequest.pb(compute.AdvanceRolloutRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.AdvanceRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.advance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.cancel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CancelRolloutRequest, + dict, + ], +) +def test_cancel_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.cancel(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(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.RolloutsRestInterceptor, "post_cancel") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_cancel_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_cancel") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CancelRolloutRequest.pb(compute.CancelRolloutRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.CancelRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.cancel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRolloutRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(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.RolloutsRestInterceptor, "post_delete") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_delete") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRolloutRequest.pb(compute.DeleteRolloutRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRolloutRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = RolloutsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RolloutsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) - # It is an error to provide an api_key and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RolloutsClient( - client_options=options, - transport=transport, + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Rollout( + cancellation_time="cancellation_time_value", + completion_time="completion_time_value", + creation_timestamp="creation_timestamp_value", + current_wave_number=2045, + description="description_value", + etag="etag_value", + id=205, + kind="kind_value", + name="name_value", + pause_time="pause_time_value", + resume_time="resume_time_value", + rollout_plan="rollout_plan_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + state="state_value", ) - # 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 = RolloutsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - # It is an error to provide scopes and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RolloutsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Convert return value to protobuf type + return_value = compute.Rollout.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.Rollout) + assert response.cancellation_time == "cancellation_time_value" + assert response.completion_time == "completion_time_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.current_wave_number == 2045 + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.pause_time == "pause_time_value" + assert response.resume_time == "resume_time_value" + assert response.rollout_plan == "rollout_plan_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.state == "state_value" -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), ) client = RolloutsClient(transport=transport) - assert client.transport is transport + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRolloutRequest.pb(compute.GetRolloutRequest()) + 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.Rollout.to_json(compute.Rollout()) + req.return_value.content = return_value -@pytest.mark.parametrize( - "transport_class", - [ - transports.RolloutsRestTransport, - ], -) -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() + request = compute.GetRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Rollout() + post_with_metadata.return_value = compute.Rollout(), metadata + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = RolloutsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): +def test_list_rest_bad_request(request_type=compute.ListRolloutsRequest): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "rollout": "sample2"} + request_init = {"project": "sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2483,51 +4353,34 @@ def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel(request) + client.list(request) @pytest.mark.parametrize( "request_type", [ - compute.CancelRolloutRequest, + compute.ListRolloutsRequest, dict, ], ) -def test_cancel_rest_call_success(request_type): +def test_list_rest_call_success(request_type): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "rollout": "sample2"} + request_init = {"project": "sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation( - client_operation_id="client_operation_id_value", - creation_timestamp="creation_timestamp_value", - description="description_value", - end_time="end_time_value", - http_error_message="http_error_message_value", - http_error_status_code=2374, - id=205, - insert_time="insert_time_value", - kind="kind_value", - name="name_value", - operation_group_id="operation_group_id_value", - operation_type="operation_type_value", - progress=885, - region="region_value", + return_value = compute.RolloutsListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", self_link="self_link_value", - start_time="start_time_value", - status=compute.Operation.Status.DONE, - status_message="status_message_value", - target_id=947, - target_link="target_link_value", - user="user_value", - zone="zone_value", + unreachables=["unreachables_value"], ) # Wrap the value into a proper Response obj @@ -2535,41 +4388,24 @@ def test_cancel_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RolloutsListResponse.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.cancel(request) + response = client.list(request) # Establish that the response is the type that we expect. - assert isinstance(response, extended_operation.ExtendedOperation) - assert response.client_operation_id == "client_operation_id_value" - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.end_time == "end_time_value" - assert response.http_error_message == "http_error_message_value" - assert response.http_error_status_code == 2374 - assert response.id == 205 - assert response.insert_time == "insert_time_value" - assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.operation_group_id == "operation_group_id_value" - assert response.operation_type == "operation_type_value" - assert response.progress == 885 - assert response.region == "region_value" + assert isinstance(response, pagers.ListPager) + assert response.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" - assert response.start_time == "start_time_value" - assert response.status == compute.Operation.Status.DONE - assert response.status_message == "status_message_value" - assert response.target_id == 947 - assert response.target_link == "target_link_value" - assert response.user == "user_value" - assert response.zone == "zone_value" + assert response.unreachables == ["unreachables_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_cancel_rest_interceptors(null_interceptor): +def test_list_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), @@ -2579,16 +4415,16 @@ def test_cancel_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RolloutsRestInterceptor, "post_cancel") as post, + mock.patch.object(transports.RolloutsRestInterceptor, "post_list") as post, mock.patch.object( - transports.RolloutsRestInterceptor, "post_cancel_with_metadata" + transports.RolloutsRestInterceptor, "post_list_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_cancel") as pre, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_list") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.CancelRolloutRequest.pb(compute.CancelRolloutRequest()) + pb_message = compute.ListRolloutsRequest.pb(compute.ListRolloutsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2599,19 +4435,21 @@ def test_cancel_rest_interceptors(null_interceptor): 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.Operation.to_json(compute.Operation()) + return_value = compute.RolloutsListResponse.to_json( + compute.RolloutsListResponse() + ) req.return_value.content = return_value - request = compute.CancelRolloutRequest() + request = compute.ListRolloutsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Operation() - post_with_metadata.return_value = compute.Operation(), metadata + post.return_value = compute.RolloutsListResponse() + post_with_metadata.return_value = compute.RolloutsListResponse(), metadata - client.cancel( + client.list( request, metadata=[ ("key", "val"), @@ -2624,7 +4462,7 @@ def test_cancel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): +def test_pause_rest_bad_request(request_type=compute.PauseRolloutRequest): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2645,17 +4483,17 @@ def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete(request) + client.pause(request) @pytest.mark.parametrize( "request_type", [ - compute.DeleteRolloutRequest, + compute.PauseRolloutRequest, dict, ], ) -def test_delete_rest_call_success(request_type): +def test_pause_rest_call_success(request_type): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2702,7 +4540,7 @@ def test_delete_rest_call_success(request_type): 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.delete(request) + response = client.pause(request) # Establish that the response is the type that we expect. assert isinstance(response, extended_operation.ExtendedOperation) @@ -2731,7 +4569,7 @@ def test_delete_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_rest_interceptors(null_interceptor): +def test_pause_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), @@ -2741,16 +4579,16 @@ def test_delete_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RolloutsRestInterceptor, "post_delete") as post, + mock.patch.object(transports.RolloutsRestInterceptor, "post_pause") as post, mock.patch.object( - transports.RolloutsRestInterceptor, "post_delete_with_metadata" + transports.RolloutsRestInterceptor, "post_pause_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_delete") as pre, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_pause") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.DeleteRolloutRequest.pb(compute.DeleteRolloutRequest()) + pb_message = compute.PauseRolloutRequest.pb(compute.PauseRolloutRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2764,7 +4602,7 @@ def test_delete_rest_interceptors(null_interceptor): return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.DeleteRolloutRequest() + request = compute.PauseRolloutRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2773,7 +4611,7 @@ def test_delete_rest_interceptors(null_interceptor): post.return_value = compute.Operation() post_with_metadata.return_value = compute.Operation(), metadata - client.delete( + client.pause( request, metadata=[ ("key", "val"), @@ -2786,7 +4624,7 @@ def test_delete_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): +def test_resume_rest_bad_request(request_type=compute.ResumeRolloutRequest): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2807,17 +4645,17 @@ def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): 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) + client.resume(request) @pytest.mark.parametrize( "request_type", [ - compute.GetRolloutRequest, + compute.ResumeRolloutRequest, dict, ], ) -def test_get_rest_call_success(request_type): +def test_resume_rest_call_success(request_type): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2829,20 +4667,29 @@ def test_get_rest_call_success(request_type): # 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.Rollout( - cancellation_time="cancellation_time_value", - completion_time="completion_time_value", + return_value = compute.Operation( + client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", - current_wave_number=2045, description="description_value", - etag="etag_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, id=205, + insert_time="insert_time_value", kind="kind_value", name="name_value", - rollout_plan="rollout_plan_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", self_link="self_link_value", - self_link_with_id="self_link_with_id_value", - state="state_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", ) # Wrap the value into a proper Response obj @@ -2850,32 +4697,41 @@ def test_get_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Rollout.pb(return_value) + return_value = compute.Operation.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) + response = client.resume(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.Rollout) - assert response.cancellation_time == "cancellation_time_value" - assert response.completion_time == "completion_time_value" + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" - assert response.current_wave_number == 2045 assert response.description == "description_value" - assert response.etag == "etag_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 assert response.id == 205 + assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" - assert response.rollout_plan == "rollout_plan_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" assert response.self_link == "self_link_value" - assert response.self_link_with_id == "self_link_with_id_value" - assert response.state == "state_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_rest_interceptors(null_interceptor): +def test_resume_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), @@ -2885,16 +4741,16 @@ def test_get_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RolloutsRestInterceptor, "post_get") as post, + mock.patch.object(transports.RolloutsRestInterceptor, "post_resume") as post, mock.patch.object( - transports.RolloutsRestInterceptor, "post_get_with_metadata" + transports.RolloutsRestInterceptor, "post_resume_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_get") as pre, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_resume") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetRolloutRequest.pb(compute.GetRolloutRequest()) + pb_message = compute.ResumeRolloutRequest.pb(compute.ResumeRolloutRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2905,19 +4761,19 @@ def test_get_rest_interceptors(null_interceptor): 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.Rollout.to_json(compute.Rollout()) + return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.GetRolloutRequest() + request = compute.ResumeRolloutRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Rollout() - post_with_metadata.return_value = compute.Rollout(), metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata - client.get( + client.resume( request, metadata=[ ("key", "val"), @@ -2930,141 +4786,30 @@ def test_get_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_rest_bad_request(request_type=compute.ListRolloutsRequest): +def test_initialize_client_w_rest(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = 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) + assert client is not None -@pytest.mark.parametrize( - "request_type", - [ - compute.ListRolloutsRequest, - dict, - ], -) -def test_list_rest_call_success(request_type): +# 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_advance_unary_empty_call_rest(): client = RolloutsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"project": "sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = compute.RolloutsListResponse( - etag="etag_value", - id="id_value", - next_page_token="next_page_token_value", - self_link="self_link_value", - unreachables=["unreachables_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.RolloutsListResponse.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.etag == "etag_value" - assert response.id == "id_value" - assert response.next_page_token == "next_page_token_value" - assert response.self_link == "self_link_value" - assert response.unreachables == ["unreachables_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_rest_interceptors(null_interceptor): - transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + transport="rest", ) - client = RolloutsClient(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.RolloutsRestInterceptor, "post_list") as post, - mock.patch.object( - transports.RolloutsRestInterceptor, "post_list_with_metadata" - ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_list") as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = compute.ListRolloutsRequest.pb(compute.ListRolloutsRequest()) - 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.RolloutsListResponse.to_json( - compute.RolloutsListResponse() - ) - req.return_value.content = return_value - - request = compute.ListRolloutsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = compute.RolloutsListResponse() - post_with_metadata.return_value = compute.RolloutsListResponse(), metadata - - client.list( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.advance), "__call__") as call: + client.advance_unary(request=None) -def test_initialize_client_w_rest(): - client = RolloutsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - assert client is not None + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AdvanceRolloutRequest() + assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, @@ -3143,6 +4888,44 @@ def test_list_empty_call_rest(): 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_pause_unary_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause), "__call__") as call: + client.pause_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PauseRolloutRequest() + 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_resume_unary_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume), "__call__") as call: + client.resume_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ResumeRolloutRequest() + assert args[0] == request_msg + + def test_rollouts_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -3165,10 +4948,13 @@ def test_rollouts_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( + "advance", "cancel", "delete", "get", "list", + "pause", + "resume", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3312,6 +5098,9 @@ def test_rollouts_client_transport_session_collision(transport_name): credentials=creds2, transport=transport_name, ) + session1 = client1.transport.advance._session + session2 = client2.transport.advance._session + assert session1 != session2 session1 = client1.transport.cancel._session session2 = client2.transport.cancel._session assert session1 != session2 @@ -3324,6 +5113,12 @@ def test_rollouts_client_transport_session_collision(transport_name): session1 = client1.transport.list._session session2 = client2.transport.list._session assert session1 != session2 + session1 = client1.transport.pause._session + session2 = client2.transport.pause._session + assert session1 != session2 + session1 = client1.transport.resume._session + session2 = client2.transport.resume._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py index 495e1e25959e..94f4470e0013 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_routers.py @@ -10202,6 +10202,7 @@ def test_insert_rest_call_success(request_type): { "auto_network_tier": "auto_network_tier_value", "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, "enable_dynamic_port_allocation": True, "enable_endpoint_independent_mapping": True, "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], @@ -11115,6 +11116,7 @@ def test_patch_rest_call_success(request_type): { "auto_network_tier": "auto_network_tier_value", "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, "enable_dynamic_port_allocation": True, "enable_endpoint_independent_mapping": True, "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], @@ -11994,6 +11996,7 @@ def test_preview_rest_call_success(request_type): { "auto_network_tier": "auto_network_tier_value", "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, "enable_dynamic_port_allocation": True, "enable_endpoint_independent_mapping": True, "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], @@ -12526,6 +12529,7 @@ def test_update_rest_call_success(request_type): { "auto_network_tier": "auto_network_tier_value", "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, "enable_dynamic_port_allocation": True, "enable_endpoint_independent_mapping": True, "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_service_attachments.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_service_attachments.py index eaee7cd70e8c..dc688f1a30fe 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_service_attachments.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_service_attachments.py @@ -4339,6 +4339,7 @@ def test_get_rest_call_success(request_type): id=205, kind="kind_value", name="name_value", + nat_ips_per_endpoint=2132, nat_subnets=["nat_subnets_value"], producer_forwarding_rule="producer_forwarding_rule_value", propagated_connection_limit=2868, @@ -4372,6 +4373,7 @@ def test_get_rest_call_success(request_type): assert response.id == 205 assert response.kind == "kind_value" assert response.name == "name_value" + assert response.nat_ips_per_endpoint == 2132 assert response.nat_subnets == ["nat_subnets_value"] assert response.producer_forwarding_rule == "producer_forwarding_rule_value" assert response.propagated_connection_limit == 2868 @@ -4652,6 +4654,7 @@ def test_insert_rest_call_success(request_type): "kind": "kind_value", "metadata": {}, "name": "name_value", + "nat_ips_per_endpoint": 2132, "nat_subnets": ["nat_subnets_value1", "nat_subnets_value2"], "producer_forwarding_rule": "producer_forwarding_rule_value", "propagated_connection_limit": 2868, @@ -5086,6 +5089,7 @@ def test_patch_rest_call_success(request_type): "kind": "kind_value", "metadata": {}, "name": "name_value", + "nat_ips_per_endpoint": 2132, "nat_subnets": ["nat_subnets_value1", "nat_subnets_value2"], "producer_forwarding_rule": "producer_forwarding_rule_value", "propagated_connection_limit": 2868, diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_subnetworks.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_subnetworks.py index 5cbf811b2a75..820085d75de5 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_subnetworks.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_subnetworks.py @@ -5662,6 +5662,7 @@ def test_get_rest_call_success(request_type): ipv6_access_type="ipv6_access_type_value", ipv6_cidr_range="ipv6_cidr_range_value", ipv6_gce_endpoint="ipv6_gce_endpoint_value", + ipv6_network_tier="ipv6_network_tier_value", kind="kind_value", name="name_value", network="network_value", @@ -5711,6 +5712,7 @@ def test_get_rest_call_success(request_type): assert response.ipv6_access_type == "ipv6_access_type_value" assert response.ipv6_cidr_range == "ipv6_cidr_range_value" assert response.ipv6_gce_endpoint == "ipv6_gce_endpoint_value" + assert response.ipv6_network_tier == "ipv6_network_tier_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.network == "network_value" @@ -5977,6 +5979,7 @@ def test_insert_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_cidr_range": "ipv6_cidr_range_value", "ipv6_gce_endpoint": "ipv6_gce_endpoint_value", + "ipv6_network_tier": "ipv6_network_tier_value", "kind": "kind_value", "log_config": { "aggregation_interval": "aggregation_interval_value", @@ -6551,6 +6554,7 @@ def test_patch_rest_call_success(request_type): "ipv6_access_type": "ipv6_access_type_value", "ipv6_cidr_range": "ipv6_cidr_range_value", "ipv6_gce_endpoint": "ipv6_gce_endpoint_value", + "ipv6_network_tier": "ipv6_network_tier_value", "kind": "kind_value", "log_config": { "aggregation_interval": "aggregation_interval_value", diff --git a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py index 1c20ef2120c1..3f4258c3d734 100644 --- a/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py +++ b/packages/google-cloud-compute-v1beta/tests/unit/gapic/compute_v1beta/test_url_maps.py @@ -4889,6 +4889,9 @@ def test_insert_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -4907,6 +4910,10 @@ def test_insert_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -5725,6 +5732,9 @@ def test_patch_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -5743,6 +5753,10 @@ def test_patch_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -6393,6 +6407,9 @@ def test_update_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -6411,6 +6428,10 @@ def test_update_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { @@ -6861,6 +6882,9 @@ def test_validate_rest_call_success(request_type): "abort": {"http_status": 1219, "percentage": 0.10540000000000001}, "delay": {"fixed_delay": {}, "percentage": 0.10540000000000001}, }, + "image_optimization_policy": { + "query_parameter_interpretation": "query_parameter_interpretation_value" + }, "max_stream_duration": {}, "request_mirror_policy": { "backend_service": "backend_service_value", @@ -6879,6 +6903,10 @@ def test_validate_rest_call_success(request_type): "host_rewrite": "host_rewrite_value", "path_prefix_rewrite": "path_prefix_rewrite_value", "path_template_rewrite": "path_template_rewrite_value", + "regex_rewrite": { + "path_pattern": "path_pattern_value", + "path_substitution": "path_substitution_value", + }, }, "weighted_backend_services": [ { diff --git a/packages/google-cloud-compute/google/cloud/compute/__init__.py b/packages/google-cloud-compute/google/cloud/compute/__init__.py index 95463f674400..045c8e11824d 100644 --- a/packages/google-cloud-compute/google/cloud/compute/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute/__init__.py @@ -346,6 +346,7 @@ AddSignedUrlKeyBackendBucketRequest, AddSignedUrlKeyBackendServiceRequest, AdvancedMachineFeatures, + AdvanceRolloutRequest, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, AggregatedListAutoscalersRequest, @@ -469,6 +470,7 @@ BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy, BackendServiceLocalityLoadBalancingPolicyConfigPolicy, BackendServiceLogConfig, + BackendServiceLogConfigLoggingHttpHeader, BackendServiceNetworkPassThroughLbTrafficPolicy, BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity, BackendServiceOrchestrationInfo, @@ -546,6 +548,7 @@ CustomErrorResponsePolicyCustomErrorResponseRule, Data, Date, + DateTime, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -584,6 +587,7 @@ DeleteInterconnectRequest, DeleteLicenseRequest, DeleteMachineImageRequest, + DeleteNamedSetRouterRequest, DeleteNetworkAttachmentRequest, DeleteNetworkEdgeSecurityServiceRequest, DeleteNetworkEndpointGroupRequest, @@ -723,6 +727,7 @@ FlexibleTimeRange, ForwardingRule, ForwardingRuleAggregatedList, + ForwardingRuleAttachedExtension, ForwardingRuleList, ForwardingRuleReference, ForwardingRuleServiceDirectoryRegistration, @@ -841,6 +846,7 @@ GetMachineImageRequest, GetMachineTypeRequest, GetMacsecConfigInterconnectRequest, + GetNamedSetRouterRequest, GetNatIpInfoRouterRequest, GetNatMappingInfoRoutersRequest, GetNetworkAttachmentRequest, @@ -1123,6 +1129,7 @@ InstanceGroupManagerInstanceFlexibilityPolicy, InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection, InstanceGroupManagerInstanceLifecyclePolicy, + InstanceGroupManagerInstanceLifecyclePolicyOnRepair, InstanceGroupManagerList, InstanceGroupManagerResizeRequest, InstanceGroupManagerResizeRequestsListResponse, @@ -1346,6 +1353,7 @@ ListMachineTypesRequest, ListManagedInstancesInstanceGroupManagersRequest, ListManagedInstancesRegionInstanceGroupManagersRequest, + ListNamedSetsRoutersRequest, ListNetworkAttachmentsRequest, ListNetworkEndpointGroupsRequest, ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, @@ -1457,6 +1465,8 @@ ManagedInstanceLastAttempt, ManagedInstanceLastAttemptErrors, ManagedInstancePropertiesFromFlexibilityPolicy, + ManagedInstanceScheduling, + ManagedInstanceShutdownDetails, ManagedInstanceVersion, Metadata, MetadataFilter, @@ -1468,6 +1478,7 @@ MoveInstanceProjectRequest, MoveOrganizationSecurityPolicyRequest, NamedPort, + NamedSet, NatIpInfo, NatIpInfoNatIpInfoMapping, NatIpInfoResponse, @@ -1578,6 +1589,7 @@ PatchInterconnectAttachmentRequest, PatchInterconnectGroupRequest, PatchInterconnectRequest, + PatchNamedSetRouterRequest, PatchNetworkAttachmentRequest, PatchNetworkEdgeSecurityServiceRequest, PatchNetworkFirewallPolicyRequest, @@ -1626,12 +1638,14 @@ PatchWireGroupRequest, PathMatcher, PathRule, + PauseRolloutRequest, PerformMaintenanceInstanceRequest, PerformMaintenanceNodeGroupRequest, PerformMaintenanceReservationBlockRequest, PerformMaintenanceReservationRequest, PerformMaintenanceReservationSubBlockRequest, PerInstanceConfig, + PeriodicPartialMaintenanceSchedule, Policy, PreconfiguredWafSet, PreservedState, @@ -1792,11 +1806,13 @@ ResourceStatus, ResourceStatusEffectiveInstanceMetadata, ResourceStatusPhysicalHostTopology, + ResourceStatusPhysicalHostTopologyAdditionalAttributes, ResourceStatusReservationConsumptionInfo, ResourceStatusScheduling, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + ResumeRolloutRequest, Rollout, RolloutPlan, RolloutPlansListResponse, @@ -1837,8 +1853,10 @@ RouterNatSubnetworkToNat, RouterNatSubnetworkToNat64, RouterParams, + RoutersGetNamedSetResponse, RoutersGetRoutePolicyResponse, RoutersListBgpRoutes, + RoutersListNamedSets, RoutersListRoutePolicies, RoutersPreviewResponse, RoutersScopedList, @@ -2194,6 +2212,7 @@ TestIamPermissionsVpnGatewayRequest, TestPermissionsRequest, TestPermissionsResponse, + TimeZone, Uint128, UpcomingMaintenance, UpdateAccessConfigInstanceRequest, @@ -2212,6 +2231,7 @@ UpdateKmsKeyRegionSnapshotRequest, UpdateKmsKeySnapshotRequest, UpdateLicenseRequest, + UpdateNamedSetRouterRequest, UpdateNetworkInterfaceInstanceRequest, UpdatePeeringNetworkRequest, UpdatePerInstanceConfigsInstanceGroupManagerRequest, @@ -2302,6 +2322,7 @@ XpnResourceId, Zone, ZoneList, + ZoneResourceStatus, ZoneSetLabelsRequest, ZoneSetNestedPolicyRequest, ZoneSetPolicyRequest, @@ -2471,6 +2492,7 @@ "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", "AdvancedMachineFeatures", + "AdvanceRolloutRequest", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", @@ -2594,6 +2616,7 @@ "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -2671,6 +2694,7 @@ "CustomErrorResponsePolicyCustomErrorResponseRule", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2709,6 +2733,7 @@ "DeleteInterconnectRequest", "DeleteLicenseRequest", "DeleteMachineImageRequest", + "DeleteNamedSetRouterRequest", "DeleteNetworkAttachmentRequest", "DeleteNetworkEdgeSecurityServiceRequest", "DeleteNetworkEndpointGroupRequest", @@ -2848,6 +2873,7 @@ "FlexibleTimeRange", "ForwardingRule", "ForwardingRuleAggregatedList", + "ForwardingRuleAttachedExtension", "ForwardingRuleList", "ForwardingRuleReference", "ForwardingRuleServiceDirectoryRegistration", @@ -2966,6 +2992,7 @@ "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", "GetNetworkAttachmentRequest", @@ -3248,6 +3275,7 @@ "InstanceGroupManagerInstanceFlexibilityPolicy", "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerResizeRequest", "InstanceGroupManagerResizeRequestsListResponse", @@ -3471,6 +3499,7 @@ "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest", @@ -3582,6 +3611,8 @@ "ManagedInstanceLastAttempt", "ManagedInstanceLastAttemptErrors", "ManagedInstancePropertiesFromFlexibilityPolicy", + "ManagedInstanceScheduling", + "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", "Metadata", "MetadataFilter", @@ -3593,6 +3624,7 @@ "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "NamedPort", + "NamedSet", "NatIpInfo", "NatIpInfoNatIpInfoMapping", "NatIpInfoResponse", @@ -3703,6 +3735,7 @@ "PatchInterconnectAttachmentRequest", "PatchInterconnectGroupRequest", "PatchInterconnectRequest", + "PatchNamedSetRouterRequest", "PatchNetworkAttachmentRequest", "PatchNetworkEdgeSecurityServiceRequest", "PatchNetworkFirewallPolicyRequest", @@ -3751,12 +3784,14 @@ "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseRolloutRequest", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", "PerInstanceConfig", + "PeriodicPartialMaintenanceSchedule", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -3917,11 +3952,13 @@ "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeRolloutRequest", "Rollout", "RolloutPlan", "RolloutPlansListResponse", @@ -3962,8 +3999,10 @@ "RouterNatSubnetworkToNat", "RouterNatSubnetworkToNat64", "RouterParams", + "RoutersGetNamedSetResponse", "RoutersGetRoutePolicyResponse", "RoutersListBgpRoutes", + "RoutersListNamedSets", "RoutersListRoutePolicies", "RoutersPreviewResponse", "RoutersScopedList", @@ -4319,6 +4358,7 @@ "TestIamPermissionsVpnGatewayRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -4337,6 +4377,7 @@ "UpdateKmsKeyRegionSnapshotRequest", "UpdateKmsKeySnapshotRequest", "UpdateLicenseRequest", + "UpdateNamedSetRouterRequest", "UpdateNetworkInterfaceInstanceRequest", "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", @@ -4427,6 +4468,7 @@ "XpnResourceId", "Zone", "ZoneList", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py index 97c83318261d..e30cbc9dd464 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/__init__.py @@ -197,6 +197,7 @@ AddSignedUrlKeyBackendBucketRequest, AddSignedUrlKeyBackendServiceRequest, AdvancedMachineFeatures, + AdvanceRolloutRequest, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, AggregatedListAutoscalersRequest, @@ -320,6 +321,7 @@ BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy, BackendServiceLocalityLoadBalancingPolicyConfigPolicy, BackendServiceLogConfig, + BackendServiceLogConfigLoggingHttpHeader, BackendServiceNetworkPassThroughLbTrafficPolicy, BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity, BackendServiceOrchestrationInfo, @@ -397,6 +399,7 @@ CustomErrorResponsePolicyCustomErrorResponseRule, Data, Date, + DateTime, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -435,6 +438,7 @@ DeleteInterconnectRequest, DeleteLicenseRequest, DeleteMachineImageRequest, + DeleteNamedSetRouterRequest, DeleteNetworkAttachmentRequest, DeleteNetworkEdgeSecurityServiceRequest, DeleteNetworkEndpointGroupRequest, @@ -574,6 +578,7 @@ FlexibleTimeRange, ForwardingRule, ForwardingRuleAggregatedList, + ForwardingRuleAttachedExtension, ForwardingRuleList, ForwardingRuleReference, ForwardingRuleServiceDirectoryRegistration, @@ -692,6 +697,7 @@ GetMachineImageRequest, GetMachineTypeRequest, GetMacsecConfigInterconnectRequest, + GetNamedSetRouterRequest, GetNatIpInfoRouterRequest, GetNatMappingInfoRoutersRequest, GetNetworkAttachmentRequest, @@ -974,6 +980,7 @@ InstanceGroupManagerInstanceFlexibilityPolicy, InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection, InstanceGroupManagerInstanceLifecyclePolicy, + InstanceGroupManagerInstanceLifecyclePolicyOnRepair, InstanceGroupManagerList, InstanceGroupManagerResizeRequest, InstanceGroupManagerResizeRequestsListResponse, @@ -1197,6 +1204,7 @@ ListMachineTypesRequest, ListManagedInstancesInstanceGroupManagersRequest, ListManagedInstancesRegionInstanceGroupManagersRequest, + ListNamedSetsRoutersRequest, ListNetworkAttachmentsRequest, ListNetworkEndpointGroupsRequest, ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, @@ -1308,6 +1316,8 @@ ManagedInstanceLastAttempt, ManagedInstanceLastAttemptErrors, ManagedInstancePropertiesFromFlexibilityPolicy, + ManagedInstanceScheduling, + ManagedInstanceShutdownDetails, ManagedInstanceVersion, Metadata, MetadataFilter, @@ -1319,6 +1329,7 @@ MoveInstanceProjectRequest, MoveOrganizationSecurityPolicyRequest, NamedPort, + NamedSet, NatIpInfo, NatIpInfoNatIpInfoMapping, NatIpInfoResponse, @@ -1429,6 +1440,7 @@ PatchInterconnectAttachmentRequest, PatchInterconnectGroupRequest, PatchInterconnectRequest, + PatchNamedSetRouterRequest, PatchNetworkAttachmentRequest, PatchNetworkEdgeSecurityServiceRequest, PatchNetworkFirewallPolicyRequest, @@ -1477,12 +1489,14 @@ PatchWireGroupRequest, PathMatcher, PathRule, + PauseRolloutRequest, PerformMaintenanceInstanceRequest, PerformMaintenanceNodeGroupRequest, PerformMaintenanceReservationBlockRequest, PerformMaintenanceReservationRequest, PerformMaintenanceReservationSubBlockRequest, PerInstanceConfig, + PeriodicPartialMaintenanceSchedule, Policy, PreconfiguredWafSet, PreservedState, @@ -1643,11 +1657,13 @@ ResourceStatus, ResourceStatusEffectiveInstanceMetadata, ResourceStatusPhysicalHostTopology, + ResourceStatusPhysicalHostTopologyAdditionalAttributes, ResourceStatusReservationConsumptionInfo, ResourceStatusScheduling, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + ResumeRolloutRequest, Rollout, RolloutPlan, RolloutPlansListResponse, @@ -1688,8 +1704,10 @@ RouterNatSubnetworkToNat, RouterNatSubnetworkToNat64, RouterParams, + RoutersGetNamedSetResponse, RoutersGetRoutePolicyResponse, RoutersListBgpRoutes, + RoutersListNamedSets, RoutersListRoutePolicies, RoutersPreviewResponse, RoutersScopedList, @@ -2045,6 +2063,7 @@ TestIamPermissionsVpnGatewayRequest, TestPermissionsRequest, TestPermissionsResponse, + TimeZone, Uint128, UpcomingMaintenance, UpdateAccessConfigInstanceRequest, @@ -2063,6 +2082,7 @@ UpdateKmsKeyRegionSnapshotRequest, UpdateKmsKeySnapshotRequest, UpdateLicenseRequest, + UpdateNamedSetRouterRequest, UpdateNetworkInterfaceInstanceRequest, UpdatePeeringNetworkRequest, UpdatePerInstanceConfigsInstanceGroupManagerRequest, @@ -2153,6 +2173,7 @@ XpnResourceId, Zone, ZoneList, + ZoneResourceStatus, ZoneSetLabelsRequest, ZoneSetNestedPolicyRequest, ZoneSetPolicyRequest, @@ -2284,6 +2305,7 @@ def _get_version(dependency_name): "AddressList", "AddressesClient", "AddressesScopedList", + "AdvanceRolloutRequest", "AdvancedMachineFeatures", "AdviceClient", "AggregatedListAcceleratorTypesRequest", @@ -2410,6 +2432,7 @@ def _get_version(dependency_name): "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -2489,6 +2512,7 @@ def _get_version(dependency_name): "CustomerEncryptionKeyProtectedDisk", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2527,6 +2551,7 @@ def _get_version(dependency_name): "DeleteInterconnectRequest", "DeleteLicenseRequest", "DeleteMachineImageRequest", + "DeleteNamedSetRouterRequest", "DeleteNetworkAttachmentRequest", "DeleteNetworkEdgeSecurityServiceRequest", "DeleteNetworkEndpointGroupRequest", @@ -2671,6 +2696,7 @@ def _get_version(dependency_name): "FlexibleTimeRange", "ForwardingRule", "ForwardingRuleAggregatedList", + "ForwardingRuleAttachedExtension", "ForwardingRuleList", "ForwardingRuleReference", "ForwardingRuleServiceDirectoryRegistration", @@ -2793,6 +2819,7 @@ def _get_version(dependency_name): "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", "GetNetworkAttachmentRequest", @@ -3083,6 +3110,7 @@ def _get_version(dependency_name): "InstanceGroupManagerInstanceFlexibilityPolicy", "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerResizeRequest", "InstanceGroupManagerResizeRequestStatus", @@ -3322,6 +3350,7 @@ def _get_version(dependency_name): "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest", @@ -3435,6 +3464,8 @@ def _get_version(dependency_name): "ManagedInstanceLastAttempt", "ManagedInstanceLastAttemptErrors", "ManagedInstancePropertiesFromFlexibilityPolicy", + "ManagedInstanceScheduling", + "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", "Metadata", "MetadataFilter", @@ -3446,6 +3477,7 @@ def _get_version(dependency_name): "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "NamedPort", + "NamedSet", "NatIpInfo", "NatIpInfoNatIpInfoMapping", "NatIpInfoResponse", @@ -3567,6 +3599,7 @@ def _get_version(dependency_name): "PatchInterconnectAttachmentRequest", "PatchInterconnectGroupRequest", "PatchInterconnectRequest", + "PatchNamedSetRouterRequest", "PatchNetworkAttachmentRequest", "PatchNetworkEdgeSecurityServiceRequest", "PatchNetworkFirewallPolicyRequest", @@ -3615,12 +3648,14 @@ def _get_version(dependency_name): "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseRolloutRequest", "PerInstanceConfig", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", + "PeriodicPartialMaintenanceSchedule", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -3823,11 +3858,13 @@ def _get_version(dependency_name): "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeRolloutRequest", "Rollout", "RolloutPlan", "RolloutPlanWave", @@ -3876,8 +3913,10 @@ def _get_version(dependency_name): "RouterStatusNatStatusNatRuleStatus", "RouterStatusResponse", "RoutersClient", + "RoutersGetNamedSetResponse", "RoutersGetRoutePolicyResponse", "RoutersListBgpRoutes", + "RoutersListNamedSets", "RoutersListRoutePolicies", "RoutersPreviewResponse", "RoutersScopedList", @@ -4246,6 +4285,7 @@ def _get_version(dependency_name): "TestIamPermissionsVpnGatewayRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -4264,6 +4304,7 @@ def _get_version(dependency_name): "UpdateKmsKeyRegionSnapshotRequest", "UpdateKmsKeySnapshotRequest", "UpdateLicenseRequest", + "UpdateNamedSetRouterRequest", "UpdateNetworkInterfaceInstanceRequest", "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", @@ -4359,10 +4400,10 @@ def _get_version(dependency_name): "Zone", "ZoneList", "ZoneOperationsClient", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", "ZoneVmExtensionPoliciesClient", "ZonesClient", ) -# Trigger CI check diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json index d6534f4cabf1..36793a48e8bf 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json +++ b/packages/google-cloud-compute/google/cloud/compute_v1/gapic_metadata.json @@ -4764,6 +4764,11 @@ "rest": { "libraryClient": "RolloutsClient", "rpcs": { + "Advance": { + "methods": [ + "advance" + ] + }, "Cancel": { "methods": [ "cancel" @@ -4783,6 +4788,16 @@ "methods": [ "list" ] + }, + "Pause": { + "methods": [ + "pause" + ] + }, + "Resume": { + "methods": [ + "resume" + ] } } } @@ -4803,6 +4818,11 @@ "delete" ] }, + "DeleteNamedSet": { + "methods": [ + "delete_named_set" + ] + }, "DeleteRoutePolicy": { "methods": [ "delete_route_policy" @@ -4813,6 +4833,11 @@ "get" ] }, + "GetNamedSet": { + "methods": [ + "get_named_set" + ] + }, "GetNatIpInfo": { "methods": [ "get_nat_ip_info" @@ -4848,6 +4873,11 @@ "list_bgp_routes" ] }, + "ListNamedSets": { + "methods": [ + "list_named_sets" + ] + }, "ListRoutePolicies": { "methods": [ "list_route_policies" @@ -4858,6 +4888,11 @@ "patch" ] }, + "PatchNamedSet": { + "methods": [ + "patch_named_set" + ] + }, "PatchRoutePolicy": { "methods": [ "patch_route_policy" @@ -4873,6 +4908,11 @@ "update" ] }, + "UpdateNamedSet": { + "methods": [ + "update_named_set" + ] + }, "UpdateRoutePolicy": { "methods": [ "update_route_policy" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py index 8ad2520d3988..b174a696e879 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/backend_services/client.py @@ -2662,8 +2662,11 @@ def list_usable( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListUsablePager: - r"""Retrieves a list of all usable backend services in - the specified project. + r"""Retrieves a list of all usable backend services for + Application Load Balancers and Proxy Network Load + Balancers in the specified project. Backend services for + external and internal passthrough Network Load Balancers + are not included in the response. .. code-block:: python diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py index e2f5d0b49d89..e0c02bde20ae 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/region_backend_services/client.py @@ -1936,8 +1936,11 @@ def list_usable( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> pagers.ListUsablePager: - r"""Retrieves a list of all usable backend services in - the specified project in the given region. + r"""Retrieves a list of all usable backend services for + Application Load Balancers and Proxy Network Load + Balancers in the specified project in the given region. + Backend services for external and internal passthrough + Network Load Balancers are not included in the response. .. code-block:: python diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py index 9a658ef00897..096613aa69eb 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/client.py @@ -704,6 +704,282 @@ def __init__( }, ) + def advance_unary( + self, + request: Optional[Union[compute.AdvanceRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: 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.Operation: + r"""Advances a Rollout to the next wave, or completes it + if no waves remain. + + .. 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_v1 + + def sample_advance(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.AdvanceRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AdvanceRolloutRequest, dict]): + The request object. A request message for + Rollouts.Advance. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to advance. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.AdvanceRolloutRequest): + request = compute.AdvanceRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advance] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # 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 advance( + self, + request: Optional[Union[compute.AdvanceRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Advances a Rollout to the next wave, or completes it + if no waves remain. + + .. 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_v1 + + def sample_advance(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.AdvanceRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.AdvanceRolloutRequest, dict]): + The request object. A request message for + Rollouts.Advance. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to advance. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.AdvanceRolloutRequest): + request = compute.AdvanceRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.advance] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def cancel_unary( self, request: Optional[Union[compute.CancelRolloutRequest, dict]] = None, @@ -1490,6 +1766,552 @@ def sample_list(): # Done; return the response. return response + def pause_unary( + self, + request: Optional[Union[compute.PauseRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: 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.Operation: + r"""Pauses a Rollout. + + .. 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_v1 + + def sample_pause(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.PauseRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.PauseRolloutRequest, dict]): + The request object. A request message for Rollouts.Pause. + See the method description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to pause. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.PauseRolloutRequest): + request = compute.PauseRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # 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 pause( + self, + request: Optional[Union[compute.PauseRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Pauses a Rollout. + + .. 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_v1 + + def sample_pause(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.PauseRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.PauseRolloutRequest, dict]): + The request object. A request message for Rollouts.Pause. + See the method description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to pause. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.PauseRolloutRequest): + request = compute.PauseRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.pause] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def resume_unary( + self, + request: Optional[Union[compute.ResumeRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: 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.Operation: + r"""Resumes a Rollout. + + .. 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_v1 + + def sample_resume(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.ResumeRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ResumeRolloutRequest, dict]): + The request object. A request message for + Rollouts.Resume. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to resume. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.ResumeRolloutRequest): + request = compute.ResumeRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # 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 resume( + self, + request: Optional[Union[compute.ResumeRolloutRequest, dict]] = None, + *, + project: Optional[str] = None, + rollout: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Resumes a Rollout. + + .. 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_v1 + + def sample_resume(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.ResumeRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ResumeRolloutRequest, dict]): + The request object. A request message for + Rollouts.Resume. See the method + description for details. + project (str): + Required. Project ID for this + request. + + This corresponds to the ``project`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + rollout (str): + Required. Name of the Rollout + resource to resume. + + This corresponds to the ``rollout`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, rollout] + 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.ResumeRolloutRequest): + request = compute.ResumeRolloutRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if project is not None: + request.project = project + if rollout is not None: + request.rollout = rollout + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resume] + + # 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), + ("rollout", request.rollout), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._global_operations_client + operation_request = compute.GetGlobalOperationRequest() + operation_request.project = request.project + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + def __enter__(self) -> "RolloutsClient": return self diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py index d3f70163e219..8988f7071279 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/base.py @@ -147,6 +147,11 @@ def host(self): def _prep_wrapped_messages(self, client_info): # Precompute the wrapped methods. self._wrapped_methods = { + self.advance: gapic_v1.method.wrap_method( + self.advance, + default_timeout=600.0, + client_info=client_info, + ), self.cancel: gapic_v1.method.wrap_method( self.cancel, default_timeout=600.0, @@ -187,6 +192,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.pause: gapic_v1.method.wrap_method( + self.pause, + default_timeout=600.0, + client_info=client_info, + ), + self.resume: gapic_v1.method.wrap_method( + self.resume, + default_timeout=600.0, + client_info=client_info, + ), } def close(self): @@ -198,6 +213,15 @@ def close(self): """ raise NotImplementedError() + @property + def advance( + self, + ) -> Callable[ + [compute.AdvanceRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def cancel( self, @@ -233,6 +257,24 @@ def list( ]: raise NotImplementedError() + @property + def pause( + self, + ) -> Callable[ + [compute.PauseRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + + @property + def resume( + self, + ) -> Callable[ + [compute.ResumeRolloutRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py index d03f3eb6558b..94bd09a8bb9a 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest.py @@ -72,6 +72,14 @@ class RolloutsRestInterceptor: .. code-block:: python class MyCustomRolloutsInterceptor(RolloutsRestInterceptor): + def pre_advance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_advance(self, response): + logging.log(f"Received response: {response}") + return response + def pre_cancel(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -104,12 +112,72 @@ def post_list(self, response): logging.log(f"Received response: {response}") return response + def pre_pause(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_pause(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_resume(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_resume(self, response): + logging.log(f"Received response: {response}") + return response + transport = RolloutsRestTransport(interceptor=MyCustomRolloutsInterceptor()) client = RolloutsClient(transport=transport) """ + def pre_advance( + self, + request: compute.AdvanceRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.AdvanceRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for advance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_advance(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for advance + + DEPRECATED. Please use the `post_advance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_advance` interceptor runs + before the `post_advance_with_metadata` interceptor. + """ + return response + + def post_advance_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for advance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_advance_with_metadata` + interceptor in new development instead of the `post_advance` interceptor. + When both interceptors are used, this `post_advance_with_metadata` interceptor runs after the + `post_advance` interceptor. The (possibly modified) response returned by + `post_advance` will be passed to + `post_advance_with_metadata`. + """ + return response, metadata + def pre_cancel( self, request: compute.CancelRolloutRequest, @@ -288,6 +356,94 @@ def post_list_with_metadata( """ return response, metadata + def pre_pause( + self, + request: compute.PauseRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.PauseRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for pause + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_pause(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for pause + + DEPRECATED. Please use the `post_pause_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_pause` interceptor runs + before the `post_pause_with_metadata` interceptor. + """ + return response + + def post_pause_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for pause + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_pause_with_metadata` + interceptor in new development instead of the `post_pause` interceptor. + When both interceptors are used, this `post_pause_with_metadata` interceptor runs after the + `post_pause` interceptor. The (possibly modified) response returned by + `post_pause` will be passed to + `post_pause_with_metadata`. + """ + return response, metadata + + def pre_resume( + self, + request: compute.ResumeRolloutRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.ResumeRolloutRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for resume + + Override in a subclass to manipulate the request or metadata + before they are sent to the Rollouts server. + """ + return request, metadata + + def post_resume(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for resume + + DEPRECATED. Please use the `post_resume_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Rollouts server but before + it is returned to user code. This `post_resume` interceptor runs + before the `post_resume_with_metadata` interceptor. + """ + return response + + def post_resume_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for resume + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Rollouts server but before it is returned to user code. + + We recommend only using this `post_resume_with_metadata` + interceptor in new development instead of the `post_resume` interceptor. + When both interceptors are used, this `post_resume_with_metadata` interceptor runs after the + `post_resume` interceptor. The (possibly modified) response returned by + `post_resume` will be passed to + `post_resume_with_metadata`. + """ + return response, metadata + @dataclasses.dataclass class RolloutsRestStub: @@ -386,6 +542,180 @@ def __init__( self._interceptor = interceptor or RolloutsRestInterceptor() self._prep_wrapped_messages(client_info) + class _Advance(_BaseRolloutsRestTransport._BaseAdvance, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Advance") + + @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.AdvanceRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the advance method over HTTP. + + Args: + request (~.compute.AdvanceRolloutRequest): + The request object. A request message for + Rollouts.Advance. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BaseAdvance._get_http_options() + + request, metadata = self._interceptor.pre_advance(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseAdvance._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutsRestTransport._BaseAdvance._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_v1.RolloutsClient.Advance", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Advance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Advance._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_advance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_advance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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_v1.RolloutsClient.advance", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Advance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _Cancel(_BaseRolloutsRestTransport._BaseCancel, RolloutsRestStub): def __hash__(self): return hash("RolloutsRestTransport.Cancel") @@ -1023,6 +1353,357 @@ def __call__( ) return resp + class _Pause(_BaseRolloutsRestTransport._BasePause, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Pause") + + @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.PauseRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the pause method over HTTP. + + Args: + request (~.compute.PauseRolloutRequest): + The request object. A request message for Rollouts.Pause. + 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BasePause._get_http_options() + + request, metadata = self._interceptor.pre_pause(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BasePause._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseRolloutsRestTransport._BasePause._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_v1.RolloutsClient.Pause", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Pause", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Pause._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_pause(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_pause_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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_v1.RolloutsClient.pause", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Pause", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Resume(_BaseRolloutsRestTransport._BaseResume, RolloutsRestStub): + def __hash__(self): + return hash("RolloutsRestTransport.Resume") + + @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.ResumeRolloutRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the resume method over HTTP. + + Args: + request (~.compute.ResumeRolloutRequest): + The request object. A request message for + Rollouts.Resume. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRolloutsRestTransport._BaseResume._get_http_options() + + request, metadata = self._interceptor.pre_resume(request, metadata) + transcoded_request = ( + _BaseRolloutsRestTransport._BaseResume._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRolloutsRestTransport._BaseResume._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_v1.RolloutsClient.Resume", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Resume", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RolloutsRestTransport._Resume._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.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_resume(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_resume_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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_v1.RolloutsClient.resume", + extra={ + "serviceName": "google.cloud.compute.v1.Rollouts", + "rpcName": "Resume", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + @property + def advance(self) -> Callable[[compute.AdvanceRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Advance(self._session, self._host, self._interceptor) # type: ignore + @property def cancel(self) -> Callable[[compute.CancelRolloutRequest], compute.Operation]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -1049,6 +1730,18 @@ def list( # In C++ this would require a dynamic_cast return self._List(self._session, self._host, self._interceptor) # type: ignore + @property + def pause(self) -> Callable[[compute.PauseRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Pause(self._session, self._host, self._interceptor) # type: ignore + + @property + def resume(self) -> Callable[[compute.ResumeRolloutRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._Resume(self._session, self._host, self._interceptor) # type: ignore + @property def kind(self) -> str: return "rest" diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py index 7594c13936e1..861c9d9593f8 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/rollouts/transports/rest_base.py @@ -87,6 +87,52 @@ def __init__( api_audience=api_audience, ) + class _BaseAdvance: + 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": "post", + "uri": "/compute/v1/projects/{project}/global/rollouts/{rollout}/advance", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.AdvanceRolloutRequest.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( + _BaseRolloutsRestTransport._BaseAdvance._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseCancel: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -271,5 +317,97 @@ def _get_query_params_json(transcoded_request): return query_params + class _BasePause: + 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": "post", + "uri": "/compute/v1/projects/{project}/global/rollouts/{rollout}/pause", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PauseRolloutRequest.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( + _BaseRolloutsRestTransport._BasePause._get_unset_required_fields( + query_params + ) + ) + + return query_params + + class _BaseResume: + 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": "post", + "uri": "/compute/v1/projects/{project}/global/rollouts/{rollout}/resume", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ResumeRolloutRequest.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( + _BaseRolloutsRestTransport._BaseResume._get_unset_required_fields( + query_params + ) + ) + + return query_params + __all__ = ("_BaseRolloutsRestTransport",) diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py index 06fd0231ba58..17c2cc175368 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/client.py @@ -1118,9 +1118,9 @@ def error_code(self): # Done; return the response. return response - def delete_route_policy_unary( + def delete_named_set_unary( self, - request: Optional[Union[compute.DeleteRoutePolicyRouterRequest, dict]] = None, + request: Optional[Union[compute.DeleteNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1129,7 +1129,7 @@ def delete_route_policy_unary( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Deletes Route Policy + r"""Deletes Named Set .. code-block:: python @@ -1142,28 +1142,28 @@ def delete_route_policy_unary( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_delete_route_policy(): + def sample_delete_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.DeleteRoutePolicyRouterRequest( + request = compute_v1.DeleteNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.delete_route_policy(request=request) + response = client.delete_named_set(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.DeleteRoutePolicyRouterRequest, dict]): + request (Union[google.cloud.compute_v1.types.DeleteNamedSetRouterRequest, dict]): The request object. A request message for - Routers.DeleteRoutePolicy. See the - method description for details. + Routers.DeleteNamedSet. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -1176,7 +1176,7 @@ def sample_delete_route_policy(): should not be set. router (str): Name of the Router resource where - Route Policy is defined. + Named Set is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this @@ -1210,8 +1210,8 @@ def sample_delete_route_policy(): # - 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.DeleteRoutePolicyRouterRequest): - request = compute.DeleteRoutePolicyRouterRequest(request) + if not isinstance(request, compute.DeleteNamedSetRouterRequest): + request = compute.DeleteNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -1223,7 +1223,7 @@ def sample_delete_route_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_route_policy] + rpc = self._transport._wrapped_methods[self._transport.delete_named_set] # Certain fields should be provided within the metadata header; # add these here. @@ -1251,9 +1251,9 @@ def sample_delete_route_policy(): # Done; return the response. return response - def delete_route_policy( + def delete_named_set( self, - request: Optional[Union[compute.DeleteRoutePolicyRouterRequest, dict]] = None, + request: Optional[Union[compute.DeleteNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1262,7 +1262,7 @@ def delete_route_policy( timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> extended_operation.ExtendedOperation: - r"""Deletes Route Policy + r"""Deletes Named Set .. code-block:: python @@ -1275,28 +1275,28 @@ def delete_route_policy( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_delete_route_policy(): + def sample_delete_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.DeleteRoutePolicyRouterRequest( + request = compute_v1.DeleteNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.delete_route_policy(request=request) + response = client.delete_named_set(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.DeleteRoutePolicyRouterRequest, dict]): + request (Union[google.cloud.compute_v1.types.DeleteNamedSetRouterRequest, dict]): The request object. A request message for - Routers.DeleteRoutePolicy. See the - method description for details. + Routers.DeleteNamedSet. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -1309,7 +1309,7 @@ def sample_delete_route_policy(): should not be set. router (str): Name of the Router resource where - Route Policy is defined. + Named Set is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this @@ -1343,8 +1343,8 @@ def sample_delete_route_policy(): # - 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.DeleteRoutePolicyRouterRequest): - request = compute.DeleteRoutePolicyRouterRequest(request) + if not isinstance(request, compute.DeleteNamedSetRouterRequest): + request = compute.DeleteNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -1356,7 +1356,7 @@ def sample_delete_route_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_route_policy] + rpc = self._transport._wrapped_methods[self._transport.delete_named_set] # Certain fields should be provided within the metadata header; # add these here. @@ -1409,9 +1409,9 @@ def error_code(self): # Done; return the response. return response - def get( + def delete_route_policy_unary( self, - request: Optional[Union[compute.GetRouterRequest, dict]] = None, + request: Optional[Union[compute.DeleteRoutePolicyRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1419,8 +1419,8 @@ def get( retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.Router: - r"""Returns the specified Router resource. + ) -> compute.Operation: + r"""Deletes Route Policy .. code-block:: python @@ -1433,27 +1433,28 @@ def get( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_get(): + def sample_delete_route_policy(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.GetRouterRequest( + request = compute_v1.DeleteRoutePolicyRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.get(request=request) + response = client.delete_route_policy(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.GetRouterRequest, dict]): - The request object. A request message for Routers.Get. - See the method description for details. + request (Union[google.cloud.compute_v1.types.DeleteRoutePolicyRouterRequest, dict]): + The request object. A request message for + Routers.DeleteRoutePolicy. See the + method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -1465,8 +1466,8 @@ def sample_get(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to - return. + Name of the Router resource where + Route Policy is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this @@ -1480,11 +1481,9 @@ def sample_get(): be of type `bytes`. Returns: - google.cloud.compute_v1.types.Router: - Represents a Cloud Router resource. - - For more information about Cloud Router, - read theCloud Router overview. + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. """ # Create or coerce a protobuf request object. @@ -1502,8 +1501,8 @@ def sample_get(): # - 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.GetRouterRequest): - request = compute.GetRouterRequest(request) + if not isinstance(request, compute.DeleteRoutePolicyRouterRequest): + request = compute.DeleteRoutePolicyRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -1515,7 +1514,7 @@ def sample_get(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get] + rpc = self._transport._wrapped_methods[self._transport.delete_route_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -1543,9 +1542,9 @@ def sample_get(): # Done; return the response. return response - def get_nat_ip_info( + def delete_route_policy( self, - request: Optional[Union[compute.GetNatIpInfoRouterRequest, dict]] = None, + request: Optional[Union[compute.DeleteRoutePolicyRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1553,8 +1552,8 @@ def get_nat_ip_info( retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.NatIpInfoResponse: - r"""Retrieves runtime NAT IP information. + ) -> extended_operation.ExtendedOperation: + r"""Deletes Route Policy .. code-block:: python @@ -1567,28 +1566,28 @@ def get_nat_ip_info( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_get_nat_ip_info(): + def sample_delete_route_policy(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.GetNatIpInfoRouterRequest( + request = compute_v1.DeleteRoutePolicyRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.get_nat_ip_info(request=request) + response = client.delete_route_policy(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.GetNatIpInfoRouterRequest, dict]): + request (Union[google.cloud.compute_v1.types.DeleteRoutePolicyRouterRequest, dict]): The request object. A request message for - Routers.GetNatIpInfo. See the method - description for details. + Routers.DeleteRoutePolicy. See the + method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -1600,9 +1599,8 @@ def sample_get_nat_ip_info(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to query - for Nat IP information. The name should - conform to RFC1035. + Name of the Router resource where + Route Policy is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this @@ -1616,7 +1614,9 @@ def sample_get_nat_ip_info(): be of type `bytes`. Returns: - google.cloud.compute_v1.types.NatIpInfoResponse: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. """ # Create or coerce a protobuf request object. @@ -1634,8 +1634,8 @@ def sample_get_nat_ip_info(): # - 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.GetNatIpInfoRouterRequest): - request = compute.GetNatIpInfoRouterRequest(request) + if not isinstance(request, compute.DeleteRoutePolicyRouterRequest): + request = compute.DeleteRoutePolicyRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -1647,7 +1647,7 @@ def sample_get_nat_ip_info(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_nat_ip_info] + rpc = self._transport._wrapped_methods[self._transport.delete_route_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -1672,12 +1672,37 @@ def sample_get_nat_ip_info(): metadata=metadata, ) + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + # Done; return the response. return response - def get_nat_mapping_info( + def get( self, - request: Optional[Union[compute.GetNatMappingInfoRoutersRequest, dict]] = None, + request: Optional[Union[compute.GetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1685,9 +1710,8 @@ def get_nat_mapping_info( retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.GetNatMappingInfoPager: - r"""Retrieves runtime Nat mapping information of VM - endpoints. + ) -> compute.Router: + r"""Returns the specified Router resource. .. code-block:: python @@ -1700,29 +1724,27 @@ def get_nat_mapping_info( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_get_nat_mapping_info(): + def sample_get(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.GetNatMappingInfoRoutersRequest( + request = compute_v1.GetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - page_result = client.get_nat_mapping_info(request=request) + response = client.get(request=request) # Handle the response - for response in page_result: - print(response) + print(response) Args: - request (Union[google.cloud.compute_v1.types.GetNatMappingInfoRoutersRequest, dict]): - The request object. A request message for - Routers.GetNatMappingInfo. See the - method description for details. + request (Union[google.cloud.compute_v1.types.GetRouterRequest, dict]): + The request object. A request message for Routers.Get. + See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -1734,9 +1756,8 @@ def sample_get_nat_mapping_info(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to query - for Nat Mapping information of VM - endpoints. + Name of the Router resource to + return. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this @@ -1750,12 +1771,11 @@ def sample_get_nat_mapping_info(): be of type `bytes`. Returns: - google.cloud.compute_v1.services.routers.pagers.GetNatMappingInfoPager: - Contains a list of - VmEndpointNatMappings. - Iterating over this object will yield - results and resolve additional pages - automatically. + google.cloud.compute_v1.types.Router: + Represents a Cloud Router resource. + + For more information about Cloud Router, + read theCloud Router overview. """ # Create or coerce a protobuf request object. @@ -1773,8 +1793,8 @@ def sample_get_nat_mapping_info(): # - 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.GetNatMappingInfoRoutersRequest): - request = compute.GetNatMappingInfoRoutersRequest(request) + if not isinstance(request, compute.GetRouterRequest): + request = compute.GetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -1786,7 +1806,7 @@ def sample_get_nat_mapping_info(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_nat_mapping_info] + rpc = self._transport._wrapped_methods[self._transport.get] # Certain fields should be provided within the metadata header; # add these here. @@ -1811,23 +1831,12 @@ def sample_get_nat_mapping_info(): metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GetNatMappingInfoPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - def get_route_policy( + def get_named_set( self, - request: Optional[Union[compute.GetRoutePolicyRouterRequest, dict]] = None, + request: Optional[Union[compute.GetNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1835,8 +1844,8 @@ def get_route_policy( retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RoutersGetRoutePolicyResponse: - r"""Returns specified Route Policy + ) -> compute.RoutersGetNamedSetResponse: + r"""Returns specified Named Set .. code-block:: python @@ -1849,27 +1858,27 @@ def get_route_policy( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_get_route_policy(): + def sample_get_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.GetRoutePolicyRouterRequest( + request = compute_v1.GetNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.get_route_policy(request=request) + response = client.get_named_set(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.GetRoutePolicyRouterRequest, dict]): + request (Union[google.cloud.compute_v1.types.GetNamedSetRouterRequest, dict]): The request object. A request message for - Routers.GetRoutePolicy. See the method + Routers.GetNamedSet. See the method description for details. project (str): Project ID for this request. @@ -1883,7 +1892,7 @@ def sample_get_route_policy(): should not be set. router (str): Name of the Router resource to query - for the route policy. The name should + for the named set. The name should conform to RFC1035. This corresponds to the ``router`` field @@ -1898,7 +1907,7 @@ def sample_get_route_policy(): be of type `bytes`. Returns: - google.cloud.compute_v1.types.RoutersGetRoutePolicyResponse: + google.cloud.compute_v1.types.RoutersGetNamedSetResponse: """ # Create or coerce a protobuf request object. @@ -1916,8 +1925,8 @@ def sample_get_route_policy(): # - 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.GetRoutePolicyRouterRequest): - request = compute.GetRoutePolicyRouterRequest(request) + if not isinstance(request, compute.GetNamedSetRouterRequest): + request = compute.GetNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -1929,7 +1938,7 @@ def sample_get_route_policy(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_route_policy] + rpc = self._transport._wrapped_methods[self._transport.get_named_set] # Certain fields should be provided within the metadata header; # add these here. @@ -1957,9 +1966,9 @@ def sample_get_route_policy(): # Done; return the response. return response - def get_router_status( + def get_nat_ip_info( self, - request: Optional[Union[compute.GetRouterStatusRouterRequest, dict]] = None, + request: Optional[Union[compute.GetNatIpInfoRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -1967,9 +1976,8 @@ def get_router_status( retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RouterStatusResponse: - r"""Retrieves runtime information of the specified - router. + ) -> compute.NatIpInfoResponse: + r"""Retrieves runtime NAT IP information. .. code-block:: python @@ -1982,27 +1990,27 @@ def get_router_status( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_get_router_status(): + def sample_get_nat_ip_info(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.GetRouterStatusRouterRequest( + request = compute_v1.GetNatIpInfoRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.get_router_status(request=request) + response = client.get_nat_ip_info(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.GetRouterStatusRouterRequest, dict]): + request (Union[google.cloud.compute_v1.types.GetNatIpInfoRouterRequest, dict]): The request object. A request message for - Routers.GetRouterStatus. See the method + Routers.GetNatIpInfo. See the method description for details. project (str): Project ID for this request. @@ -2015,7 +2023,10 @@ def sample_get_router_status(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to query. + Name of the Router resource to query + for Nat IP information. The name should + conform to RFC1035. + This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -2028,7 +2039,7 @@ def sample_get_router_status(): be of type `bytes`. Returns: - google.cloud.compute_v1.types.RouterStatusResponse: + google.cloud.compute_v1.types.NatIpInfoResponse: """ # Create or coerce a protobuf request object. @@ -2046,8 +2057,8 @@ def sample_get_router_status(): # - 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.GetRouterStatusRouterRequest): - request = compute.GetRouterStatusRouterRequest(request) + if not isinstance(request, compute.GetNatIpInfoRouterRequest): + request = compute.GetNatIpInfoRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -2059,7 +2070,7 @@ def sample_get_router_status(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_router_status] + rpc = self._transport._wrapped_methods[self._transport.get_nat_ip_info] # Certain fields should be provided within the metadata header; # add these here. @@ -2087,19 +2098,19 @@ def sample_get_router_status(): # Done; return the response. return response - def insert_unary( + def get_nat_mapping_info( self, - request: Optional[Union[compute.InsertRouterRequest, dict]] = None, + request: Optional[Union[compute.GetNatMappingInfoRoutersRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, - router_resource: Optional[compute.Router] = None, + router: 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.Operation: - r"""Creates a Router resource in the specified project - and region using the data included in the request. + ) -> pagers.GetNatMappingInfoPager: + r"""Retrieves runtime Nat mapping information of VM + endpoints. .. code-block:: python @@ -2112,26 +2123,1154 @@ def insert_unary( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_insert(): + def sample_get_nat_mapping_info(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.InsertRouterRequest( + request = compute_v1.GetNatMappingInfoRoutersRequest( project="project_value", region="region_value", + router="router_value", ) # Make the request - response = client.insert(request=request) + page_result = client.get_nat_mapping_info(request=request) # Handle the response - print(response) + for response in page_result: + print(response) Args: - request (Union[google.cloud.compute_v1.types.InsertRouterRequest, dict]): - The request object. A request message for Routers.Insert. - See the method description for details. + request (Union[google.cloud.compute_v1.types.GetNatMappingInfoRoutersRequest, dict]): + The request object. A request message for + Routers.GetNatMappingInfo. 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router (str): + Name of the Router resource to query + for Nat Mapping information of VM + endpoints. + + This corresponds to the ``router`` 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_v1.services.routers.pagers.GetNatMappingInfoPager: + Contains a list of + VmEndpointNatMappings. + 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, router] + 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.GetNatMappingInfoRoutersRequest): + request = compute.GetNatMappingInfoRoutersRequest(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 router is not None: + request.router = router + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_nat_mapping_info] + + # 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), + ("router", request.router), + ) + ), + ) + + # 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.GetNatMappingInfoPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_route_policy( + self, + request: Optional[Union[compute.GetRoutePolicyRouterRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router: 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.RoutersGetRoutePolicyResponse: + r"""Returns specified Route Policy + + .. 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_v1 + + def sample_get_route_policy(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.GetRoutePolicyRouterRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + response = client.get_route_policy(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetRoutePolicyRouterRequest, dict]): + The request object. A request message for + Routers.GetRoutePolicy. 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router (str): + Name of the Router resource to query + for the route policy. The name should + conform to RFC1035. + + This corresponds to the ``router`` 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_v1.types.RoutersGetRoutePolicyResponse: + + """ + # 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, router] + 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.GetRoutePolicyRouterRequest): + request = compute.GetRoutePolicyRouterRequest(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 router is not None: + request.router = router + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_route_policy] + + # 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), + ("router", request.router), + ) + ), + ) + + # 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 get_router_status( + self, + request: Optional[Union[compute.GetRouterStatusRouterRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router: 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.RouterStatusResponse: + r"""Retrieves runtime information of the specified + router. + + .. 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_v1 + + def sample_get_router_status(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.GetRouterStatusRouterRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + response = client.get_router_status(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.GetRouterStatusRouterRequest, dict]): + The request object. A request message for + Routers.GetRouterStatus. 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router (str): + Name of the Router resource to query. + This corresponds to the ``router`` 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_v1.types.RouterStatusResponse: + + """ + # 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, router] + 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.GetRouterStatusRouterRequest): + request = compute.GetRouterStatusRouterRequest(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 router is not None: + request.router = router + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_router_status] + + # 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), + ("router", request.router), + ) + ), + ) + + # 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 insert_unary( + self, + request: Optional[Union[compute.InsertRouterRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router_resource: Optional[compute.Router] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Creates a Router resource in the specified project + and region using the data included in the request. + + .. 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_v1 + + def sample_insert(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.InsertRouterRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertRouterRequest, dict]): + The request object. A request message for Routers.Insert. + 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router_resource (google.cloud.compute_v1.types.Router): + The body resource for this request + This corresponds to the ``router_resource`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, router_resource] + 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.InsertRouterRequest): + request = compute.InsertRouterRequest(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 router_resource is not None: + request.router_resource = router_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # 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), + ) + ), + ) + + # 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 insert( + self, + request: Optional[Union[compute.InsertRouterRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router_resource: Optional[compute.Router] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> extended_operation.ExtendedOperation: + r"""Creates a Router resource in the specified project + and region using the data included in the request. + + .. 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_v1 + + def sample_insert(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.InsertRouterRequest( + project="project_value", + region="region_value", + ) + + # Make the request + response = client.insert(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.InsertRouterRequest, dict]): + The request object. A request message for Routers.Insert. + 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router_resource (google.cloud.compute_v1.types.Router): + The body resource for this request + This corresponds to the ``router_resource`` 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.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. + + """ + # 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, router_resource] + 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.InsertRouterRequest): + request = compute.InsertRouterRequest(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 router_resource is not None: + request.router_resource = router_resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.insert] + + # 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), + ) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + + # Done; return the response. + return response + + def list( + self, + request: Optional[Union[compute.ListRoutersRequest, dict]] = None, + *, + project: Optional[str] = None, + region: 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 Router resources available to the + specified project. + + .. 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_v1 + + def sample_list(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.ListRoutersRequest( + 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_v1.types.ListRoutersRequest, dict]): + The request object. A request message for Routers.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. + This corresponds to the ``region`` 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_v1.services.routers.pagers.ListPager: + Contains a list of Router resources. + + 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] + 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.ListRoutersRequest): + request = compute.ListRoutersRequest(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 + + # 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), + ) + ), + ) + + # 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 list_bgp_routes( + self, + request: Optional[Union[compute.ListBgpRoutesRoutersRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router: 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.ListBgpRoutesPager: + r"""Retrieves a list of router bgp routes available to + the specified project. + + .. 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_v1 + + def sample_list_bgp_routes(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.ListBgpRoutesRoutersRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + page_result = client.list_bgp_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListBgpRoutesRoutersRequest, dict]): + The request object. A request message for + Routers.ListBgpRoutes. 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router (str): + Name or id of the resource for this + request. Name should conform to RFC1035. + + This corresponds to the ``router`` 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_v1.services.routers.pagers.ListBgpRoutesPager: + 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, router] + 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.ListBgpRoutesRoutersRequest): + request = compute.ListBgpRoutesRoutersRequest(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 router is not None: + request.router = router + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_bgp_routes] + + # 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), + ("router", request.router), + ) + ), + ) + + # 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.ListBgpRoutesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_named_sets( + self, + request: Optional[Union[compute.ListNamedSetsRoutersRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router: 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.ListNamedSetsPager: + r"""Retrieves a list of router named set subresources + available to the specified project. + + .. 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_v1 + + def sample_list_named_sets(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.ListNamedSetsRoutersRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + page_result = client.list_named_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListNamedSetsRoutersRequest, dict]): + The request object. A request message for + Routers.ListNamedSets. 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. + This corresponds to the ``region`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router (str): + Name or id of the resource for this + request. Name should conform to RFC1035. + + This corresponds to the ``router`` 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_v1.services.routers.pagers.ListNamedSetsPager: + 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, router] + 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.ListNamedSetsRoutersRequest): + request = compute.ListNamedSetsRoutersRequest(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 router is not None: + request.router = router + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_named_sets] + + # 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), + ("router", request.router), + ) + ), + ) + + # 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.ListNamedSetsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_route_policies( + self, + request: Optional[Union[compute.ListRoutePoliciesRoutersRequest, dict]] = None, + *, + project: Optional[str] = None, + region: Optional[str] = None, + router: 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.ListRoutePoliciesPager: + r"""Retrieves a list of router route policy subresources + available to the specified project. + + .. 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_v1 + + def sample_list_route_policies(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.ListRoutePoliciesRoutersRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + page_result = client.list_route_policies(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.compute_v1.types.ListRoutePoliciesRoutersRequest, dict]): + The request object. A request message for + Routers.ListRoutePolicies. See the + method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -2142,9 +3281,11 @@ def sample_insert(): This corresponds to the ``region`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - router_resource (google.cloud.compute_v1.types.Router): - The body resource for this request - This corresponds to the ``router_resource`` field + router (str): + Name or id of the resource for this + request. Name should conform to RFC1035. + + This corresponds to the ``router`` 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, @@ -2156,15 +3297,16 @@ def sample_insert(): be of type `bytes`. Returns: - google.api_core.extended_operation.ExtendedOperation: - An object representing a extended - long-running operation. + google.cloud.compute_v1.services.routers.pagers.ListRoutePoliciesPager: + 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, router_resource] + flattened_params = [project, region, router] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -2176,20 +3318,20 @@ def sample_insert(): # - 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.InsertRouterRequest): - request = compute.InsertRouterRequest(request) + if not isinstance(request, compute.ListRoutePoliciesRoutersRequest): + request = compute.ListRoutePoliciesRoutersRequest(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 router_resource is not None: - request.router_resource = router_resource + if router is not None: + request.router = router # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert] + rpc = self._transport._wrapped_methods[self._transport.list_route_policies] # Certain fields should be provided within the metadata header; # add these here. @@ -2198,6 +3340,7 @@ def sample_insert(): ( ("project", request.project), ("region", request.region), + ("router", request.router), ) ), ) @@ -2213,22 +3356,36 @@ def sample_insert(): metadata=metadata, ) + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRoutePoliciesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + # Done; return the response. return response - def insert( + def patch_unary( self, - request: Optional[Union[compute.InsertRouterRequest, dict]] = None, + request: Optional[Union[compute.PatchRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, + router: Optional[str] = None, router_resource: Optional[compute.Router] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> extended_operation.ExtendedOperation: - r"""Creates a Router resource in the specified project - and region using the data included in the request. + ) -> compute.Operation: + r"""Patches the specified Router resource with the data + included in the request. This method supportsPATCH + semantics and usesJSON merge + patch format and processing rules. .. code-block:: python @@ -2241,25 +3398,26 @@ def insert( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_insert(): + def sample_patch(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.InsertRouterRequest( + request = compute_v1.PatchRouterRequest( project="project_value", region="region_value", + router="router_value", ) # Make the request - response = client.insert(request=request) + response = client.patch(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.InsertRouterRequest, dict]): - The request object. A request message for Routers.Insert. + request (Union[google.cloud.compute_v1.types.PatchRouterRequest, dict]): + The request object. A request message for Routers.Patch. See the method description for details. project (str): Project ID for this request. @@ -2271,6 +3429,11 @@ def sample_insert(): This corresponds to the ``region`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + router (str): + Name of the Router resource to patch. + This corresponds to the ``router`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. router_resource (google.cloud.compute_v1.types.Router): The body resource for this request This corresponds to the ``router_resource`` field @@ -2293,7 +3456,7 @@ def sample_insert(): # 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, router_resource] + flattened_params = [project, region, router, router_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -2305,20 +3468,22 @@ def sample_insert(): # - 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.InsertRouterRequest): - request = compute.InsertRouterRequest(request) + if not isinstance(request, compute.PatchRouterRequest): + request = compute.PatchRouterRequest(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 router is not None: + request.router = router if router_resource is not None: request.router_resource = router_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.insert] + rpc = self._transport._wrapped_methods[self._transport.patch] # Certain fields should be provided within the metadata header; # add these here. @@ -2327,6 +3492,7 @@ def sample_insert(): ( ("project", request.project), ("region", request.region), + ("router", request.router), ) ), ) @@ -2342,46 +3508,25 @@ def sample_insert(): metadata=metadata, ) - operation_service = self._transport._region_operations_client - operation_request = compute.GetRegionOperationRequest() - operation_request.project = request.project - operation_request.region = request.region - operation_request.operation = response.name - - get_operation = functools.partial(operation_service.get, operation_request) - # Cancel is not part of extended operations yet. - cancel_operation = lambda: None - - # Note: this class is an implementation detail to provide a uniform - # set of names for certain fields in the extended operation proto message. - # See google.api_core.extended_operation.ExtendedOperation for details - # on these properties and the expected interface. - class _CustomOperation(extended_operation.ExtendedOperation): - @property - def error_message(self): - return self._extended_operation.http_error_message - - @property - def error_code(self): - return self._extended_operation.http_error_status_code - - response = _CustomOperation.make(get_operation, cancel_operation, response) - # Done; return the response. return response - def list( + def patch( self, - request: Optional[Union[compute.ListRoutersRequest, dict]] = None, + request: Optional[Union[compute.PatchRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, + router: Optional[str] = None, + router_resource: Optional[compute.Router] = 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 Router resources available to the - specified project. + ) -> extended_operation.ExtendedOperation: + r"""Patches the specified Router resource with the data + included in the request. This method supportsPATCH + semantics and usesJSON merge + patch format and processing rules. .. code-block:: python @@ -2394,26 +3539,26 @@ def list( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_list(): + def sample_patch(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.ListRoutersRequest( + request = compute_v1.PatchRouterRequest( project="project_value", region="region_value", + router="router_value", ) # Make the request - page_result = client.list(request=request) + response = client.patch(request=request) # Handle the response - for response in page_result: - print(response) + print(response) Args: - request (Union[google.cloud.compute_v1.types.ListRoutersRequest, dict]): - The request object. A request message for Routers.List. + request (Union[google.cloud.compute_v1.types.PatchRouterRequest, dict]): + The request object. A request message for Routers.Patch. See the method description for details. project (str): Project ID for this request. @@ -2425,6 +3570,16 @@ def sample_list(): This corresponds to the ``region`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + router (str): + Name of the Router resource to patch. + This corresponds to the ``router`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + router_resource (google.cloud.compute_v1.types.Router): + The body resource for this request + This corresponds to the ``router_resource`` 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. @@ -2434,18 +3589,15 @@ def sample_list(): be of type `bytes`. Returns: - google.cloud.compute_v1.services.routers.pagers.ListPager: - Contains a list of Router resources. - - Iterating over this object will yield - results and resolve additional pages - automatically. + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. """ # 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] + flattened_params = [project, region, router, router_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -2457,18 +3609,22 @@ def sample_list(): # - 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.ListRoutersRequest): - request = compute.ListRoutersRequest(request) + if not isinstance(request, compute.PatchRouterRequest): + request = compute.PatchRouterRequest(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 router is not None: + request.router = router + if router_resource is not None: + request.router_resource = router_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list] + rpc = self._transport._wrapped_methods[self._transport.patch] # Certain fields should be provided within the metadata header; # add these here. @@ -2477,6 +3633,7 @@ def sample_list(): ( ("project", request.project), ("region", request.region), + ("router", request.router), ) ), ) @@ -2492,33 +3649,47 @@ def sample_list(): 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, - ) + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) # Done; return the response. return response - def list_bgp_routes( + def patch_named_set_unary( self, - request: Optional[Union[compute.ListBgpRoutesRoutersRequest, dict]] = None, + request: Optional[Union[compute.PatchNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, + named_set_resource: Optional[compute.NamedSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListBgpRoutesPager: - r"""Retrieves a list of router bgp routes available to - the specified project. + ) -> compute.Operation: + r"""Patches Named Set .. code-block:: python @@ -2531,28 +3702,27 @@ def list_bgp_routes( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_list_bgp_routes(): + def sample_patch_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.ListBgpRoutesRoutersRequest( + request = compute_v1.PatchNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - page_result = client.list_bgp_routes(request=request) + response = client.patch_named_set(request=request) # Handle the response - for response in page_result: - print(response) + print(response) Args: - request (Union[google.cloud.compute_v1.types.ListBgpRoutesRoutersRequest, dict]): + request (Union[google.cloud.compute_v1.types.PatchNamedSetRouterRequest, dict]): The request object. A request message for - Routers.ListBgpRoutes. See the method + Routers.PatchNamedSet. See the method description for details. project (str): Project ID for this request. @@ -2565,12 +3735,17 @@ def sample_list_bgp_routes(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name or id of the resource for this - request. Name should conform to RFC1035. + Name of the Router resource where + Named Set is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + named_set_resource (google.cloud.compute_v1.types.NamedSet): + The body resource for this request + This corresponds to the ``named_set_resource`` 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. @@ -2580,16 +3755,15 @@ def sample_list_bgp_routes(): be of type `bytes`. Returns: - google.cloud.compute_v1.services.routers.pagers.ListBgpRoutesPager: - Iterating over this object will yield - results and resolve additional pages - automatically. + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. """ # 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, router] + flattened_params = [project, region, router, named_set_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -2601,8 +3775,8 @@ def sample_list_bgp_routes(): # - 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.ListBgpRoutesRoutersRequest): - request = compute.ListBgpRoutesRoutersRequest(request) + if not isinstance(request, compute.PatchNamedSetRouterRequest): + request = compute.PatchNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -2611,10 +3785,12 @@ def sample_list_bgp_routes(): request.region = region if router is not None: request.router = router + if named_set_resource is not None: + request.named_set_resource = named_set_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_bgp_routes] + rpc = self._transport._wrapped_methods[self._transport.patch_named_set] # Certain fields should be provided within the metadata header; # add these here. @@ -2639,33 +3815,22 @@ def sample_list_bgp_routes(): metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListBgpRoutesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) - # Done; return the response. return response - def list_route_policies( + def patch_named_set( self, - request: Optional[Union[compute.ListRoutePoliciesRoutersRequest, dict]] = None, + request: Optional[Union[compute.PatchNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, + named_set_resource: Optional[compute.NamedSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> pagers.ListRoutePoliciesPager: - r"""Retrieves a list of router route policy subresources - available to the specified project. + ) -> extended_operation.ExtendedOperation: + r"""Patches Named Set .. code-block:: python @@ -2678,29 +3843,28 @@ def list_route_policies( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_list_route_policies(): + def sample_patch_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.ListRoutePoliciesRoutersRequest( + request = compute_v1.PatchNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - page_result = client.list_route_policies(request=request) + response = client.patch_named_set(request=request) # Handle the response - for response in page_result: - print(response) + print(response) Args: - request (Union[google.cloud.compute_v1.types.ListRoutePoliciesRoutersRequest, dict]): + request (Union[google.cloud.compute_v1.types.PatchNamedSetRouterRequest, dict]): The request object. A request message for - Routers.ListRoutePolicies. See the - method description for details. + Routers.PatchNamedSet. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -2712,12 +3876,17 @@ def sample_list_route_policies(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name or id of the resource for this - request. Name should conform to RFC1035. + Name of the Router resource where + Named Set is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + named_set_resource (google.cloud.compute_v1.types.NamedSet): + The body resource for this request + This corresponds to the ``named_set_resource`` 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. @@ -2727,16 +3896,15 @@ def sample_list_route_policies(): be of type `bytes`. Returns: - google.cloud.compute_v1.services.routers.pagers.ListRoutePoliciesPager: - Iterating over this object will yield - results and resolve additional pages - automatically. + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. """ # 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, router] + flattened_params = [project, region, router, named_set_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -2748,8 +3916,8 @@ def sample_list_route_policies(): # - 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.ListRoutePoliciesRoutersRequest): - request = compute.ListRoutePoliciesRoutersRequest(request) + if not isinstance(request, compute.PatchNamedSetRouterRequest): + request = compute.PatchNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -2758,10 +3926,12 @@ def sample_list_route_policies(): request.region = region if router is not None: request.router = router + if named_set_resource is not None: + request.named_set_resource = named_set_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_route_policies] + rpc = self._transport._wrapped_methods[self._transport.patch_named_set] # Certain fields should be provided within the metadata header; # add these here. @@ -2786,36 +3956,47 @@ def sample_list_route_policies(): metadata=metadata, ) - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListRoutePoliciesPager( - method=rpc, - request=request, - response=response, - retry=retry, - timeout=timeout, - metadata=metadata, - ) + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) # Done; return the response. return response - def patch_unary( + def patch_route_policy_unary( self, - request: Optional[Union[compute.PatchRouterRequest, dict]] = None, + request: Optional[Union[compute.PatchRoutePolicyRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, - router_resource: Optional[compute.Router] = None, + route_policy_resource: Optional[compute.RoutePolicy] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Patches the specified Router resource with the data - included in the request. This method supportsPATCH - semantics and usesJSON merge - patch format and processing rules. + r"""Patches Route Policy .. code-block:: python @@ -2828,27 +4009,28 @@ def patch_unary( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_patch(): + def sample_patch_route_policy(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.PatchRouterRequest( + request = compute_v1.PatchRoutePolicyRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.patch(request=request) + response = client.patch_route_policy(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.PatchRouterRequest, dict]): - The request object. A request message for Routers.Patch. - See the method description for details. + request (Union[google.cloud.compute_v1.types.PatchRoutePolicyRouterRequest, dict]): + The request object. A request message for + Routers.PatchRoutePolicy. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -2860,13 +4042,15 @@ def sample_patch(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to patch. + Name of the Router resource where + Route Policy is defined. + This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - router_resource (google.cloud.compute_v1.types.Router): + route_policy_resource (google.cloud.compute_v1.types.RoutePolicy): The body resource for this request - This corresponds to the ``router_resource`` field + This corresponds to the ``route_policy_resource`` 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, @@ -2886,7 +4070,7 @@ def sample_patch(): # 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, router, router_resource] + flattened_params = [project, region, router, route_policy_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -2898,8 +4082,8 @@ def sample_patch(): # - 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.PatchRouterRequest): - request = compute.PatchRouterRequest(request) + if not isinstance(request, compute.PatchRoutePolicyRouterRequest): + request = compute.PatchRoutePolicyRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -2908,12 +4092,12 @@ def sample_patch(): request.region = region if router is not None: request.router = router - if router_resource is not None: - request.router_resource = router_resource + if route_policy_resource is not None: + request.route_policy_resource = route_policy_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.patch] + rpc = self._transport._wrapped_methods[self._transport.patch_route_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -2941,22 +4125,19 @@ def sample_patch(): # Done; return the response. return response - def patch( + def patch_route_policy( self, - request: Optional[Union[compute.PatchRouterRequest, dict]] = None, + request: Optional[Union[compute.PatchRoutePolicyRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, - router_resource: Optional[compute.Router] = None, + route_policy_resource: Optional[compute.RoutePolicy] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> extended_operation.ExtendedOperation: - r"""Patches the specified Router resource with the data - included in the request. This method supportsPATCH - semantics and usesJSON merge - patch format and processing rules. + r"""Patches Route Policy .. code-block:: python @@ -2969,27 +4150,28 @@ def patch( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_patch(): + def sample_patch_route_policy(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.PatchRouterRequest( + request = compute_v1.PatchRoutePolicyRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.patch(request=request) + response = client.patch_route_policy(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.PatchRouterRequest, dict]): - The request object. A request message for Routers.Patch. - See the method description for details. + request (Union[google.cloud.compute_v1.types.PatchRoutePolicyRouterRequest, dict]): + The request object. A request message for + Routers.PatchRoutePolicy. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -3001,13 +4183,15 @@ def sample_patch(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to patch. + Name of the Router resource where + Route Policy is defined. + This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - router_resource (google.cloud.compute_v1.types.Router): + route_policy_resource (google.cloud.compute_v1.types.RoutePolicy): The body resource for this request - This corresponds to the ``router_resource`` field + This corresponds to the ``route_policy_resource`` 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, @@ -3027,7 +4211,7 @@ def sample_patch(): # 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, router, router_resource] + flattened_params = [project, region, router, route_policy_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -3039,8 +4223,8 @@ def sample_patch(): # - 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.PatchRouterRequest): - request = compute.PatchRouterRequest(request) + if not isinstance(request, compute.PatchRoutePolicyRouterRequest): + request = compute.PatchRoutePolicyRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -3049,12 +4233,12 @@ def sample_patch(): request.region = region if router is not None: request.router = router - if router_resource is not None: - request.router_resource = router_resource + if route_policy_resource is not None: + request.route_policy_resource = route_policy_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.patch] + rpc = self._transport._wrapped_methods[self._transport.patch_route_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -3107,19 +4291,21 @@ def error_code(self): # Done; return the response. return response - def patch_route_policy_unary( + def preview( self, - request: Optional[Union[compute.PatchRoutePolicyRouterRequest, dict]] = None, + request: Optional[Union[compute.PreviewRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, - route_policy_resource: Optional[compute.RoutePolicy] = None, + router_resource: Optional[compute.Router] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.Operation: - r"""Patches Route Policy + ) -> compute.RoutersPreviewResponse: + r"""Preview fields auto-generated during router create + andupdate operations. Calling this method does NOT + create or update the router. .. code-block:: python @@ -3132,27 +4318,27 @@ def patch_route_policy_unary( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_patch_route_policy(): + def sample_preview(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.PatchRoutePolicyRouterRequest( + request = compute_v1.PreviewRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.patch_route_policy(request=request) + response = client.preview(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.PatchRoutePolicyRouterRequest, dict]): + request (Union[google.cloud.compute_v1.types.PreviewRouterRequest, dict]): The request object. A request message for - Routers.PatchRoutePolicy. See the method + Routers.Preview. See the method description for details. project (str): Project ID for this request. @@ -3165,15 +4351,13 @@ def sample_patch_route_policy(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource where - Route Policy is defined. - + Name of the Router resource to query. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - route_policy_resource (google.cloud.compute_v1.types.RoutePolicy): + router_resource (google.cloud.compute_v1.types.Router): The body resource for this request - This corresponds to the ``route_policy_resource`` field + This corresponds to the ``router_resource`` 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, @@ -3185,15 +4369,13 @@ def sample_patch_route_policy(): be of type `bytes`. Returns: - google.api_core.extended_operation.ExtendedOperation: - An object representing a extended - long-running operation. + google.cloud.compute_v1.types.RoutersPreviewResponse: """ # 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, router, route_policy_resource] + flattened_params = [project, region, router, router_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -3205,8 +4387,8 @@ def sample_patch_route_policy(): # - 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.PatchRoutePolicyRouterRequest): - request = compute.PatchRoutePolicyRouterRequest(request) + if not isinstance(request, compute.PreviewRouterRequest): + request = compute.PreviewRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -3215,12 +4397,12 @@ def sample_patch_route_policy(): request.region = region if router is not None: request.router = router - if route_policy_resource is not None: - request.route_policy_resource = route_policy_resource + if router_resource is not None: + request.router_resource = router_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.patch_route_policy] + rpc = self._transport._wrapped_methods[self._transport.preview] # Certain fields should be provided within the metadata header; # add these here. @@ -3248,19 +4430,24 @@ def sample_patch_route_policy(): # Done; return the response. return response - def patch_route_policy( + def update_unary( self, - request: Optional[Union[compute.PatchRoutePolicyRouterRequest, dict]] = None, + request: Optional[Union[compute.UpdateRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, - route_policy_resource: Optional[compute.RoutePolicy] = None, + router_resource: Optional[compute.Router] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> extended_operation.ExtendedOperation: - r"""Patches Route Policy + ) -> compute.Operation: + r"""Updates the specified Router resource with the data + included in the request. This method conforms toPUT + semantics, which requests that the state of the target + resource be created or replaced with the state defined + by the representation enclosed in the request message + payload. .. code-block:: python @@ -3273,28 +4460,27 @@ def patch_route_policy( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_patch_route_policy(): + def sample_update(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.PatchRoutePolicyRouterRequest( + request = compute_v1.UpdateRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.patch_route_policy(request=request) + response = client.update(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.PatchRoutePolicyRouterRequest, dict]): - The request object. A request message for - Routers.PatchRoutePolicy. See the method - description for details. + request (Union[google.cloud.compute_v1.types.UpdateRouterRequest, dict]): + The request object. A request message for Routers.Update. + See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -3306,15 +4492,15 @@ def sample_patch_route_policy(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource where - Route Policy is defined. + Name of the Router resource to + update. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - route_policy_resource (google.cloud.compute_v1.types.RoutePolicy): + router_resource (google.cloud.compute_v1.types.Router): The body resource for this request - This corresponds to the ``route_policy_resource`` field + This corresponds to the ``router_resource`` 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, @@ -3334,7 +4520,7 @@ def sample_patch_route_policy(): # 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, router, route_policy_resource] + flattened_params = [project, region, router, router_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -3346,8 +4532,8 @@ def sample_patch_route_policy(): # - 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.PatchRoutePolicyRouterRequest): - request = compute.PatchRoutePolicyRouterRequest(request) + if not isinstance(request, compute.UpdateRouterRequest): + request = compute.UpdateRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -3356,12 +4542,12 @@ def sample_patch_route_policy(): request.region = region if router is not None: request.router = router - if route_policy_resource is not None: - request.route_policy_resource = route_policy_resource + if router_resource is not None: + request.router_resource = router_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.patch_route_policy] + rpc = self._transport._wrapped_methods[self._transport.update] # Certain fields should be provided within the metadata header; # add these here. @@ -3386,37 +4572,12 @@ def sample_patch_route_policy(): metadata=metadata, ) - operation_service = self._transport._region_operations_client - operation_request = compute.GetRegionOperationRequest() - operation_request.project = request.project - operation_request.region = request.region - operation_request.operation = response.name - - get_operation = functools.partial(operation_service.get, operation_request) - # Cancel is not part of extended operations yet. - cancel_operation = lambda: None - - # Note: this class is an implementation detail to provide a uniform - # set of names for certain fields in the extended operation proto message. - # See google.api_core.extended_operation.ExtendedOperation for details - # on these properties and the expected interface. - class _CustomOperation(extended_operation.ExtendedOperation): - @property - def error_message(self): - return self._extended_operation.http_error_message - - @property - def error_code(self): - return self._extended_operation.http_error_status_code - - response = _CustomOperation.make(get_operation, cancel_operation, response) - # Done; return the response. return response - def preview( + def update( self, - request: Optional[Union[compute.PreviewRouterRequest, dict]] = None, + request: Optional[Union[compute.UpdateRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, @@ -3425,10 +4586,13 @@ def preview( retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RoutersPreviewResponse: - r"""Preview fields auto-generated during router create - andupdate operations. Calling this method does NOT - create or update the router. + ) -> extended_operation.ExtendedOperation: + r"""Updates the specified Router resource with the data + included in the request. This method conforms toPUT + semantics, which requests that the state of the target + resource be created or replaced with the state defined + by the representation enclosed in the request message + payload. .. code-block:: python @@ -3441,28 +4605,27 @@ def preview( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_preview(): + def sample_update(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.PreviewRouterRequest( + request = compute_v1.UpdateRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.preview(request=request) + response = client.update(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.PreviewRouterRequest, dict]): - The request object. A request message for - Routers.Preview. See the method - description for details. + request (Union[google.cloud.compute_v1.types.UpdateRouterRequest, dict]): + The request object. A request message for Routers.Update. + See the method description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -3474,7 +4637,9 @@ def sample_preview(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to query. + Name of the Router resource to + update. + This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. @@ -3492,7 +4657,9 @@ def sample_preview(): be of type `bytes`. Returns: - google.cloud.compute_v1.types.RoutersPreviewResponse: + google.api_core.extended_operation.ExtendedOperation: + An object representing a extended + long-running operation. """ # Create or coerce a protobuf request object. @@ -3510,8 +4677,8 @@ def sample_preview(): # - 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.PreviewRouterRequest): - request = compute.PreviewRouterRequest(request) + if not isinstance(request, compute.UpdateRouterRequest): + request = compute.UpdateRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -3525,7 +4692,7 @@ def sample_preview(): # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.preview] + rpc = self._transport._wrapped_methods[self._transport.update] # Certain fields should be provided within the metadata header; # add these here. @@ -3550,27 +4717,47 @@ def sample_preview(): metadata=metadata, ) + operation_service = self._transport._region_operations_client + operation_request = compute.GetRegionOperationRequest() + operation_request.project = request.project + operation_request.region = request.region + operation_request.operation = response.name + + get_operation = functools.partial(operation_service.get, operation_request) + # Cancel is not part of extended operations yet. + cancel_operation = lambda: None + + # Note: this class is an implementation detail to provide a uniform + # set of names for certain fields in the extended operation proto message. + # See google.api_core.extended_operation.ExtendedOperation for details + # on these properties and the expected interface. + class _CustomOperation(extended_operation.ExtendedOperation): + @property + def error_message(self): + return self._extended_operation.http_error_message + + @property + def error_code(self): + return self._extended_operation.http_error_status_code + + response = _CustomOperation.make(get_operation, cancel_operation, response) + # Done; return the response. return response - def update_unary( + def update_named_set_unary( self, - request: Optional[Union[compute.UpdateRouterRequest, dict]] = None, + request: Optional[Union[compute.UpdateNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, - router_resource: Optional[compute.Router] = None, + named_set_resource: Optional[compute.NamedSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Updates the specified Router resource with the data - included in the request. This method conforms toPUT - semantics, which requests that the state of the target - resource be created or replaced with the state defined - by the representation enclosed in the request message - payload. + r"""Updates or creates new Named Set .. code-block:: python @@ -3583,27 +4770,28 @@ def update_unary( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_update(): + def sample_update_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.UpdateRouterRequest( + request = compute_v1.UpdateNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.update(request=request) + response = client.update_named_set(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.UpdateRouterRequest, dict]): - The request object. A request message for Routers.Update. - See the method description for details. + request (Union[google.cloud.compute_v1.types.UpdateNamedSetRouterRequest, dict]): + The request object. A request message for + Routers.UpdateNamedSet. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -3615,15 +4803,15 @@ def sample_update(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to - update. + Name of the Router resource where + Named Set is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - router_resource (google.cloud.compute_v1.types.Router): + named_set_resource (google.cloud.compute_v1.types.NamedSet): The body resource for this request - This corresponds to the ``router_resource`` field + This corresponds to the ``named_set_resource`` 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, @@ -3643,7 +4831,7 @@ def sample_update(): # 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, router, router_resource] + flattened_params = [project, region, router, named_set_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -3655,8 +4843,8 @@ def sample_update(): # - 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.UpdateRouterRequest): - request = compute.UpdateRouterRequest(request) + if not isinstance(request, compute.UpdateNamedSetRouterRequest): + request = compute.UpdateNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -3665,12 +4853,12 @@ def sample_update(): request.region = region if router is not None: request.router = router - if router_resource is not None: - request.router_resource = router_resource + if named_set_resource is not None: + request.named_set_resource = named_set_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update] + rpc = self._transport._wrapped_methods[self._transport.update_named_set] # Certain fields should be provided within the metadata header; # add these here. @@ -3698,24 +4886,19 @@ def sample_update(): # Done; return the response. return response - def update( + def update_named_set( self, - request: Optional[Union[compute.UpdateRouterRequest, dict]] = None, + request: Optional[Union[compute.UpdateNamedSetRouterRequest, dict]] = None, *, project: Optional[str] = None, region: Optional[str] = None, router: Optional[str] = None, - router_resource: Optional[compute.Router] = None, + named_set_resource: Optional[compute.NamedSet] = None, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Union[float, object] = gapic_v1.method.DEFAULT, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> extended_operation.ExtendedOperation: - r"""Updates the specified Router resource with the data - included in the request. This method conforms toPUT - semantics, which requests that the state of the target - resource be created or replaced with the state defined - by the representation enclosed in the request message - payload. + r"""Updates or creates new Named Set .. code-block:: python @@ -3728,27 +4911,28 @@ def update( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import compute_v1 - def sample_update(): + def sample_update_named_set(): # Create a client client = compute_v1.RoutersClient() # Initialize request argument(s) - request = compute_v1.UpdateRouterRequest( + request = compute_v1.UpdateNamedSetRouterRequest( project="project_value", region="region_value", router="router_value", ) # Make the request - response = client.update(request=request) + response = client.update_named_set(request=request) # Handle the response print(response) Args: - request (Union[google.cloud.compute_v1.types.UpdateRouterRequest, dict]): - The request object. A request message for Routers.Update. - See the method description for details. + request (Union[google.cloud.compute_v1.types.UpdateNamedSetRouterRequest, dict]): + The request object. A request message for + Routers.UpdateNamedSet. See the method + description for details. project (str): Project ID for this request. This corresponds to the ``project`` field @@ -3760,15 +4944,15 @@ def sample_update(): on the ``request`` instance; if ``request`` is provided, this should not be set. router (str): - Name of the Router resource to - update. + Name of the Router resource where + Named Set is defined. This corresponds to the ``router`` field on the ``request`` instance; if ``request`` is provided, this should not be set. - router_resource (google.cloud.compute_v1.types.Router): + named_set_resource (google.cloud.compute_v1.types.NamedSet): The body resource for this request - This corresponds to the ``router_resource`` field + This corresponds to the ``named_set_resource`` 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, @@ -3788,7 +4972,7 @@ def sample_update(): # 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, router, router_resource] + flattened_params = [project, region, router, named_set_resource] has_flattened_params = ( len([param for param in flattened_params if param is not None]) > 0 ) @@ -3800,8 +4984,8 @@ def sample_update(): # - 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.UpdateRouterRequest): - request = compute.UpdateRouterRequest(request) + if not isinstance(request, compute.UpdateNamedSetRouterRequest): + request = compute.UpdateNamedSetRouterRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if project is not None: @@ -3810,12 +4994,12 @@ def sample_update(): request.region = region if router is not None: request.router = router - if router_resource is not None: - request.router_resource = router_resource + if named_set_resource is not None: + request.named_set_resource = named_set_resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update] + rpc = self._transport._wrapped_methods[self._transport.update_named_set] # Certain fields should be provided within the metadata header; # add these here. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/pagers.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/pagers.py index ffe613a72b3d..af51a6fb9e38 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/pagers.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/pagers.py @@ -348,6 +348,82 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListNamedSetsPager: + """A pager for iterating through ``list_named_sets`` requests. + + This class thinly wraps an initial + :class:`google.cloud.compute_v1.types.RoutersListNamedSets` object, and + provides an ``__iter__`` method to iterate through its + ``result`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNamedSets`` requests and continue to iterate + through the ``result`` field on the + corresponding responses. + + All the usual :class:`google.cloud.compute_v1.types.RoutersListNamedSets` + 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.RoutersListNamedSets], + request: compute.ListNamedSetsRoutersRequest, + response: compute.RoutersListNamedSets, + *, + 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_v1.types.ListNamedSetsRoutersRequest): + The initial request object. + response (google.cloud.compute_v1.types.RoutersListNamedSets): + 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.ListNamedSetsRoutersRequest(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.RoutersListNamedSets]: + 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.NamedSet]: + for page in self.pages: + yield from page.result + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListRoutePoliciesPager: """A pager for iterating through ``list_route_policies`` requests. diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py index 1563cc779e94..852ef32160f4 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/base.py @@ -167,6 +167,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.delete_named_set: gapic_v1.method.wrap_method( + self.delete_named_set, + default_timeout=600.0, + client_info=client_info, + ), self.delete_route_policy: gapic_v1.method.wrap_method( self.delete_route_policy, default_timeout=600.0, @@ -187,6 +192,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.get_named_set: gapic_v1.method.wrap_method( + self.get_named_set, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), self.get_nat_ip_info: gapic_v1.method.wrap_method( self.get_nat_ip_info, default_retry=retries.Retry( @@ -282,6 +302,21 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.list_named_sets: gapic_v1.method.wrap_method( + self.list_named_sets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.DeadlineExceeded, + core_exceptions.ServiceUnavailable, + ), + deadline=600.0, + ), + default_timeout=600.0, + client_info=client_info, + ), self.list_route_policies: gapic_v1.method.wrap_method( self.list_route_policies, default_retry=retries.Retry( @@ -302,6 +337,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.patch_named_set: gapic_v1.method.wrap_method( + self.patch_named_set, + default_timeout=600.0, + client_info=client_info, + ), self.patch_route_policy: gapic_v1.method.wrap_method( self.patch_route_policy, default_timeout=600.0, @@ -317,6 +357,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=600.0, client_info=client_info, ), + self.update_named_set: gapic_v1.method.wrap_method( + self.update_named_set, + default_timeout=600.0, + client_info=client_info, + ), self.update_route_policy: gapic_v1.method.wrap_method( self.update_route_policy, default_timeout=600.0, @@ -351,6 +396,15 @@ def delete( ]: raise NotImplementedError() + @property + def delete_named_set( + self, + ) -> Callable[ + [compute.DeleteNamedSetRouterRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def delete_route_policy( self, @@ -368,6 +422,18 @@ def get( ]: raise NotImplementedError() + @property + def get_named_set( + self, + ) -> Callable[ + [compute.GetNamedSetRouterRequest], + Union[ + compute.RoutersGetNamedSetResponse, + Awaitable[compute.RoutersGetNamedSetResponse], + ], + ]: + raise NotImplementedError() + @property def get_nat_ip_info( self, @@ -437,6 +503,15 @@ def list_bgp_routes( ]: raise NotImplementedError() + @property + def list_named_sets( + self, + ) -> Callable[ + [compute.ListNamedSetsRoutersRequest], + Union[compute.RoutersListNamedSets, Awaitable[compute.RoutersListNamedSets]], + ]: + raise NotImplementedError() + @property def list_route_policies( self, @@ -458,6 +533,15 @@ def patch( ]: raise NotImplementedError() + @property + def patch_named_set( + self, + ) -> Callable[ + [compute.PatchNamedSetRouterRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def patch_route_policy( self, @@ -487,6 +571,15 @@ def update( ]: raise NotImplementedError() + @property + def update_named_set( + self, + ) -> Callable[ + [compute.UpdateNamedSetRouterRequest], + Union[compute.Operation, Awaitable[compute.Operation]], + ]: + raise NotImplementedError() + @property def update_route_policy( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py index 00ba7894abd0..efba6dbdc37f 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest.py @@ -88,6 +88,14 @@ def post_delete(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_named_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_named_set(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_route_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -104,6 +112,14 @@ def post_get(self, response): logging.log(f"Received response: {response}") return response + def pre_get_named_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_named_set(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_nat_ip_info(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -160,6 +176,14 @@ def post_list_bgp_routes(self, response): logging.log(f"Received response: {response}") return response + def pre_list_named_sets(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_named_sets(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_route_policies(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -176,6 +200,14 @@ def post_patch(self, response): logging.log(f"Received response: {response}") return response + def pre_patch_named_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_patch_named_set(self, response): + logging.log(f"Received response: {response}") + return response + def pre_patch_route_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -200,6 +232,14 @@ def post_update(self, response): logging.log(f"Received response: {response}") return response + def pre_update_named_set(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_update_named_set(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_route_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -306,6 +346,52 @@ def post_delete_with_metadata( """ return response, metadata + def pre_delete_named_set( + self, + request: compute.DeleteNamedSetRouterRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.DeleteNamedSetRouterRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_named_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routers server. + """ + return request, metadata + + def post_delete_named_set(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for delete_named_set + + DEPRECATED. Please use the `post_delete_named_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Routers server but before + it is returned to user code. This `post_delete_named_set` interceptor runs + before the `post_delete_named_set_with_metadata` interceptor. + """ + return response + + def post_delete_named_set_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_named_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Routers server but before it is returned to user code. + + We recommend only using this `post_delete_named_set_with_metadata` + interceptor in new development instead of the `post_delete_named_set` interceptor. + When both interceptors are used, this `post_delete_named_set_with_metadata` interceptor runs after the + `post_delete_named_set` interceptor. The (possibly modified) response returned by + `post_delete_named_set` will be passed to + `post_delete_named_set_with_metadata`. + """ + return response, metadata + def pre_delete_route_policy( self, request: compute.DeleteRoutePolicyRouterRequest, @@ -398,6 +484,56 @@ def post_get_with_metadata( """ return response, metadata + def pre_get_named_set( + self, + request: compute.GetNamedSetRouterRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.GetNamedSetRouterRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_named_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routers server. + """ + return request, metadata + + def post_get_named_set( + self, response: compute.RoutersGetNamedSetResponse + ) -> compute.RoutersGetNamedSetResponse: + """Post-rpc interceptor for get_named_set + + DEPRECATED. Please use the `post_get_named_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Routers server but before + it is returned to user code. This `post_get_named_set` interceptor runs + before the `post_get_named_set_with_metadata` interceptor. + """ + return response + + def post_get_named_set_with_metadata( + self, + response: compute.RoutersGetNamedSetResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.RoutersGetNamedSetResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_named_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Routers server but before it is returned to user code. + + We recommend only using this `post_get_named_set_with_metadata` + interceptor in new development instead of the `post_get_named_set` interceptor. + When both interceptors are used, this `post_get_named_set_with_metadata` interceptor runs after the + `post_get_named_set` interceptor. The (possibly modified) response returned by + `post_get_named_set` will be passed to + `post_get_named_set_with_metadata`. + """ + return response, metadata + def pre_get_nat_ip_info( self, request: compute.GetNatIpInfoRouterRequest, @@ -730,6 +866,54 @@ def post_list_bgp_routes_with_metadata( """ return response, metadata + def pre_list_named_sets( + self, + request: compute.ListNamedSetsRoutersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.ListNamedSetsRoutersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_named_sets + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routers server. + """ + return request, metadata + + def post_list_named_sets( + self, response: compute.RoutersListNamedSets + ) -> compute.RoutersListNamedSets: + """Post-rpc interceptor for list_named_sets + + DEPRECATED. Please use the `post_list_named_sets_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Routers server but before + it is returned to user code. This `post_list_named_sets` interceptor runs + before the `post_list_named_sets_with_metadata` interceptor. + """ + return response + + def post_list_named_sets_with_metadata( + self, + response: compute.RoutersListNamedSets, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.RoutersListNamedSets, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for list_named_sets + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Routers server but before it is returned to user code. + + We recommend only using this `post_list_named_sets_with_metadata` + interceptor in new development instead of the `post_list_named_sets` interceptor. + When both interceptors are used, this `post_list_named_sets_with_metadata` interceptor runs after the + `post_list_named_sets` interceptor. The (possibly modified) response returned by + `post_list_named_sets` will be passed to + `post_list_named_sets_with_metadata`. + """ + return response, metadata + def pre_list_route_policies( self, request: compute.ListRoutePoliciesRoutersRequest, @@ -824,6 +1008,52 @@ def post_patch_with_metadata( """ return response, metadata + def pre_patch_named_set( + self, + request: compute.PatchNamedSetRouterRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.PatchNamedSetRouterRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for patch_named_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routers server. + """ + return request, metadata + + def post_patch_named_set(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for patch_named_set + + DEPRECATED. Please use the `post_patch_named_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Routers server but before + it is returned to user code. This `post_patch_named_set` interceptor runs + before the `post_patch_named_set_with_metadata` interceptor. + """ + return response + + def post_patch_named_set_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for patch_named_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Routers server but before it is returned to user code. + + We recommend only using this `post_patch_named_set_with_metadata` + interceptor in new development instead of the `post_patch_named_set` interceptor. + When both interceptors are used, this `post_patch_named_set_with_metadata` interceptor runs after the + `post_patch_named_set` interceptor. The (possibly modified) response returned by + `post_patch_named_set` will be passed to + `post_patch_named_set_with_metadata`. + """ + return response, metadata + def pre_patch_route_policy( self, request: compute.PatchRoutePolicyRouterRequest, @@ -960,6 +1190,52 @@ def post_update_with_metadata( """ return response, metadata + def pre_update_named_set( + self, + request: compute.UpdateNamedSetRouterRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + compute.UpdateNamedSetRouterRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_named_set + + Override in a subclass to manipulate the request or metadata + before they are sent to the Routers server. + """ + return request, metadata + + def post_update_named_set(self, response: compute.Operation) -> compute.Operation: + """Post-rpc interceptor for update_named_set + + DEPRECATED. Please use the `post_update_named_set_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Routers server but before + it is returned to user code. This `post_update_named_set` interceptor runs + before the `post_update_named_set_with_metadata` interceptor. + """ + return response + + def post_update_named_set_with_metadata( + self, + response: compute.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[compute.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_named_set + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Routers server but before it is returned to user code. + + We recommend only using this `post_update_named_set_with_metadata` + interceptor in new development instead of the `post_update_named_set` interceptor. + When both interceptors are used, this `post_update_named_set_with_metadata` interceptor runs after the + `post_update_named_set` interceptor. The (possibly modified) response returned by + `post_update_named_set` will be passed to + `post_update_named_set_with_metadata`. + """ + return response, metadata + def pre_update_route_policy( self, request: compute.UpdateRoutePolicyRouterRequest, @@ -1427,11 +1703,11 @@ def __call__( ) return resp - class _DeleteRoutePolicy( - _BaseRoutersRestTransport._BaseDeleteRoutePolicy, RoutersRestStub + class _DeleteNamedSet( + _BaseRoutersRestTransport._BaseDeleteNamedSet, RoutersRestStub ): def __hash__(self): - return hash("RoutersRestTransport.DeleteRoutePolicy") + return hash("RoutersRestTransport.DeleteNamedSet") @staticmethod def _get_response( @@ -1457,19 +1733,19 @@ def _get_response( def __call__( self, - request: compute.DeleteRoutePolicyRouterRequest, + request: compute.DeleteNamedSetRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Call the delete route policy method over HTTP. + r"""Call the delete named set method over HTTP. Args: - request (~.compute.DeleteRoutePolicyRouterRequest): + request (~.compute.DeleteNamedSetRouterRequest): The request object. A request message for - Routers.DeleteRoutePolicy. See the - method description for details. + Routers.DeleteNamedSet. 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. @@ -1512,19 +1788,21 @@ def __call__( """ http_options = ( - _BaseRoutersRestTransport._BaseDeleteRoutePolicy._get_http_options() + _BaseRoutersRestTransport._BaseDeleteNamedSet._get_http_options() ) - request, metadata = self._interceptor.pre_delete_route_policy( + request, metadata = self._interceptor.pre_delete_named_set( request, metadata ) - transcoded_request = _BaseRoutersRestTransport._BaseDeleteRoutePolicy._get_transcoded_request( - http_options, request + transcoded_request = ( + _BaseRoutersRestTransport._BaseDeleteNamedSet._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params query_params = ( - _BaseRoutersRestTransport._BaseDeleteRoutePolicy._get_query_params_json( + _BaseRoutersRestTransport._BaseDeleteNamedSet._get_query_params_json( transcoded_request ) ) @@ -1547,17 +1825,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.DeleteRoutePolicy", + f"Sending request for google.cloud.compute_v1.RoutersClient.DeleteNamedSet", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "DeleteRoutePolicy", + "rpcName": "DeleteNamedSet", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._DeleteRoutePolicy._get_response( + response = RoutersRestTransport._DeleteNamedSet._get_response( self._host, metadata, query_params, @@ -1577,9 +1855,9 @@ def __call__( json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_delete_route_policy(resp) + resp = self._interceptor.post_delete_named_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_route_policy_with_metadata( + resp, _ = self._interceptor.post_delete_named_set_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1595,19 +1873,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.delete_route_policy", + "Received response for google.cloud.compute_v1.RoutersClient.delete_named_set", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "DeleteRoutePolicy", + "rpcName": "DeleteNamedSet", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _Get(_BaseRoutersRestTransport._BaseGet, RoutersRestStub): + class _DeleteRoutePolicy( + _BaseRoutersRestTransport._BaseDeleteRoutePolicy, RoutersRestStub + ): def __hash__(self): - return hash("RoutersRestTransport.Get") + return hash("RoutersRestTransport.DeleteRoutePolicy") @staticmethod def _get_response( @@ -1633,18 +1913,19 @@ def _get_response( def __call__( self, - request: compute.GetRouterRequest, + request: compute.DeleteRoutePolicyRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.Router: - r"""Call the get method over HTTP. + ) -> compute.Operation: + r"""Call the delete route policy method over HTTP. Args: - request (~.compute.GetRouterRequest): - The request object. A request message for Routers.Get. - See the method description for details. + request (~.compute.DeleteRoutePolicyRouterRequest): + The request object. A request message for + Routers.DeleteRoutePolicy. 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. @@ -1654,57 +1935,85 @@ def __call__( be of type `bytes`. Returns: - ~.compute.Router: - Represents a Cloud Router resource. + ~.compute.Operation: + Represents an Operation resource. - For more information about Cloud Router, - read theCloud Router overview. + Google Compute Engine has three Operation resources: - """ + - `Global `__ + - `Regional `__ + - `Zonal `__ - http_options = _BaseRoutersRestTransport._BaseGet._get_http_options() + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. - request, metadata = self._interceptor.pre_get(request, metadata) - transcoded_request = ( - _BaseRoutersRestTransport._BaseGet._get_transcoded_request( - http_options, request - ) - ) + Operations can be global, regional or zonal. - # Jsonify the query params - query_params = _BaseRoutersRestTransport._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, + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseRoutersRestTransport._BaseDeleteRoutePolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_route_policy( + request, metadata + ) + transcoded_request = _BaseRoutersRestTransport._BaseDeleteRoutePolicy._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = ( + _BaseRoutersRestTransport._BaseDeleteRoutePolicy._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_v1.RoutersClient.Get", + f"Sending request for google.cloud.compute_v1.RoutersClient.DeleteRoutePolicy", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "Get", + "rpcName": "DeleteRoutePolicy", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._Get._get_response( + response = RoutersRestTransport._DeleteRoutePolicy._get_response( self._host, metadata, query_params, @@ -1719,19 +2028,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.Router() - pb_resp = compute.Router.pb(resp) + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get(resp) + resp = self._interceptor.post_delete_route_policy(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_with_metadata(resp, response_metadata) + resp, _ = self._interceptor.post_delete_route_policy_with_metadata( + resp, response_metadata + ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.Router.to_json(response) + response_payload = compute.Operation.to_json(response) except: response_payload = None http_response = { @@ -1740,19 +2051,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.get", + "Received response for google.cloud.compute_v1.RoutersClient.delete_route_policy", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "Get", + "rpcName": "DeleteRoutePolicy", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetNatIpInfo(_BaseRoutersRestTransport._BaseGetNatIpInfo, RoutersRestStub): + class _Get(_BaseRoutersRestTransport._BaseGet, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.GetNatIpInfo") + return hash("RoutersRestTransport.Get") @staticmethod def _get_response( @@ -1778,19 +2089,18 @@ def _get_response( def __call__( self, - request: compute.GetNatIpInfoRouterRequest, + request: compute.GetRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.NatIpInfoResponse: - r"""Call the get nat ip info method over HTTP. + ) -> compute.Router: + r"""Call the get method over HTTP. Args: - request (~.compute.GetNatIpInfoRouterRequest): - The request object. A request message for - Routers.GetNatIpInfo. See the method - description for details. + request (~.compute.GetRouterRequest): + The request object. A request message for Routers.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. @@ -1800,26 +2110,26 @@ def __call__( be of type `bytes`. Returns: - ~.compute.NatIpInfoResponse: + ~.compute.Router: + Represents a Cloud Router resource. + + For more information about Cloud Router, + read theCloud Router overview. """ - http_options = ( - _BaseRoutersRestTransport._BaseGetNatIpInfo._get_http_options() - ) + http_options = _BaseRoutersRestTransport._BaseGet._get_http_options() - request, metadata = self._interceptor.pre_get_nat_ip_info(request, metadata) + request, metadata = self._interceptor.pre_get(request, metadata) transcoded_request = ( - _BaseRoutersRestTransport._BaseGetNatIpInfo._get_transcoded_request( + _BaseRoutersRestTransport._BaseGet._get_transcoded_request( http_options, request ) ) # Jsonify the query params - query_params = ( - _BaseRoutersRestTransport._BaseGetNatIpInfo._get_query_params_json( - transcoded_request - ) + query_params = _BaseRoutersRestTransport._BaseGet._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1840,17 +2150,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.GetNatIpInfo", + f"Sending request for google.cloud.compute_v1.RoutersClient.Get", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetNatIpInfo", + "rpcName": "Get", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._GetNatIpInfo._get_response( + response = RoutersRestTransport._Get._get_response( self._host, metadata, query_params, @@ -1865,21 +2175,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.NatIpInfoResponse() - pb_resp = compute.NatIpInfoResponse.pb(resp) + resp = compute.Router() + pb_resp = compute.Router.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_nat_ip_info(resp) + resp = self._interceptor.post_get(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_nat_ip_info_with_metadata( - resp, response_metadata - ) + 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.NatIpInfoResponse.to_json(response) + response_payload = compute.Router.to_json(response) except: response_payload = None http_response = { @@ -1888,21 +2196,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.get_nat_ip_info", + "Received response for google.cloud.compute_v1.RoutersClient.get", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetNatIpInfo", + "rpcName": "Get", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetNatMappingInfo( - _BaseRoutersRestTransport._BaseGetNatMappingInfo, RoutersRestStub - ): + class _GetNamedSet(_BaseRoutersRestTransport._BaseGetNamedSet, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.GetNatMappingInfo") + return hash("RoutersRestTransport.GetNamedSet") @staticmethod def _get_response( @@ -1928,19 +2234,19 @@ def _get_response( def __call__( self, - request: compute.GetNatMappingInfoRoutersRequest, + request: compute.GetNamedSetRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.VmEndpointNatMappingsList: - r"""Call the get nat mapping info method over HTTP. + ) -> compute.RoutersGetNamedSetResponse: + r"""Call the get named set method over HTTP. Args: - request (~.compute.GetNatMappingInfoRoutersRequest): + request (~.compute.GetNamedSetRouterRequest): The request object. A request message for - Routers.GetNatMappingInfo. See the - method description for details. + Routers.GetNamedSet. 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. @@ -1950,26 +2256,24 @@ def __call__( be of type `bytes`. Returns: - ~.compute.VmEndpointNatMappingsList: - Contains a list of - VmEndpointNatMappings. + ~.compute.RoutersGetNamedSetResponse: """ http_options = ( - _BaseRoutersRestTransport._BaseGetNatMappingInfo._get_http_options() + _BaseRoutersRestTransport._BaseGetNamedSet._get_http_options() ) - request, metadata = self._interceptor.pre_get_nat_mapping_info( - request, metadata - ) - transcoded_request = _BaseRoutersRestTransport._BaseGetNatMappingInfo._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_get_named_set(request, metadata) + transcoded_request = ( + _BaseRoutersRestTransport._BaseGetNamedSet._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params query_params = ( - _BaseRoutersRestTransport._BaseGetNatMappingInfo._get_query_params_json( + _BaseRoutersRestTransport._BaseGetNamedSet._get_query_params_json( transcoded_request ) ) @@ -1992,17 +2296,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.GetNatMappingInfo", + f"Sending request for google.cloud.compute_v1.RoutersClient.GetNamedSet", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetNatMappingInfo", + "rpcName": "GetNamedSet", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._GetNatMappingInfo._get_response( + response = RoutersRestTransport._GetNamedSet._get_response( self._host, metadata, query_params, @@ -2017,21 +2321,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.VmEndpointNatMappingsList() - pb_resp = compute.VmEndpointNatMappingsList.pb(resp) + resp = compute.RoutersGetNamedSetResponse() + pb_resp = compute.RoutersGetNamedSetResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_nat_mapping_info(resp) + resp = self._interceptor.post_get_named_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_nat_mapping_info_with_metadata( + resp, _ = self._interceptor.post_get_named_set_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.VmEndpointNatMappingsList.to_json( + response_payload = compute.RoutersGetNamedSetResponse.to_json( response ) except: @@ -2042,21 +2346,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.get_nat_mapping_info", + "Received response for google.cloud.compute_v1.RoutersClient.get_named_set", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetNatMappingInfo", + "rpcName": "GetNamedSet", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetRoutePolicy( - _BaseRoutersRestTransport._BaseGetRoutePolicy, RoutersRestStub - ): + class _GetNatIpInfo(_BaseRoutersRestTransport._BaseGetNatIpInfo, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.GetRoutePolicy") + return hash("RoutersRestTransport.GetNatIpInfo") @staticmethod def _get_response( @@ -2082,18 +2384,18 @@ def _get_response( def __call__( self, - request: compute.GetRoutePolicyRouterRequest, + request: compute.GetNatIpInfoRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RoutersGetRoutePolicyResponse: - r"""Call the get route policy method over HTTP. + ) -> compute.NatIpInfoResponse: + r"""Call the get nat ip info method over HTTP. Args: - request (~.compute.GetRoutePolicyRouterRequest): + request (~.compute.GetNatIpInfoRouterRequest): The request object. A request message for - Routers.GetRoutePolicy. See the method + Routers.GetNatIpInfo. See the method description for details. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. @@ -2104,26 +2406,24 @@ def __call__( be of type `bytes`. Returns: - ~.compute.RoutersGetRoutePolicyResponse: + ~.compute.NatIpInfoResponse: """ http_options = ( - _BaseRoutersRestTransport._BaseGetRoutePolicy._get_http_options() + _BaseRoutersRestTransport._BaseGetNatIpInfo._get_http_options() ) - request, metadata = self._interceptor.pre_get_route_policy( - request, metadata - ) + request, metadata = self._interceptor.pre_get_nat_ip_info(request, metadata) transcoded_request = ( - _BaseRoutersRestTransport._BaseGetRoutePolicy._get_transcoded_request( + _BaseRoutersRestTransport._BaseGetNatIpInfo._get_transcoded_request( http_options, request ) ) # Jsonify the query params query_params = ( - _BaseRoutersRestTransport._BaseGetRoutePolicy._get_query_params_json( + _BaseRoutersRestTransport._BaseGetNatIpInfo._get_query_params_json( transcoded_request ) ) @@ -2146,17 +2446,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.GetRoutePolicy", + f"Sending request for google.cloud.compute_v1.RoutersClient.GetNatIpInfo", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetRoutePolicy", + "rpcName": "GetNatIpInfo", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._GetRoutePolicy._get_response( + response = RoutersRestTransport._GetNatIpInfo._get_response( self._host, metadata, query_params, @@ -2171,23 +2471,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.RoutersGetRoutePolicyResponse() - pb_resp = compute.RoutersGetRoutePolicyResponse.pb(resp) + resp = compute.NatIpInfoResponse() + pb_resp = compute.NatIpInfoResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_route_policy(resp) + resp = self._interceptor.post_get_nat_ip_info(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_route_policy_with_metadata( + resp, _ = self._interceptor.post_get_nat_ip_info_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.RoutersGetRoutePolicyResponse.to_json( - response - ) + response_payload = compute.NatIpInfoResponse.to_json(response) except: response_payload = None http_response = { @@ -2196,21 +2494,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.get_route_policy", + "Received response for google.cloud.compute_v1.RoutersClient.get_nat_ip_info", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetRoutePolicy", + "rpcName": "GetNatIpInfo", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetRouterStatus( - _BaseRoutersRestTransport._BaseGetRouterStatus, RoutersRestStub + class _GetNatMappingInfo( + _BaseRoutersRestTransport._BaseGetNatMappingInfo, RoutersRestStub ): def __hash__(self): - return hash("RoutersRestTransport.GetRouterStatus") + return hash("RoutersRestTransport.GetNatMappingInfo") @staticmethod def _get_response( @@ -2236,19 +2534,19 @@ def _get_response( def __call__( self, - request: compute.GetRouterStatusRouterRequest, + request: compute.GetNatMappingInfoRoutersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RouterStatusResponse: - r"""Call the get router status method over HTTP. + ) -> compute.VmEndpointNatMappingsList: + r"""Call the get nat mapping info method over HTTP. Args: - request (~.compute.GetRouterStatusRouterRequest): + request (~.compute.GetNatMappingInfoRoutersRequest): The request object. A request message for - Routers.GetRouterStatus. See the method - description for details. + Routers.GetNatMappingInfo. 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. @@ -2258,26 +2556,26 @@ def __call__( be of type `bytes`. Returns: - ~.compute.RouterStatusResponse: + ~.compute.VmEndpointNatMappingsList: + Contains a list of + VmEndpointNatMappings. """ http_options = ( - _BaseRoutersRestTransport._BaseGetRouterStatus._get_http_options() + _BaseRoutersRestTransport._BaseGetNatMappingInfo._get_http_options() ) - request, metadata = self._interceptor.pre_get_router_status( + request, metadata = self._interceptor.pre_get_nat_mapping_info( request, metadata ) - transcoded_request = ( - _BaseRoutersRestTransport._BaseGetRouterStatus._get_transcoded_request( - http_options, request - ) + transcoded_request = _BaseRoutersRestTransport._BaseGetNatMappingInfo._get_transcoded_request( + http_options, request ) # Jsonify the query params query_params = ( - _BaseRoutersRestTransport._BaseGetRouterStatus._get_query_params_json( + _BaseRoutersRestTransport._BaseGetNatMappingInfo._get_query_params_json( transcoded_request ) ) @@ -2300,17 +2598,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.GetRouterStatus", + f"Sending request for google.cloud.compute_v1.RoutersClient.GetNatMappingInfo", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetRouterStatus", + "rpcName": "GetNatMappingInfo", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._GetRouterStatus._get_response( + response = RoutersRestTransport._GetNatMappingInfo._get_response( self._host, metadata, query_params, @@ -2325,21 +2623,647 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.RouterStatusResponse() - pb_resp = compute.RouterStatusResponse.pb(resp) + resp = compute.VmEndpointNatMappingsList() + pb_resp = compute.VmEndpointNatMappingsList.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_router_status(resp) + resp = self._interceptor.post_get_nat_mapping_info(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_nat_mapping_info_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.VmEndpointNatMappingsList.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_v1.RoutersClient.get_nat_mapping_info", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "GetNatMappingInfo", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRoutePolicy( + _BaseRoutersRestTransport._BaseGetRoutePolicy, RoutersRestStub + ): + def __hash__(self): + return hash("RoutersRestTransport.GetRoutePolicy") + + @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.GetRoutePolicyRouterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RoutersGetRoutePolicyResponse: + r"""Call the get route policy method over HTTP. + + Args: + request (~.compute.GetRoutePolicyRouterRequest): + The request object. A request message for + Routers.GetRoutePolicy. 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.RoutersGetRoutePolicyResponse: + + """ + + http_options = ( + _BaseRoutersRestTransport._BaseGetRoutePolicy._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_route_policy( + request, metadata + ) + transcoded_request = ( + _BaseRoutersRestTransport._BaseGetRoutePolicy._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRoutersRestTransport._BaseGetRoutePolicy._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_v1.RoutersClient.GetRoutePolicy", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "GetRoutePolicy", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutersRestTransport._GetRoutePolicy._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.RoutersGetRoutePolicyResponse() + pb_resp = compute.RoutersGetRoutePolicyResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_route_policy(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_route_policy_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.RoutersGetRoutePolicyResponse.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_v1.RoutersClient.get_route_policy", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "GetRoutePolicy", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetRouterStatus( + _BaseRoutersRestTransport._BaseGetRouterStatus, RoutersRestStub + ): + def __hash__(self): + return hash("RoutersRestTransport.GetRouterStatus") + + @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.GetRouterStatusRouterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RouterStatusResponse: + r"""Call the get router status method over HTTP. + + Args: + request (~.compute.GetRouterStatusRouterRequest): + The request object. A request message for + Routers.GetRouterStatus. 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.RouterStatusResponse: + + """ + + http_options = ( + _BaseRoutersRestTransport._BaseGetRouterStatus._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_router_status( + request, metadata + ) + transcoded_request = ( + _BaseRoutersRestTransport._BaseGetRouterStatus._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseRoutersRestTransport._BaseGetRouterStatus._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_v1.RoutersClient.GetRouterStatus", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "GetRouterStatus", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutersRestTransport._GetRouterStatus._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.RouterStatusResponse() + pb_resp = compute.RouterStatusResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_router_status(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_router_status_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.RouterStatusResponse.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_v1.RoutersClient.get_router_status", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "GetRouterStatus", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _Insert(_BaseRoutersRestTransport._BaseInsert, RoutersRestStub): + def __hash__(self): + return hash("RoutersRestTransport.Insert") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: compute.InsertRouterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the insert method over HTTP. + + Args: + request (~.compute.InsertRouterRequest): + The request object. A request message for Routers.Insert. + 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = _BaseRoutersRestTransport._BaseInsert._get_http_options() + + request, metadata = self._interceptor.pre_insert(request, metadata) + transcoded_request = ( + _BaseRoutersRestTransport._BaseInsert._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseRoutersRestTransport._BaseInsert._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseRoutersRestTransport._BaseInsert._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_v1.RoutersClient.Insert", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "Insert", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutersRestTransport._Insert._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_insert(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_insert_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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_v1.RoutersClient.insert", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "Insert", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _List(_BaseRoutersRestTransport._BaseList, RoutersRestStub): + def __hash__(self): + return hash("RoutersRestTransport.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.ListRoutersRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.RouterList: + r"""Call the list method over HTTP. + + Args: + request (~.compute.ListRoutersRequest): + The request object. A request message for Routers.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.RouterList: + Contains a list of Router resources. + """ + + http_options = _BaseRoutersRestTransport._BaseList._get_http_options() + + request, metadata = self._interceptor.pre_list(request, metadata) + transcoded_request = ( + _BaseRoutersRestTransport._BaseList._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = _BaseRoutersRestTransport._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_v1.RoutersClient.List", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "List", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutersRestTransport._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.RouterList() + pb_resp = compute.RouterList.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_get_router_status_with_metadata( - resp, response_metadata - ) + 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.RouterStatusResponse.to_json(response) + response_payload = compute.RouterList.to_json(response) except: response_payload = None http_response = { @@ -2348,19 +3272,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.get_router_status", + "Received response for google.cloud.compute_v1.RoutersClient.list", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "GetRouterStatus", + "rpcName": "List", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _Insert(_BaseRoutersRestTransport._BaseInsert, RoutersRestStub): + class _ListBgpRoutes(_BaseRoutersRestTransport._BaseListBgpRoutes, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.Insert") + return hash("RoutersRestTransport.ListBgpRoutes") @staticmethod def _get_response( @@ -2381,24 +3305,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: compute.InsertRouterRequest, + request: compute.ListBgpRoutesRoutersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.Operation: - r"""Call the insert method over HTTP. + ) -> compute.RoutersListBgpRoutes: + r"""Call the list bgp routes method over HTTP. Args: - request (~.compute.InsertRouterRequest): - The request object. A request message for Routers.Insert. - See the method description for details. + request (~.compute.ListBgpRoutesRoutersRequest): + The request object. A request message for + Routers.ListBgpRoutes. 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. @@ -2408,54 +3332,26 @@ def __call__( be of type `bytes`. Returns: - ~.compute.Operation: - Represents an Operation resource. - - Google Compute Engine has three Operation resources: - - - `Global `__ - - `Regional `__ - - `Zonal `__ - - You can use an operation resource to manage asynchronous - API requests. For more information, readHandling API - responses. - - Operations can be global, regional or zonal. - - :: - - - For global operations, use the `globalOperations` - resource. - - For regional operations, use the - `regionOperations` resource. - - For zonal operations, use - the `zoneOperations` resource. - - For more information, read Global, Regional, and Zonal - Resources. - - Note that completed Operation resources have a limited - retention period. + ~.compute.RoutersListBgpRoutes: """ - http_options = _BaseRoutersRestTransport._BaseInsert._get_http_options() + http_options = ( + _BaseRoutersRestTransport._BaseListBgpRoutes._get_http_options() + ) - request, metadata = self._interceptor.pre_insert(request, metadata) + request, metadata = self._interceptor.pre_list_bgp_routes(request, metadata) transcoded_request = ( - _BaseRoutersRestTransport._BaseInsert._get_transcoded_request( + _BaseRoutersRestTransport._BaseListBgpRoutes._get_transcoded_request( http_options, request ) ) - body = _BaseRoutersRestTransport._BaseInsert._get_request_body_json( - transcoded_request - ) - # Jsonify the query params - query_params = _BaseRoutersRestTransport._BaseInsert._get_query_params_json( - transcoded_request + query_params = ( + _BaseRoutersRestTransport._BaseListBgpRoutes._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2476,24 +3372,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.Insert", + f"Sending request for google.cloud.compute_v1.RoutersClient.ListBgpRoutes", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "Insert", + "rpcName": "ListBgpRoutes", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._Insert._get_response( + response = RoutersRestTransport._ListBgpRoutes._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2502,21 +3397,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.Operation() - pb_resp = compute.Operation.pb(resp) + resp = compute.RoutersListBgpRoutes() + pb_resp = compute.RoutersListBgpRoutes.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_insert(resp) + resp = self._interceptor.post_list_bgp_routes(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_insert_with_metadata( + resp, _ = self._interceptor.post_list_bgp_routes_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.Operation.to_json(response) + response_payload = compute.RoutersListBgpRoutes.to_json(response) except: response_payload = None http_response = { @@ -2525,19 +3420,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.insert", + "Received response for google.cloud.compute_v1.RoutersClient.list_bgp_routes", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "Insert", + "rpcName": "ListBgpRoutes", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _List(_BaseRoutersRestTransport._BaseList, RoutersRestStub): + class _ListNamedSets(_BaseRoutersRestTransport._BaseListNamedSets, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.List") + return hash("RoutersRestTransport.ListNamedSets") @staticmethod def _get_response( @@ -2563,18 +3458,19 @@ def _get_response( def __call__( self, - request: compute.ListRoutersRequest, + request: compute.ListNamedSetsRoutersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RouterList: - r"""Call the list method over HTTP. + ) -> compute.RoutersListNamedSets: + r"""Call the list named sets method over HTTP. Args: - request (~.compute.ListRoutersRequest): - The request object. A request message for Routers.List. - See the method description for details. + request (~.compute.ListNamedSetsRoutersRequest): + The request object. A request message for + Routers.ListNamedSets. 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. @@ -2584,22 +3480,26 @@ def __call__( be of type `bytes`. Returns: - ~.compute.RouterList: - Contains a list of Router resources. + ~.compute.RoutersListNamedSets: + """ - http_options = _BaseRoutersRestTransport._BaseList._get_http_options() + http_options = ( + _BaseRoutersRestTransport._BaseListNamedSets._get_http_options() + ) - request, metadata = self._interceptor.pre_list(request, metadata) + request, metadata = self._interceptor.pre_list_named_sets(request, metadata) transcoded_request = ( - _BaseRoutersRestTransport._BaseList._get_transcoded_request( + _BaseRoutersRestTransport._BaseListNamedSets._get_transcoded_request( http_options, request ) ) # Jsonify the query params - query_params = _BaseRoutersRestTransport._BaseList._get_query_params_json( - transcoded_request + query_params = ( + _BaseRoutersRestTransport._BaseListNamedSets._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2620,17 +3520,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.List", + f"Sending request for google.cloud.compute_v1.RoutersClient.ListNamedSets", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "List", + "rpcName": "ListNamedSets", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._List._get_response( + response = RoutersRestTransport._ListNamedSets._get_response( self._host, metadata, query_params, @@ -2645,19 +3545,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.RouterList() - pb_resp = compute.RouterList.pb(resp) + resp = compute.RoutersListNamedSets() + pb_resp = compute.RoutersListNamedSets.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list(resp) + resp = self._interceptor.post_list_named_sets(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_with_metadata(resp, response_metadata) + resp, _ = self._interceptor.post_list_named_sets_with_metadata( + resp, response_metadata + ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.RouterList.to_json(response) + response_payload = compute.RoutersListNamedSets.to_json(response) except: response_payload = None http_response = { @@ -2666,19 +3568,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.list", + "Received response for google.cloud.compute_v1.RoutersClient.list_named_sets", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "List", + "rpcName": "ListNamedSets", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListBgpRoutes(_BaseRoutersRestTransport._BaseListBgpRoutes, RoutersRestStub): + class _ListRoutePolicies( + _BaseRoutersRestTransport._BaseListRoutePolicies, RoutersRestStub + ): def __hash__(self): - return hash("RoutersRestTransport.ListBgpRoutes") + return hash("RoutersRestTransport.ListRoutePolicies") @staticmethod def _get_response( @@ -2704,19 +3608,19 @@ def _get_response( def __call__( self, - request: compute.ListBgpRoutesRoutersRequest, + request: compute.ListRoutePoliciesRoutersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RoutersListBgpRoutes: - r"""Call the list bgp routes method over HTTP. + ) -> compute.RoutersListRoutePolicies: + r"""Call the list route policies method over HTTP. Args: - request (~.compute.ListBgpRoutesRoutersRequest): + request (~.compute.ListRoutePoliciesRoutersRequest): The request object. A request message for - Routers.ListBgpRoutes. See the method - description for details. + Routers.ListRoutePolicies. 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. @@ -2726,24 +3630,24 @@ def __call__( be of type `bytes`. Returns: - ~.compute.RoutersListBgpRoutes: + ~.compute.RoutersListRoutePolicies: """ http_options = ( - _BaseRoutersRestTransport._BaseListBgpRoutes._get_http_options() + _BaseRoutersRestTransport._BaseListRoutePolicies._get_http_options() ) - request, metadata = self._interceptor.pre_list_bgp_routes(request, metadata) - transcoded_request = ( - _BaseRoutersRestTransport._BaseListBgpRoutes._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_route_policies( + request, metadata + ) + transcoded_request = _BaseRoutersRestTransport._BaseListRoutePolicies._get_transcoded_request( + http_options, request ) # Jsonify the query params query_params = ( - _BaseRoutersRestTransport._BaseListBgpRoutes._get_query_params_json( + _BaseRoutersRestTransport._BaseListRoutePolicies._get_query_params_json( transcoded_request ) ) @@ -2766,17 +3670,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.ListBgpRoutes", + f"Sending request for google.cloud.compute_v1.RoutersClient.ListRoutePolicies", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "ListBgpRoutes", + "rpcName": "ListRoutePolicies", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._ListBgpRoutes._get_response( + response = RoutersRestTransport._ListRoutePolicies._get_response( self._host, metadata, query_params, @@ -2791,21 +3695,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.RoutersListBgpRoutes() - pb_resp = compute.RoutersListBgpRoutes.pb(resp) + resp = compute.RoutersListRoutePolicies() + pb_resp = compute.RoutersListRoutePolicies.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_bgp_routes(resp) + resp = self._interceptor.post_list_route_policies(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_bgp_routes_with_metadata( + resp, _ = self._interceptor.post_list_route_policies_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.RoutersListBgpRoutes.to_json(response) + response_payload = compute.RoutersListRoutePolicies.to_json( + response + ) except: response_payload = None http_response = { @@ -2814,21 +3720,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.list_bgp_routes", + "Received response for google.cloud.compute_v1.RoutersClient.list_route_policies", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "ListBgpRoutes", + "rpcName": "ListRoutePolicies", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListRoutePolicies( - _BaseRoutersRestTransport._BaseListRoutePolicies, RoutersRestStub - ): + class _Patch(_BaseRoutersRestTransport._BasePatch, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.ListRoutePolicies") + return hash("RoutersRestTransport.Patch") @staticmethod def _get_response( @@ -2849,24 +3753,24 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: compute.ListRoutePoliciesRoutersRequest, + request: compute.PatchRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> compute.RoutersListRoutePolicies: - r"""Call the list route policies method over HTTP. + ) -> compute.Operation: + r"""Call the patch method over HTTP. Args: - request (~.compute.ListRoutePoliciesRoutersRequest): - The request object. A request message for - Routers.ListRoutePolicies. See the - method description for details. + request (~.compute.PatchRouterRequest): + The request object. A request message for Routers.Patch. + 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. @@ -2876,26 +3780,54 @@ def __call__( be of type `bytes`. Returns: - ~.compute.RoutersListRoutePolicies: + ~.compute.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. """ - http_options = ( - _BaseRoutersRestTransport._BaseListRoutePolicies._get_http_options() - ) + http_options = _BaseRoutersRestTransport._BasePatch._get_http_options() - request, metadata = self._interceptor.pre_list_route_policies( - request, metadata + request, metadata = self._interceptor.pre_patch(request, metadata) + transcoded_request = ( + _BaseRoutersRestTransport._BasePatch._get_transcoded_request( + http_options, request + ) ) - transcoded_request = _BaseRoutersRestTransport._BaseListRoutePolicies._get_transcoded_request( - http_options, request + + body = _BaseRoutersRestTransport._BasePatch._get_request_body_json( + transcoded_request ) # Jsonify the query params - query_params = ( - _BaseRoutersRestTransport._BaseListRoutePolicies._get_query_params_json( - transcoded_request - ) + query_params = _BaseRoutersRestTransport._BasePatch._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -2916,23 +3848,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.ListRoutePolicies", + f"Sending request for google.cloud.compute_v1.RoutersClient.Patch", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "ListRoutePolicies", + "rpcName": "Patch", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._ListRoutePolicies._get_response( + response = RoutersRestTransport._Patch._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -2941,23 +3874,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = compute.RoutersListRoutePolicies() - pb_resp = compute.RoutersListRoutePolicies.pb(resp) + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_route_policies(resp) + resp = self._interceptor.post_patch(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_route_policies_with_metadata( + resp, _ = self._interceptor.post_patch_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = compute.RoutersListRoutePolicies.to_json( - response - ) + response_payload = compute.Operation.to_json(response) except: response_payload = None http_response = { @@ -2966,19 +3897,19 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.list_route_policies", + "Received response for google.cloud.compute_v1.RoutersClient.patch", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "ListRoutePolicies", + "rpcName": "Patch", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _Patch(_BaseRoutersRestTransport._BasePatch, RoutersRestStub): + class _PatchNamedSet(_BaseRoutersRestTransport._BasePatchNamedSet, RoutersRestStub): def __hash__(self): - return hash("RoutersRestTransport.Patch") + return hash("RoutersRestTransport.PatchNamedSet") @staticmethod def _get_response( @@ -3005,18 +3936,19 @@ def _get_response( def __call__( self, - request: compute.PatchRouterRequest, + request: compute.PatchNamedSetRouterRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), ) -> compute.Operation: - r"""Call the patch method over HTTP. + r"""Call the patch named set method over HTTP. Args: - request (~.compute.PatchRouterRequest): - The request object. A request message for Routers.Patch. - See the method description for details. + request (~.compute.PatchNamedSetRouterRequest): + The request object. A request message for + Routers.PatchNamedSet. 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. @@ -3058,22 +3990,26 @@ def __call__( """ - http_options = _BaseRoutersRestTransport._BasePatch._get_http_options() + http_options = ( + _BaseRoutersRestTransport._BasePatchNamedSet._get_http_options() + ) - request, metadata = self._interceptor.pre_patch(request, metadata) + request, metadata = self._interceptor.pre_patch_named_set(request, metadata) transcoded_request = ( - _BaseRoutersRestTransport._BasePatch._get_transcoded_request( + _BaseRoutersRestTransport._BasePatchNamedSet._get_transcoded_request( http_options, request ) ) - body = _BaseRoutersRestTransport._BasePatch._get_request_body_json( + body = _BaseRoutersRestTransport._BasePatchNamedSet._get_request_body_json( transcoded_request ) # Jsonify the query params - query_params = _BaseRoutersRestTransport._BasePatch._get_query_params_json( - transcoded_request + query_params = ( + _BaseRoutersRestTransport._BasePatchNamedSet._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -3094,17 +4030,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.compute_v1.RoutersClient.Patch", + f"Sending request for google.cloud.compute_v1.RoutersClient.PatchNamedSet", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "Patch", + "rpcName": "PatchNamedSet", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = RoutersRestTransport._Patch._get_response( + response = RoutersRestTransport._PatchNamedSet._get_response( self._host, metadata, query_params, @@ -3125,9 +4061,9 @@ def __call__( json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_patch(resp) + resp = self._interceptor.post_patch_named_set(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_patch_with_metadata( + resp, _ = self._interceptor.post_patch_named_set_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -3143,10 +4079,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.compute_v1.RoutersClient.patch", + "Received response for google.cloud.compute_v1.RoutersClient.patch_named_set", extra={ "serviceName": "google.cloud.compute.v1.Routers", - "rpcName": "Patch", + "rpcName": "PatchNamedSet", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -3670,6 +4606,192 @@ def __call__( ) return resp + class _UpdateNamedSet( + _BaseRoutersRestTransport._BaseUpdateNamedSet, RoutersRestStub + ): + def __hash__(self): + return hash("RoutersRestTransport.UpdateNamedSet") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: compute.UpdateNamedSetRouterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> compute.Operation: + r"""Call the update named set method over HTTP. + + Args: + request (~.compute.UpdateNamedSetRouterRequest): + The request object. A request message for + Routers.UpdateNamedSet. 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.Operation: + Represents an Operation resource. + + Google Compute Engine has three Operation resources: + + - `Global `__ + - `Regional `__ + - `Zonal `__ + + You can use an operation resource to manage asynchronous + API requests. For more information, readHandling API + responses. + + Operations can be global, regional or zonal. + + :: + + - For global operations, use the `globalOperations` + resource. + - For regional operations, use the + `regionOperations` resource. + - For zonal operations, use + the `zoneOperations` resource. + + For more information, read Global, Regional, and Zonal + Resources. + + Note that completed Operation resources have a limited + retention period. + + """ + + http_options = ( + _BaseRoutersRestTransport._BaseUpdateNamedSet._get_http_options() + ) + + request, metadata = self._interceptor.pre_update_named_set( + request, metadata + ) + transcoded_request = ( + _BaseRoutersRestTransport._BaseUpdateNamedSet._get_transcoded_request( + http_options, request + ) + ) + + body = _BaseRoutersRestTransport._BaseUpdateNamedSet._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = ( + _BaseRoutersRestTransport._BaseUpdateNamedSet._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_v1.RoutersClient.UpdateNamedSet", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "UpdateNamedSet", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = RoutersRestTransport._UpdateNamedSet._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = compute.Operation() + pb_resp = compute.Operation.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_update_named_set(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_update_named_set_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = compute.Operation.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_v1.RoutersClient.update_named_set", + extra={ + "serviceName": "google.cloud.compute.v1.Routers", + "rpcName": "UpdateNamedSet", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _UpdateRoutePolicy( _BaseRoutersRestTransport._BaseUpdateRoutePolicy, RoutersRestStub ): @@ -3870,6 +4992,14 @@ def delete(self) -> Callable[[compute.DeleteRouterRequest], compute.Operation]: # In C++ this would require a dynamic_cast return self._Delete(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_named_set( + self, + ) -> Callable[[compute.DeleteNamedSetRouterRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteNamedSet(self._session, self._host, self._interceptor) # type: ignore + @property def delete_route_policy( self, @@ -3884,6 +5014,16 @@ def get(self) -> Callable[[compute.GetRouterRequest], compute.Router]: # In C++ this would require a dynamic_cast return self._Get(self._session, self._host, self._interceptor) # type: ignore + @property + def get_named_set( + self, + ) -> Callable[ + [compute.GetNamedSetRouterRequest], compute.RoutersGetNamedSetResponse + ]: + # 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._GetNamedSet(self._session, self._host, self._interceptor) # type: ignore + @property def get_nat_ip_info( self, @@ -3940,6 +5080,14 @@ def list_bgp_routes( # In C++ this would require a dynamic_cast return self._ListBgpRoutes(self._session, self._host, self._interceptor) # type: ignore + @property + def list_named_sets( + self, + ) -> Callable[[compute.ListNamedSetsRoutersRequest], compute.RoutersListNamedSets]: + # 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._ListNamedSets(self._session, self._host, self._interceptor) # type: ignore + @property def list_route_policies( self, @@ -3956,6 +5104,14 @@ def patch(self) -> Callable[[compute.PatchRouterRequest], compute.Operation]: # In C++ this would require a dynamic_cast return self._Patch(self._session, self._host, self._interceptor) # type: ignore + @property + def patch_named_set( + self, + ) -> Callable[[compute.PatchNamedSetRouterRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._PatchNamedSet(self._session, self._host, self._interceptor) # type: ignore + @property def patch_route_policy( self, @@ -3978,6 +5134,14 @@ def update(self) -> Callable[[compute.UpdateRouterRequest], compute.Operation]: # In C++ this would require a dynamic_cast return self._Update(self._session, self._host, self._interceptor) # type: ignore + @property + def update_named_set( + self, + ) -> Callable[[compute.UpdateNamedSetRouterRequest], compute.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._UpdateNamedSet(self._session, self._host, self._interceptor) # type: ignore + @property def update_route_policy( self, diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest_base.py b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest_base.py index 1fc2700f184b..21937c63c7e2 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest_base.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/services/routers/transports/rest_base.py @@ -179,6 +179,52 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseDeleteNamedSet: + 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": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/routers/{router}/deleteNamedSet", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.DeleteNamedSetRouterRequest.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( + _BaseRoutersRestTransport._BaseDeleteNamedSet._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseDeleteRoutePolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -271,6 +317,52 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseGetNamedSet: + 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/v1/projects/{project}/regions/{region}/routers/{router}/getNamedSet", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.GetNamedSetRouterRequest.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( + _BaseRoutersRestTransport._BaseGetNamedSet._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseGetNatIpInfo: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -603,6 +695,52 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseListNamedSets: + 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/v1/projects/{project}/regions/{region}/routers/{router}/listNamedSets", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.ListNamedSetsRoutersRequest.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( + _BaseRoutersRestTransport._BaseListNamedSets._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseListRoutePolicies: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -705,6 +843,62 @@ def _get_query_params_json(transcoded_request): return query_params + class _BasePatchNamedSet: + 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": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/routers/{router}/patchNamedSet", + "body": "named_set_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.PatchNamedSetRouterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @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( + _BaseRoutersRestTransport._BasePatchNamedSet._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BasePatchRoutePolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -873,6 +1067,62 @@ def _get_query_params_json(transcoded_request): return query_params + class _BaseUpdateNamedSet: + 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": "post", + "uri": "/compute/v1/projects/{project}/regions/{region}/routers/{router}/updateNamedSet", + "body": "named_set_resource", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = compute.UpdateNamedSetRouterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=False + ) + return body + + @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( + _BaseRoutersRestTransport._BaseUpdateNamedSet._get_unset_required_fields( + query_params + ) + ) + + return query_params + class _BaseUpdateRoutePolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py index 75aab92f650e..cbcc83afcc60 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/__init__.py @@ -54,6 +54,7 @@ AddSignedUrlKeyBackendBucketRequest, AddSignedUrlKeyBackendServiceRequest, AdvancedMachineFeatures, + AdvanceRolloutRequest, AggregatedListAcceleratorTypesRequest, AggregatedListAddressesRequest, AggregatedListAutoscalersRequest, @@ -177,6 +178,7 @@ BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy, BackendServiceLocalityLoadBalancingPolicyConfigPolicy, BackendServiceLogConfig, + BackendServiceLogConfigLoggingHttpHeader, BackendServiceNetworkPassThroughLbTrafficPolicy, BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity, BackendServiceOrchestrationInfo, @@ -254,6 +256,7 @@ CustomErrorResponsePolicyCustomErrorResponseRule, Data, Date, + DateTime, DeleteAccessConfigInstanceRequest, DeleteAddressRequest, DeleteAutoscalerRequest, @@ -292,6 +295,7 @@ DeleteInterconnectRequest, DeleteLicenseRequest, DeleteMachineImageRequest, + DeleteNamedSetRouterRequest, DeleteNetworkAttachmentRequest, DeleteNetworkEdgeSecurityServiceRequest, DeleteNetworkEndpointGroupRequest, @@ -431,6 +435,7 @@ FlexibleTimeRange, ForwardingRule, ForwardingRuleAggregatedList, + ForwardingRuleAttachedExtension, ForwardingRuleList, ForwardingRuleReference, ForwardingRuleServiceDirectoryRegistration, @@ -549,6 +554,7 @@ GetMachineImageRequest, GetMachineTypeRequest, GetMacsecConfigInterconnectRequest, + GetNamedSetRouterRequest, GetNatIpInfoRouterRequest, GetNatMappingInfoRoutersRequest, GetNetworkAttachmentRequest, @@ -831,6 +837,7 @@ InstanceGroupManagerInstanceFlexibilityPolicy, InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection, InstanceGroupManagerInstanceLifecyclePolicy, + InstanceGroupManagerInstanceLifecyclePolicyOnRepair, InstanceGroupManagerList, InstanceGroupManagerResizeRequest, InstanceGroupManagerResizeRequestsListResponse, @@ -1054,6 +1061,7 @@ ListMachineTypesRequest, ListManagedInstancesInstanceGroupManagersRequest, ListManagedInstancesRegionInstanceGroupManagersRequest, + ListNamedSetsRoutersRequest, ListNetworkAttachmentsRequest, ListNetworkEndpointGroupsRequest, ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest, @@ -1165,6 +1173,8 @@ ManagedInstanceLastAttempt, ManagedInstanceLastAttemptErrors, ManagedInstancePropertiesFromFlexibilityPolicy, + ManagedInstanceScheduling, + ManagedInstanceShutdownDetails, ManagedInstanceVersion, Metadata, MetadataFilter, @@ -1176,6 +1186,7 @@ MoveInstanceProjectRequest, MoveOrganizationSecurityPolicyRequest, NamedPort, + NamedSet, NatIpInfo, NatIpInfoNatIpInfoMapping, NatIpInfoResponse, @@ -1286,6 +1297,7 @@ PatchInterconnectAttachmentRequest, PatchInterconnectGroupRequest, PatchInterconnectRequest, + PatchNamedSetRouterRequest, PatchNetworkAttachmentRequest, PatchNetworkEdgeSecurityServiceRequest, PatchNetworkFirewallPolicyRequest, @@ -1334,12 +1346,14 @@ PatchWireGroupRequest, PathMatcher, PathRule, + PauseRolloutRequest, PerformMaintenanceInstanceRequest, PerformMaintenanceNodeGroupRequest, PerformMaintenanceReservationBlockRequest, PerformMaintenanceReservationRequest, PerformMaintenanceReservationSubBlockRequest, PerInstanceConfig, + PeriodicPartialMaintenanceSchedule, Policy, PreconfiguredWafSet, PreservedState, @@ -1500,11 +1514,13 @@ ResourceStatus, ResourceStatusEffectiveInstanceMetadata, ResourceStatusPhysicalHostTopology, + ResourceStatusPhysicalHostTopologyAdditionalAttributes, ResourceStatusReservationConsumptionInfo, ResourceStatusScheduling, ResumeInstanceRequest, ResumeInstancesInstanceGroupManagerRequest, ResumeInstancesRegionInstanceGroupManagerRequest, + ResumeRolloutRequest, Rollout, RolloutPlan, RolloutPlansListResponse, @@ -1545,8 +1561,10 @@ RouterNatSubnetworkToNat, RouterNatSubnetworkToNat64, RouterParams, + RoutersGetNamedSetResponse, RoutersGetRoutePolicyResponse, RoutersListBgpRoutes, + RoutersListNamedSets, RoutersListRoutePolicies, RoutersPreviewResponse, RoutersScopedList, @@ -1902,6 +1920,7 @@ TestIamPermissionsVpnGatewayRequest, TestPermissionsRequest, TestPermissionsResponse, + TimeZone, Uint128, UpcomingMaintenance, UpdateAccessConfigInstanceRequest, @@ -1920,6 +1939,7 @@ UpdateKmsKeyRegionSnapshotRequest, UpdateKmsKeySnapshotRequest, UpdateLicenseRequest, + UpdateNamedSetRouterRequest, UpdateNetworkInterfaceInstanceRequest, UpdatePeeringNetworkRequest, UpdatePerInstanceConfigsInstanceGroupManagerRequest, @@ -2010,6 +2030,7 @@ XpnResourceId, Zone, ZoneList, + ZoneResourceStatus, ZoneSetLabelsRequest, ZoneSetNestedPolicyRequest, ZoneSetPolicyRequest, @@ -2056,6 +2077,7 @@ "AddSignedUrlKeyBackendBucketRequest", "AddSignedUrlKeyBackendServiceRequest", "AdvancedMachineFeatures", + "AdvanceRolloutRequest", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", "AggregatedListAutoscalersRequest", @@ -2179,6 +2201,7 @@ "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -2256,6 +2279,7 @@ "CustomErrorResponsePolicyCustomErrorResponseRule", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -2294,6 +2318,7 @@ "DeleteInterconnectRequest", "DeleteLicenseRequest", "DeleteMachineImageRequest", + "DeleteNamedSetRouterRequest", "DeleteNetworkAttachmentRequest", "DeleteNetworkEdgeSecurityServiceRequest", "DeleteNetworkEndpointGroupRequest", @@ -2433,6 +2458,7 @@ "FlexibleTimeRange", "ForwardingRule", "ForwardingRuleAggregatedList", + "ForwardingRuleAttachedExtension", "ForwardingRuleList", "ForwardingRuleReference", "ForwardingRuleServiceDirectoryRegistration", @@ -2551,6 +2577,7 @@ "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", "GetNetworkAttachmentRequest", @@ -2833,6 +2860,7 @@ "InstanceGroupManagerInstanceFlexibilityPolicy", "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerResizeRequest", "InstanceGroupManagerResizeRequestsListResponse", @@ -3056,6 +3084,7 @@ "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest", @@ -3167,6 +3196,8 @@ "ManagedInstanceLastAttempt", "ManagedInstanceLastAttemptErrors", "ManagedInstancePropertiesFromFlexibilityPolicy", + "ManagedInstanceScheduling", + "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", "Metadata", "MetadataFilter", @@ -3178,6 +3209,7 @@ "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "NamedPort", + "NamedSet", "NatIpInfo", "NatIpInfoNatIpInfoMapping", "NatIpInfoResponse", @@ -3288,6 +3320,7 @@ "PatchInterconnectAttachmentRequest", "PatchInterconnectGroupRequest", "PatchInterconnectRequest", + "PatchNamedSetRouterRequest", "PatchNetworkAttachmentRequest", "PatchNetworkEdgeSecurityServiceRequest", "PatchNetworkFirewallPolicyRequest", @@ -3336,12 +3369,14 @@ "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseRolloutRequest", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", "PerInstanceConfig", + "PeriodicPartialMaintenanceSchedule", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -3502,11 +3537,13 @@ "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeRolloutRequest", "Rollout", "RolloutPlan", "RolloutPlansListResponse", @@ -3547,8 +3584,10 @@ "RouterNatSubnetworkToNat", "RouterNatSubnetworkToNat64", "RouterParams", + "RoutersGetNamedSetResponse", "RoutersGetRoutePolicyResponse", "RoutersListBgpRoutes", + "RoutersListNamedSets", "RoutersListRoutePolicies", "RoutersPreviewResponse", "RoutersScopedList", @@ -3904,6 +3943,7 @@ "TestIamPermissionsVpnGatewayRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -3922,6 +3962,7 @@ "UpdateKmsKeyRegionSnapshotRequest", "UpdateKmsKeySnapshotRequest", "UpdateLicenseRequest", + "UpdateNamedSetRouterRequest", "UpdateNetworkInterfaceInstanceRequest", "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", @@ -4012,6 +4053,7 @@ "XpnResourceId", "Zone", "ZoneList", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", diff --git a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py index e0e92518bf03..47268a086f97 100644 --- a/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py +++ b/packages/google-cloud-compute/google/cloud/compute_v1/types/compute.py @@ -63,6 +63,7 @@ "AddressAggregatedList", "AddressList", "AddressesScopedList", + "AdvanceRolloutRequest", "AdvancedMachineFeatures", "AggregatedListAcceleratorTypesRequest", "AggregatedListAddressesRequest", @@ -186,6 +187,7 @@ "BackendServiceLocalityLoadBalancingPolicyConfigCustomPolicy", "BackendServiceLocalityLoadBalancingPolicyConfigPolicy", "BackendServiceLogConfig", + "BackendServiceLogConfigLoggingHttpHeader", "BackendServiceNetworkPassThroughLbTrafficPolicy", "BackendServiceNetworkPassThroughLbTrafficPolicyZonalAffinity", "BackendServiceOrchestrationInfo", @@ -263,6 +265,7 @@ "CustomerEncryptionKeyProtectedDisk", "Data", "Date", + "DateTime", "DeleteAccessConfigInstanceRequest", "DeleteAddressRequest", "DeleteAutoscalerRequest", @@ -301,6 +304,7 @@ "DeleteInterconnectRequest", "DeleteLicenseRequest", "DeleteMachineImageRequest", + "DeleteNamedSetRouterRequest", "DeleteNetworkAttachmentRequest", "DeleteNetworkEdgeSecurityServiceRequest", "DeleteNetworkEndpointGroupRequest", @@ -440,6 +444,7 @@ "FlexibleTimeRange", "ForwardingRule", "ForwardingRuleAggregatedList", + "ForwardingRuleAttachedExtension", "ForwardingRuleList", "ForwardingRuleReference", "ForwardingRuleServiceDirectoryRegistration", @@ -560,6 +565,7 @@ "GetMachineImageRequest", "GetMachineTypeRequest", "GetMacsecConfigInterconnectRequest", + "GetNamedSetRouterRequest", "GetNatIpInfoRouterRequest", "GetNatMappingInfoRoutersRequest", "GetNetworkAttachmentRequest", @@ -840,6 +846,7 @@ "InstanceGroupManagerInstanceFlexibilityPolicy", "InstanceGroupManagerInstanceFlexibilityPolicyInstanceSelection", "InstanceGroupManagerInstanceLifecyclePolicy", + "InstanceGroupManagerInstanceLifecyclePolicyOnRepair", "InstanceGroupManagerList", "InstanceGroupManagerResizeRequest", "InstanceGroupManagerResizeRequestStatus", @@ -1063,6 +1070,7 @@ "ListMachineTypesRequest", "ListManagedInstancesInstanceGroupManagersRequest", "ListManagedInstancesRegionInstanceGroupManagersRequest", + "ListNamedSetsRoutersRequest", "ListNetworkAttachmentsRequest", "ListNetworkEndpointGroupsRequest", "ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest", @@ -1174,6 +1182,8 @@ "ManagedInstanceLastAttempt", "ManagedInstanceLastAttemptErrors", "ManagedInstancePropertiesFromFlexibilityPolicy", + "ManagedInstanceScheduling", + "ManagedInstanceShutdownDetails", "ManagedInstanceVersion", "Metadata", "MetadataFilter", @@ -1185,6 +1195,7 @@ "MoveInstanceProjectRequest", "MoveOrganizationSecurityPolicyRequest", "NamedPort", + "NamedSet", "NatIpInfo", "NatIpInfoNatIpInfoMapping", "NatIpInfoResponse", @@ -1295,6 +1306,7 @@ "PatchInterconnectAttachmentRequest", "PatchInterconnectGroupRequest", "PatchInterconnectRequest", + "PatchNamedSetRouterRequest", "PatchNetworkAttachmentRequest", "PatchNetworkEdgeSecurityServiceRequest", "PatchNetworkFirewallPolicyRequest", @@ -1343,12 +1355,14 @@ "PatchWireGroupRequest", "PathMatcher", "PathRule", + "PauseRolloutRequest", "PerInstanceConfig", "PerformMaintenanceInstanceRequest", "PerformMaintenanceNodeGroupRequest", "PerformMaintenanceReservationBlockRequest", "PerformMaintenanceReservationRequest", "PerformMaintenanceReservationSubBlockRequest", + "PeriodicPartialMaintenanceSchedule", "Policy", "PreconfiguredWafSet", "PreservedState", @@ -1509,11 +1523,13 @@ "ResourceStatus", "ResourceStatusEffectiveInstanceMetadata", "ResourceStatusPhysicalHostTopology", + "ResourceStatusPhysicalHostTopologyAdditionalAttributes", "ResourceStatusReservationConsumptionInfo", "ResourceStatusScheduling", "ResumeInstanceRequest", "ResumeInstancesInstanceGroupManagerRequest", "ResumeInstancesRegionInstanceGroupManagerRequest", + "ResumeRolloutRequest", "Rollout", "RolloutPlan", "RolloutPlanWave", @@ -1559,8 +1575,10 @@ "RouterStatusNatStatus", "RouterStatusNatStatusNatRuleStatus", "RouterStatusResponse", + "RoutersGetNamedSetResponse", "RoutersGetRoutePolicyResponse", "RoutersListBgpRoutes", + "RoutersListNamedSets", "RoutersListRoutePolicies", "RoutersPreviewResponse", "RoutersScopedList", @@ -1911,6 +1929,7 @@ "TestIamPermissionsVpnGatewayRequest", "TestPermissionsRequest", "TestPermissionsResponse", + "TimeZone", "Uint128", "UpcomingMaintenance", "UpdateAccessConfigInstanceRequest", @@ -1929,6 +1948,7 @@ "UpdateKmsKeyRegionSnapshotRequest", "UpdateKmsKeySnapshotRequest", "UpdateLicenseRequest", + "UpdateNamedSetRouterRequest", "UpdateNetworkInterfaceInstanceRequest", "UpdatePeeringNetworkRequest", "UpdatePerInstanceConfigsInstanceGroupManagerRequest", @@ -2019,6 +2039,7 @@ "XpnResourceId", "Zone", "ZoneList", + "ZoneResourceStatus", "ZoneSetLabelsRequest", "ZoneSetNestedPolicyRequest", "ZoneSetPolicyRequest", @@ -4442,27 +4463,39 @@ class Address(proto.Message): This field is a member of `oneof`_ ``_id``. ip_collection (str): - Reference to the source of external IPv4 - addresses, like a PublicDelegatedPrefix (PDP) - for BYOIP. The PDP must support enhanced IPv4 - allocations. + Reference to the source of IP addresses. - Use one of the following formats to specify a - PDP when reserving an external IPv4 address - using BYOIP. + It supports the following cases: - - Full resource URL, as - inhttps://www.googleapis.com/compute/v1/projects/projectId/regions/region/publicDelegatedPrefixes/pdp-name - - - Partial URL, as in + Case 1: PublicDelegatedPrefix (PDP) for + BYOIP external IPv4 addresses. The PDP must + support enhanced IPv4 allocations. - + Case 2: Internal Range for global internal + addresses. + + Use one of the following formats to specify the + resource: + For a Public Delegated Prefix: + + - + Full resource + URL:https://www.googleapis.com/compute/v1/projects/projectId/regions/region/publicDelegatedPrefixes/pdp + - Partial URL: - - + - projects/projectId/regions/region/publicDelegatedPrefixes/pdp-name - - + - regions/region/publicDelegatedPrefixes/pdp-name + For an Internal Range: + + - Full + URL:https://networkconnectivity.googleapis.com/v1/projects/project/locations/global/internalRanges/internal-range + - Partial + URL:projects/project/locations/global/internalRanges/internal-range + This field is a member of `oneof`_ ``_ip_collection``. ip_version (str): The IP version that will be used by this @@ -5098,6 +5131,67 @@ class AddressesScopedList(proto.Message): ) +class AdvanceRolloutRequest(proto.Message): + r"""A request message for Rollouts.Advance. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + current_wave_number (int): + Required. Wave number of the current wave. + + This field is a member of `oneof`_ ``_current_wave_number``. + project (str): + Required. Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + advance. + """ + + current_wave_number: int = proto.Field( + proto.INT64, + number=178280841, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class AdvancedMachineFeatures(proto.Message): r"""Specifies options for controlling advanced machine features. Options that would traditionally be configured in a BIOS belong @@ -16619,30 +16713,6 @@ class AttachedDiskInitializeParams(proto.Message): This field is a member of `oneof`_ ``_disk_size_gb``. disk_type (str): - Specifies the disk type to use to create the - instance. If not specified, the default is - pd-standard, specified using the full URL. For - example: - - https://www.googleapis.com/compute/v1/projects/project/zones/zone/diskTypes/pd-standard - - For a full list of acceptable values, - seePersistent disk types. If you specify this - field when creating a VM, you can provide either - the full or partial URL. For example, the - following values are valid: - - - - - https://www.googleapis.com/compute/v1/projects/project/zones/zone/diskTypes/diskType - - - projects/project/zones/zone/diskTypes/diskType - - zones/zone/diskTypes/diskType - - If you specify this field when creating or - updating an instance template or all-instances - configuration, specify the type of the disk, not - the URL. For example: pd-standard. This field is a member of `oneof`_ ``_disk_type``. enable_confidential_compute (bool): @@ -17905,8 +17975,9 @@ class Mode(proto.Enum): Automatically create VMs according to the policy, but do not scale the MIG in. ONLY_UP (478095374): - Automatically create VMs according to the - policy, but do not scale the MIG in. + Automatically create VMs according to the policy, but do not + scale the MIG in. It's recommended to use ONLY_SCALE_OUT + instead of ONLY_UP. """ UNDEFINED_MODE = 0 @@ -22525,6 +22596,12 @@ class BackendServiceLogConfig(proto.Message): service. The default value is false. This field is a member of `oneof`_ ``_enable``. + logging_http_request_headers (MutableSequence[google.cloud.compute_v1.types.BackendServiceLogConfigLoggingHttpHeader]): + The list of request headers that will be + logged to Stackdriver. + logging_http_response_headers (MutableSequence[google.cloud.compute_v1.types.BackendServiceLogConfigLoggingHttpHeader]): + The list of response headers that will be + logged to Stackdriver. optional_fields (MutableSequence[str]): This field can only be specified if logging is enabled for this backend service and @@ -22583,6 +22660,20 @@ class OptionalMode(proto.Enum): number=311764355, optional=True, ) + logging_http_request_headers: MutableSequence[ + "BackendServiceLogConfigLoggingHttpHeader" + ] = proto.RepeatedField( + proto.MESSAGE, + number=430426367, + message="BackendServiceLogConfigLoggingHttpHeader", + ) + logging_http_response_headers: MutableSequence[ + "BackendServiceLogConfigLoggingHttpHeader" + ] = proto.RepeatedField( + proto.MESSAGE, + number=515407743, + message="BackendServiceLogConfigLoggingHttpHeader", + ) optional_fields: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=528589944, @@ -22599,6 +22690,25 @@ class OptionalMode(proto.Enum): ) +class BackendServiceLogConfigLoggingHttpHeader(proto.Message): + r"""Determines which HTTP headers will be logged to Stackdriver. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + header_name (str): + The name of the header to be logged. + + This field is a member of `oneof`_ ``_header_name``. + """ + + header_name: str = proto.Field( + proto.STRING, + number=110223613, + optional=True, + ) + + class BackendServiceNetworkPassThroughLbTrafficPolicy(proto.Message): r""" @@ -26920,6 +27030,8 @@ class ConfidentialInstanceType(proto.Enum): UNDEFINED_CONFIDENTIAL_INSTANCE_TYPE (0): A value indicating that the enum field is not set. + CCA (66529): + Arm Confidential Compute Architecture. CONFIDENTIAL_INSTANCE_TYPE_UNSPECIFIED (115021829): No type specified. Do not use this value. SEV (81988): @@ -26932,6 +27044,7 @@ class ConfidentialInstanceType(proto.Enum): """ UNDEFINED_CONFIDENTIAL_INSTANCE_TYPE = 0 + CCA = 66529 CONFIDENTIAL_INSTANCE_TYPE_UNSPECIFIED = 115021829 SEV = 81988 SEV_SNP = 21753562 @@ -28056,6 +28169,141 @@ class Date(proto.Message): ) +class DateTime(proto.Message): + r"""Represents civil time (or occasionally physical time). + + This type can represent a civil time in one of a few possible ways: + + - When utc_offset is set and time_zone is unset: a civil time on a + calendar day with a particular offset from UTC. + - When time_zone is set and utc_offset is unset: a civil time on a + calendar day in a particular time zone. + - When neither time_zone nor utc_offset is set: a civil time on a + calendar day in local time. + + The date is relative to the Proleptic Gregorian Calendar. + + If year, month, or day are 0, the DateTime is considered not to have + a specific year, month, or day respectively. + + This type may also be used to represent a physical time if all the + date and time fields are set and either case of the ``time_offset`` + oneof is set. Consider using ``Timestamp`` message for physical time + instead. If your use case also would like to store the user's + timezone, that can be done in another field. + + This type is more flexible than some applications may want. Make + sure to document and validate your application's limitations. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + day (int): + Optional. Day of month. Must be from 1 to 31 + and valid for the year and month, or 0 if + specifying a datetime without a day. + + This field is a member of `oneof`_ ``_day``. + hours (int): + Optional. Hours of day in 24 hour format. + Should be from 0 to 23, defaults to 0 + (midnight). An API may choose to allow the value + "24:00:00" for scenarios like business closing + time. + + This field is a member of `oneof`_ ``_hours``. + minutes (int): + Optional. Minutes of hour of day. Must be + from 0 to 59, defaults to 0. + + This field is a member of `oneof`_ ``_minutes``. + month (int): + Optional. Month of year. Must be from 1 to + 12, or 0 if specifying a datetime without a + month. + + This field is a member of `oneof`_ ``_month``. + nanos (int): + Optional. Fractions of seconds in + nanoseconds. Must be from 0 to 999,999,999, + defaults to 0. + + This field is a member of `oneof`_ ``_nanos``. + seconds (int): + Optional. Seconds of minutes of the time. + Must normally be from 0 to 59, defaults to 0. An + API may allow the value 60 if it allows + leap-seconds. + + This field is a member of `oneof`_ ``_seconds``. + time_zone (google.cloud.compute_v1.types.TimeZone): + Time zone. + + This field is a member of `oneof`_ ``_time_zone``. + utc_offset (str): + UTC offset. Must be whole seconds, between + -18 hours and +18 hours. For example, a UTC + offset of -4:00 would be represented as { + seconds: -14400 }. + + This field is a member of `oneof`_ ``_utc_offset``. + year (int): + Optional. Year of date. Must be from 1 to + 9999, or 0 if specifying a datetime without a + year. + + This field is a member of `oneof`_ ``_year``. + """ + + day: int = proto.Field( + proto.INT32, + number=99228, + optional=True, + ) + hours: int = proto.Field( + proto.INT32, + number=99469071, + optional=True, + ) + minutes: int = proto.Field( + proto.INT32, + number=528030943, + optional=True, + ) + month: int = proto.Field( + proto.INT32, + number=104080000, + optional=True, + ) + nanos: int = proto.Field( + proto.INT32, + number=104586303, + optional=True, + ) + seconds: int = proto.Field( + proto.INT32, + number=359484031, + optional=True, + ) + time_zone: "TimeZone" = proto.Field( + proto.MESSAGE, + number=36848094, + optional=True, + message="TimeZone", + ) + utc_offset: str = proto.Field( + proto.STRING, + number=89045902, + optional=True, + ) + year: int = proto.Field( + proto.INT32, + number=3704893, + optional=True, + ) + + class DeleteAccessConfigInstanceRequest(proto.Message): r"""A request message for Instances.DeleteAccessConfig. See the method description for details. @@ -29154,6 +29402,12 @@ class DeleteInstanceGroupManagerRequest(proto.Message): instance_group_manager (str): The name of the managed instance group to delete. + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance deletion even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. request_id (str): @@ -29187,6 +29441,11 @@ class DeleteInstanceGroupManagerRequest(proto.Message): proto.STRING, number=249363395, ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -29450,6 +29709,12 @@ class DeleteInstancesInstanceGroupManagerRequest(proto.Message): The name of the managed instance group. instance_group_managers_delete_instances_request_resource (google.cloud.compute_v1.types.InstanceGroupManagersDeleteInstancesRequest): The body resource for this request + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance deletion even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. request_id (str): @@ -29488,6 +29753,11 @@ class DeleteInstancesInstanceGroupManagerRequest(proto.Message): number=166421252, message="InstanceGroupManagersDeleteInstancesRequest", ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -29514,6 +29784,12 @@ class DeleteInstancesRegionInstanceGroupManagerRequest(proto.Message): Attributes: instance_group_manager (str): Name of the managed instance group. + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance deletion even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. region (str): @@ -29548,6 +29824,11 @@ class DeleteInstancesRegionInstanceGroupManagerRequest(proto.Message): proto.STRING, number=249363395, ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -29993,6 +30274,74 @@ class DeleteMachineImageRequest(proto.Message): ) +class DeleteNamedSetRouterRequest(proto.Message): + r"""A request message for Routers.DeleteNamedSet. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + named_set (str): + The Named Set name for this request. Name + must conform to RFC1035 + + This field is a member of `oneof`_ ``_named_set``. + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + router (str): + Name of the Router resource where Named Set + is defined. + """ + + named_set: str = proto.Field( + proto.STRING, + number=164134492, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) + + class DeleteNetworkAttachmentRequest(proto.Message): r"""A request message for NetworkAttachments.Delete. See the method description for details. @@ -31330,6 +31679,12 @@ class DeleteRegionInstanceGroupManagerRequest(proto.Message): Attributes: instance_group_manager (str): Name of the managed instance group to delete. + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance deletion even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. region (str): @@ -31362,6 +31717,11 @@ class DeleteRegionInstanceGroupManagerRequest(proto.Message): proto.STRING, number=249363395, ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -38427,9 +38787,11 @@ class FirewallPolicyRule(proto.Message): action (str): The Action to perform when the client connection triggers the rule. Valid actions for firewall rules are: "allow", - "deny", "apply_security_profile_group" and "goto_next". - Valid actions for packet mirroring rules are: "mirror", - "do_not_mirror" and "goto_next". + "deny", "apply_security_profile_group" and "goto_next" ( + "apply_security_profile_group" can be specified only for + global network firewall policies or hierarchical firewall + policies). Valid actions for packet mirroring rules are: + "mirror", "do_not_mirror" and "goto_next". This field is a member of `oneof`_ ``_action``. description (str): @@ -38490,14 +38852,32 @@ class FirewallPolicyRule(proto.Message): This field is a member of `oneof`_ ``_rule_tuple_count``. security_profile_group (str): - A fully-qualified URL of a SecurityProfile resource + A fully-qualified URL of a SecurityProfileGroup resource instance. Example: https://networksecurity.googleapis.com/v1/projects/{project}/locations/{location}/securityProfileGroups/my-security-profile-group Must be specified if action is one of 'apply_security_profile_group' or 'mirror'. Cannot be - specified for other actions. + specified for other actions. Can be specified only for + global network firewall policies or hierarchical firewall + policies. This field is a member of `oneof`_ ``_security_profile_group``. + target_forwarding_rules (MutableSequence[str]): + A list of forwarding rules to which this rule + applies. This field allows you to control which + load balancers get this rule. For example, the + following are valid values: + + + - + https://www.googleapis.com/compute/v1/projects/project/global/forwardingRules/forwardingRule + - + https://www.googleapis.com/compute/v1/projects/project/regions/region/forwardingRules/forwardingRule + - projects/project/global/ + forwardingRules/forwardingRule + - + projects/project/regions/region/forwardingRules/ + forwardingRule target_resources (MutableSequence[str]): A list of network resource URLs to which this rule applies. This field allows you to control @@ -38519,6 +38899,13 @@ class FirewallPolicyRule(proto.Message): A list of service accounts indicating the sets of instances that are applied with this rule. + target_type (str): + Target types of the firewall policy rule. + Default value is INSTANCES. + Check the TargetType enum for the list of + possible values. + + This field is a member of `oneof`_ ``_target_type``. tls_inspect (bool): Boolean flag indicating if the traffic should be TLS decrypted. Can be set only if action = @@ -38545,6 +38932,24 @@ class Direction(proto.Enum): EGRESS = 432880501 INGRESS = 516931221 + class TargetType(proto.Enum): + r"""Target types of the firewall policy rule. + Default value is INSTANCES. + + Values: + UNDEFINED_TARGET_TYPE (0): + A value indicating that the enum field is not + set. + INSTANCES (131337822): + No description available. + INTERNAL_MANAGED_LB (309241080): + No description available. + """ + + UNDEFINED_TARGET_TYPE = 0 + INSTANCES = 131337822 + INTERNAL_MANAGED_LB = 309241080 + action: str = proto.Field( proto.STRING, number=187661878, @@ -38601,6 +39006,10 @@ class Direction(proto.Enum): number=207411626, optional=True, ) + target_forwarding_rules: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=495923747, + ) target_resources: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=528230647, @@ -38616,6 +39025,11 @@ class Direction(proto.Enum): proto.STRING, number=457639710, ) + target_type: str = proto.Field( + proto.STRING, + number=62925096, + optional=True, + ) tls_inspect: bool = proto.Field( proto.BOOL, number=43425488, @@ -39223,6 +39637,9 @@ class ForwardingRule(proto.Message): accessed from another region. This field is a member of `oneof`_ ``_allow_psc_global_access``. + attached_extensions (MutableSequence[google.cloud.compute_v1.types.ForwardingRuleAttachedExtension]): + Output only. [Output Only]. The extensions that are attached + to this ForwardingRule. backend_service (str): Identifies the backend service to which the forwarding rule sends traffic. Required for @@ -39841,6 +40258,13 @@ class PscConnectionStatus(proto.Enum): number=263471819, optional=True, ) + attached_extensions: MutableSequence["ForwardingRuleAttachedExtension"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=385226127, + message="ForwardingRuleAttachedExtension", + ) + ) backend_service: str = proto.Field( proto.STRING, number=306946058, @@ -40092,6 +40516,27 @@ def raw_page(self): ) +class ForwardingRuleAttachedExtension(proto.Message): + r"""Reference to an extension resource that is attached to this + ForwardingRule. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + reference (str): + Output only. The resource name. + + This field is a member of `oneof`_ ``_reference``. + """ + + reference: str = proto.Field( + proto.STRING, + number=148586315, + optional=True, + ) + + class ForwardingRuleList(proto.Message): r"""Contains a list of ForwardingRule resources. @@ -42841,6 +43286,9 @@ class GetForwardingRuleRequest(proto.Message): r"""A request message for ForwardingRules.Get. See the method description for details. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: forwarding_rule (str): Name of the ForwardingRule resource to @@ -42849,8 +43297,32 @@ class GetForwardingRuleRequest(proto.Message): Project ID for this request. region (str): Name of the region scoping this request. + view (str): + Check the View enum for the list of possible + values. + + This field is a member of `oneof`_ ``_view``. """ + class View(proto.Enum): + r""" + + Values: + UNDEFINED_VIEW (0): + A value indicating that the enum field is not + set. + BASIC (62970894): + The default view of a ForwardingRule, which + includes the basic fields. + FULL (2169487): + The full view, including the + ForwardingRule.\ ``attached_extensions`` field. + """ + + UNDEFINED_VIEW = 0 + BASIC = 62970894 + FULL = 2169487 + forwarding_rule: str = proto.Field( proto.STRING, number=269964030, @@ -42863,6 +43335,11 @@ class GetForwardingRuleRequest(proto.Message): proto.STRING, number=138946292, ) + view: str = proto.Field( + proto.STRING, + number=3619493, + optional=True, + ) class GetFromFamilyImageRequest(proto.Message): @@ -42942,14 +43419,41 @@ class GetGlobalForwardingRuleRequest(proto.Message): r"""A request message for GlobalForwardingRules.Get. See the method description for details. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Attributes: forwarding_rule (str): Name of the ForwardingRule resource to return. project (str): Project ID for this request. + view (str): + Check the View enum for the list of possible + values. + + This field is a member of `oneof`_ ``_view``. """ + class View(proto.Enum): + r""" + + Values: + UNDEFINED_VIEW (0): + A value indicating that the enum field is not + set. + BASIC (62970894): + The default view of a ForwardingRule, which + includes the basic fields. + FULL (2169487): + The full view, including the + ForwardingRule.\ ``attached_extensions`` field. + """ + + UNDEFINED_VIEW = 0 + BASIC = 62970894 + FULL = 2169487 + forwarding_rule: str = proto.Field( proto.STRING, number=269964030, @@ -42958,6 +43462,11 @@ class GetGlobalForwardingRuleRequest(proto.Message): proto.STRING, number=227560217, ) + view: str = proto.Field( + proto.STRING, + number=3619493, + optional=True, + ) class GetGlobalNetworkEndpointGroupRequest(proto.Message): @@ -45046,6 +45555,47 @@ class GetMacsecConfigInterconnectRequest(proto.Message): ) +class GetNamedSetRouterRequest(proto.Message): + r"""A request message for Routers.GetNamedSet. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + named_set (str): + The Named Set name for this request. Name + must conform to RFC1035 + + This field is a member of `oneof`_ ``_named_set``. + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + router (str): + Name of the Router resource to query for the + named set. The name should conform to RFC1035. + """ + + named_set: str = proto.Field( + proto.STRING, + number=164134492, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) + + class GetNatIpInfoRouterRequest(proto.Message): r"""A request message for Routers.GetNatIpInfo. See the method description for details. @@ -49485,6 +50035,8 @@ class Type(proto.Enum): set. BARE_METAL_LINUX_COMPATIBLE (354232740): No description available. + CCA_CAPABLE (79012270): + No description available. FEATURE_TYPE_UNSPECIFIED (531767259): No description available. GVNIC (68209305): @@ -49517,6 +50069,7 @@ class Type(proto.Enum): UNDEFINED_TYPE = 0 BARE_METAL_LINUX_COMPATIBLE = 354232740 + CCA_CAPABLE = 79012270 FEATURE_TYPE_UNSPECIFIED = 531767259 GVNIC = 68209305 IDPF = 2242641 @@ -59792,6 +60345,13 @@ class Instance(proto.Message): inRFC3339 text format. This field is a member of `oneof`_ ``_last_suspended_timestamp``. + local_ssd_encryption_mode (str): + Specifies which method should be used for + encrypting the Local SSDs attached to the VM. + Check the LocalSsdEncryptionMode enum for the + list of possible values. + + This field is a member of `oneof`_ ``_local_ssd_encryption_mode``. machine_type (str): Full or partial URL of the machine type resource to use for this instance, in the @@ -59989,6 +60549,34 @@ class KeyRevocationActionType(proto.Enum): NONE = 2402104 STOP = 2555906 + class LocalSsdEncryptionMode(proto.Enum): + r"""Specifies which method should be used for encrypting the + Local SSDs attached to the VM. + + Values: + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE (0): + A value indicating that the enum field is not + set. + EPHEMERAL_KEY_ENCRYPTION (413047941): + The given VM will opt-in for using ephemeral + key for encryption of Local SSDs. + The Local SSDs will not be able to recover data + in case of VM crash. + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED (454655720): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + STANDARD_ENCRYPTION (269392453): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + """ + + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE = 0 + EPHEMERAL_KEY_ENCRYPTION = 413047941 + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED = 454655720 + STANDARD_ENCRYPTION = 269392453 + class PrivateIpv6GoogleAccess(proto.Enum): r"""The private IPv6 google access type for the VM. If not specified, use INHERIT_FROM_SUBNETWORK as default. @@ -60183,6 +60771,11 @@ class Status(proto.Enum): number=356275337, optional=True, ) + local_ssd_encryption_mode: str = proto.Field( + proto.STRING, + number=121582032, + optional=True, + ) machine_type: str = proto.Field( proto.STRING, number=227711026, @@ -61732,17 +62325,17 @@ class InstanceGroupManagerInstanceLifecyclePolicy(proto.Message): Attributes: default_action_on_failure (str): - The action that a MIG performs on a failed or an unhealthy - VM. A VM is marked as unhealthy when the application running - on that VM fails a health check. Valid values are + The action that a MIG performs on a failed VM. If the value + of the onFailedHealthCheck field is ``DEFAULT_ACTION``, then + the same action also applies to the VMs on which your + application fails a health check. Valid values are :: - - REPAIR (default): MIG automatically repairs a failed or - an unhealthy VM by recreating it. For more information, see About + - REPAIR (default): MIG automatically repairs a failed VM + by recreating it. For more information, see About repairing VMs in a MIG. - - DO_NOTHING: MIG does not repair a failed or an unhealthy - VM. + - DO_NOTHING: MIG does not repair a failed VM. Check the DefaultActionOnFailure enum for the list of possible values. @@ -61787,20 +62380,24 @@ class InstanceGroupManagerInstanceLifecyclePolicy(proto.Message): values. This field is a member of `oneof`_ ``_on_failed_health_check``. + on_repair (google.cloud.compute_v1.types.InstanceGroupManagerInstanceLifecyclePolicyOnRepair): + Configuration for VM repairs in the MIG. + + This field is a member of `oneof`_ ``_on_repair``. """ class DefaultActionOnFailure(proto.Enum): - r"""The action that a MIG performs on a failed or an unhealthy VM. A VM - is marked as unhealthy when the application running on that VM fails - a health check. Valid values are + r"""The action that a MIG performs on a failed VM. If the value of the + onFailedHealthCheck field is ``DEFAULT_ACTION``, then the same + action also applies to the VMs on which your application fails a + health check. Valid values are :: - - REPAIR (default): MIG automatically repairs a failed or - an unhealthy VM by recreating it. For more information, see About + - REPAIR (default): MIG automatically repairs a failed VM + by recreating it. For more information, see About repairing VMs in a MIG. - - DO_NOTHING: MIG does not repair a failed or an unhealthy - VM. + - DO_NOTHING: MIG does not repair a failed VM. Additional supported values which may be not listed in the enum directly due to technical reasons: DO_NOTHING REPAIR @@ -61894,6 +62491,63 @@ class OnFailedHealthCheck(proto.Enum): number=39807943, optional=True, ) + on_repair: "InstanceGroupManagerInstanceLifecyclePolicyOnRepair" = proto.Field( + proto.MESSAGE, + number=371820013, + optional=True, + message="InstanceGroupManagerInstanceLifecyclePolicyOnRepair", + ) + + +class InstanceGroupManagerInstanceLifecyclePolicyOnRepair(proto.Message): + r"""Configuration for VM repairs in the MIG. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + allow_changing_zone (str): + Specifies whether the MIG can change a VM's + zone during a repair. Valid values are: + + - NO (default): MIG cannot change a VM's zone + during a repair. + - YES: MIG can select a different zone for + the VM during a repair. + Check the AllowChangingZone enum for the list of + possible values. + + This field is a member of `oneof`_ ``_allow_changing_zone``. + """ + + class AllowChangingZone(proto.Enum): + r"""Specifies whether the MIG can change a VM's zone during a + repair. Valid values are: + + - NO (default): MIG cannot change a VM's zone during a + repair. + - YES: MIG can select a different zone for the VM during a + repair. + + Values: + UNDEFINED_ALLOW_CHANGING_ZONE (0): + A value indicating that the enum field is not + set. + NO (2497): + [Default] MIG cannot change a VM's zone during a repair. + YES (87751): + MIG can select a different zone for the VM + during a repair. + """ + + UNDEFINED_ALLOW_CHANGING_ZONE = 0 + NO = 2497 + YES = 87751 + + allow_changing_zone: str = proto.Field( + proto.STRING, + number=426055112, + optional=True, + ) class InstanceGroupManagerList(proto.Message): @@ -62000,6 +62654,12 @@ class InstanceGroupManagerResizeRequest(proto.Message): identifier. This field is a member of `oneof`_ ``_id``. + instances (MutableSequence[google.cloud.compute_v1.types.PerInstanceConfig]): + The names of instances to be created by this resize request. + The number of names specified determines the number of + instances to create. The group's target size will be + increased by this number. This field cannot be used together + with 'resize_by'. kind (str): Output only. The resource type, which is alwayscompute#instanceGroupManagerResizeRequest @@ -62111,6 +62771,11 @@ class State(proto.Enum): number=3355, optional=True, ) + instances: MutableSequence["PerInstanceConfig"] = proto.RepeatedField( + proto.MESSAGE, + number=29097598, + message="PerInstanceConfig", + ) kind: str = proto.Field( proto.STRING, number=3292052, @@ -64329,17 +64994,18 @@ class InstanceManagedByIgmError(proto.Message): Attributes: error (google.cloud.compute_v1.types.InstanceManagedByIgmErrorManagedInstanceError): - Output only. [Output Only] Contents of the error. + Output only. Contents of the error. This field is a member of `oneof`_ ``_error``. instance_action_details (google.cloud.compute_v1.types.InstanceManagedByIgmErrorInstanceActionDetails): - Output only. [Output Only] Details of the instance action - that triggered this error. May be null, if the error was not - caused by an action on an instance. This field is optional. + Output only. Details of the instance action + that triggered this error. May be null, if the + error was not caused by an action on an + instance. This field is optional. This field is a member of `oneof`_ ``_instance_action_details``. timestamp (str): - Output only. [Output Only] The time that this error + Output only. The time that this error occurred. This value is in RFC3339 text format. This field is a member of `oneof`_ ``_timestamp``. @@ -64373,30 +65039,34 @@ class InstanceManagedByIgmErrorInstanceActionDetails(proto.Message): Attributes: action (str): - Output only. [Output Only] Action that managed instance - group was executing on the instance when the error occurred. - Possible values: Check the Action enum for the list of - possible values. + Output only. Action that managed instance + group was executing on the instance when the + error occurred. Possible values: + + Check the Action enum for the list of possible + values. This field is a member of `oneof`_ ``_action``. instance (str): - Output only. [Output Only] The URL of the instance. The URL - can be set even if the instance has not yet been created. + Output only. The URL of the instance. The URL + can be set even if the instance has not yet been + created. This field is a member of `oneof`_ ``_instance``. version (google.cloud.compute_v1.types.ManagedInstanceVersion): - Output only. [Output Only] Version this instance was created - from, or was being created from, but the creation failed. - Corresponds to one of the versions that were set on the - Instance Group Manager resource at the time this instance - was being created. + Output only. Version this instance was + created from, or was being created from, but the + creation failed. Corresponds to one of the + versions that were set on the Instance Group + Manager resource at the time this instance was + being created. This field is a member of `oneof`_ ``_version``. """ class Action(proto.Enum): - r"""Output only. [Output Only] Action that managed instance group was - executing on the instance when the error occurred. Possible values: + r"""Output only. Action that managed instance group was executing + on the instance when the error occurred. Possible values: Values: UNDEFINED_ACTION (0): @@ -64504,11 +65174,11 @@ class InstanceManagedByIgmErrorManagedInstanceError(proto.Message): Attributes: code (str): - Output only. [Output Only] Error code. + Output only. Error code. This field is a member of `oneof`_ ``_code``. message (str): - Output only. [Output Only] Error message. + Output only. Error message. This field is a member of `oneof`_ ``_message``. """ @@ -64659,6 +65329,13 @@ class InstanceProperties(proto.Message): labels (MutableMapping[str, str]): Labels to apply to instances that are created from these properties. + local_ssd_encryption_mode (str): + Specifies which method should be used for + encrypting the Local SSDs attached to the VM. + Check the LocalSsdEncryptionMode enum for the + list of possible values. + + This field is a member of `oneof`_ ``_local_ssd_encryption_mode``. machine_type (str): The machine type to use for instances that are created from these properties. This field only accepts a machine type @@ -64777,6 +65454,34 @@ class KeyRevocationActionType(proto.Enum): NONE = 2402104 STOP = 2555906 + class LocalSsdEncryptionMode(proto.Enum): + r"""Specifies which method should be used for encrypting the + Local SSDs attached to the VM. + + Values: + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE (0): + A value indicating that the enum field is not + set. + EPHEMERAL_KEY_ENCRYPTION (413047941): + The given VM will opt-in for using ephemeral + key for encryption of Local SSDs. + The Local SSDs will not be able to recover data + in case of VM crash. + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED (454655720): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + STANDARD_ENCRYPTION (269392453): + The given VM will be encrypted using keys + managed by the cloud infrastructure and the keys + will be deleted when the VM is deleted. + """ + + UNDEFINED_LOCAL_SSD_ENCRYPTION_MODE = 0 + EPHEMERAL_KEY_ENCRYPTION = 413047941 + LOCAL_SSD_ENCRYPTION_MODE_UNSPECIFIED = 454655720 + STANDARD_ENCRYPTION = 269392453 + class PrivateIpv6GoogleAccess(proto.Enum): r"""The private IPv6 google access type for VMs. If not specified, use INHERIT_FROM_SUBNETWORK as default. Note that for MachineImage, this @@ -64850,6 +65555,11 @@ class PrivateIpv6GoogleAccess(proto.Enum): proto.STRING, number=500195327, ) + local_ssd_encryption_mode: str = proto.Field( + proto.STRING, + number=121582032, + optional=True, + ) machine_type: str = proto.Field( proto.STRING, number=227711026, @@ -66931,6 +67641,13 @@ class Interconnect(proto.Message): resource. This field is a member of `oneof`_ ``_description``. + effective_location (str): + Output only. URL of the InterconnectLocation + object that represents where this connection is + to be provisioned. By default it will be the + same as the location field. + + This field is a member of `oneof`_ ``_effective_location``. expected_outages (MutableSequence[google.cloud.compute_v1.types.InterconnectOutageNotification]): Output only. [Output Only] A list of outages expected for this Interconnect. @@ -67372,6 +68089,11 @@ class Subzone(proto.Enum): number=422937596, optional=True, ) + effective_location: str = proto.Field( + proto.STRING, + number=302355277, + optional=True, + ) expected_outages: MutableSequence["InterconnectOutageNotification"] = ( proto.RepeatedField( proto.MESSAGE, @@ -82265,8 +82987,8 @@ class ListManagedInstancesRegionInstanceGroupManagersRequest(proto.Message): ) -class ListNetworkAttachmentsRequest(proto.Message): - r"""A request message for NetworkAttachments.List. See the method +class ListNamedSetsRoutersRequest(proto.Message): + r"""A request message for Routers.ListNamedSets. See the method description for details. @@ -82379,7 +83101,7 @@ class ListNetworkAttachmentsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region of this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -82391,6 +83113,9 @@ class ListNetworkAttachmentsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + router (str): + Name or id of the resource for this request. + Name should conform to RFC1035. """ filter: str = proto.Field( @@ -82426,11 +83151,15 @@ class ListNetworkAttachmentsRequest(proto.Message): number=517198390, optional=True, ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) -class ListNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for NetworkEndpointGroups.List. See the - method description for details. +class ListNetworkAttachmentsRequest(proto.Message): + r"""A request message for NetworkAttachments.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -82541,6 +83270,8 @@ class ListNetworkEndpointGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -82552,10 +83283,6 @@ class ListNetworkEndpointGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of thezone - where the network endpoint group is located. It - should comply with RFC1035. """ filter: str = proto.Field( @@ -82582,21 +83309,20 @@ class ListNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for - GlobalNetworkEndpointGroups.ListNetworkEndpoints. See the method - description for details. +class ListNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for NetworkEndpointGroups.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -82682,11 +83408,6 @@ class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. - network_endpoint_group (str): - The name of the network endpoint group from - which you want to generate a list of included - network endpoints. It should comply with - RFC1035. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -82723,6 +83444,10 @@ class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of thezone + where the network endpoint group is located. It + should comply with RFC1035. """ filter: str = proto.Field( @@ -82735,10 +83460,6 @@ class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): number=54715419, optional=True, ) - network_endpoint_group: str = proto.Field( - proto.STRING, - number=433907078, - ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -82758,11 +83479,15 @@ class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): +class ListNetworkEndpointsGlobalNetworkEndpointGroupsRequest(proto.Message): r"""A request message for - NetworkEndpointGroups.ListNetworkEndpoints. See the method + GlobalNetworkEndpointGroups.ListNetworkEndpoints. See the method description for details. @@ -82854,8 +83579,6 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): which you want to generate a list of included network endpoints. It should comply with RFC1035. - network_endpoint_groups_list_endpoints_request_resource (google.cloud.compute_v1.types.NetworkEndpointGroupsListEndpointsRequest): - The body resource for this request order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -82892,10 +83615,6 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone where - the network endpoint group is located. It should - comply with RFC1035. """ filter: str = proto.Field( @@ -82912,11 +83631,6 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=433907078, ) - network_endpoint_groups_list_endpoints_request_resource: "NetworkEndpointGroupsListEndpointsRequest" = proto.Field( - proto.MESSAGE, - number=59493390, - message="NetworkEndpointGroupsListEndpointsRequest", - ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -82936,15 +83650,11 @@ class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): +class ListNetworkEndpointsNetworkEndpointGroupsRequest(proto.Message): r"""A request message for - RegionNetworkEndpointGroups.ListNetworkEndpoints. See the method + NetworkEndpointGroups.ListNetworkEndpoints. See the method description for details. @@ -83036,6 +83746,8 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): which you want to generate a list of included network endpoints. It should comply with RFC1035. + network_endpoint_groups_list_endpoints_request_resource (google.cloud.compute_v1.types.NetworkEndpointGroupsListEndpointsRequest): + The body resource for this request order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -83061,10 +83773,6 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - The name of theregion - where the network endpoint group is located. It - should comply with RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -83076,6 +83784,10 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone where + the network endpoint group is located. It should + comply with RFC1035. """ filter: str = proto.Field( @@ -83092,6 +83804,11 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=433907078, ) + network_endpoint_groups_list_endpoints_request_resource: "NetworkEndpointGroupsListEndpointsRequest" = proto.Field( + proto.MESSAGE, + number=59493390, + message="NetworkEndpointGroupsListEndpointsRequest", + ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -83106,176 +83823,20 @@ class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - - -class ListNetworkFirewallPoliciesRequest(proto.Message): - r"""A request message for NetworkFirewallPolicies.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``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. - - You can also sort results in descending order based on the - creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. - - Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. - - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. - - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. - - This field is a member of `oneof`_ ``_return_partial_success``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( + zone: str = proto.Field( proto.STRING, - number=227560217, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, + number=3744684, ) -class ListNetworkProfilesRequest(proto.Message): - r"""A request message for NetworkProfiles.List. See the method +class ListNetworkEndpointsRegionNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for + RegionNetworkEndpointGroups.ListNetworkEndpoints. See the method description for details. @@ -83362,6 +83923,11 @@ class ListNetworkProfilesRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. + network_endpoint_group (str): + The name of the network endpoint group from + which you want to generate a list of included + network endpoints. It should comply with + RFC1035. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -83387,6 +83953,10 @@ class ListNetworkProfilesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + The name of theregion + where the network endpoint group is located. It + should comply with RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -83410,6 +83980,10 @@ class ListNetworkProfilesRequest(proto.Message): number=54715419, optional=True, ) + network_endpoint_group: str = proto.Field( + proto.STRING, + number=433907078, + ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -83424,6 +83998,10 @@ class ListNetworkProfilesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -83431,9 +84009,9 @@ class ListNetworkProfilesRequest(proto.Message): ) -class ListNetworksRequest(proto.Message): - r"""A request message for Networks.List. See the method - description for details. +class ListNetworkFirewallPoliciesRequest(proto.Message): + r"""A request message for NetworkFirewallPolicies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -83588,8 +84166,8 @@ class ListNetworksRequest(proto.Message): ) -class ListNodeGroupsRequest(proto.Message): - r"""A request message for NodeGroups.List. See the method +class ListNetworkProfilesRequest(proto.Message): + r"""A request message for NetworkProfiles.List. See the method description for details. @@ -83712,8 +84290,6 @@ class ListNodeGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -83745,14 +84321,10 @@ class ListNodeGroupsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListNodeTemplatesRequest(proto.Message): - r"""A request message for NodeTemplates.List. See the method +class ListNetworksRequest(proto.Message): + r"""A request message for Networks.List. See the method description for details. @@ -83864,8 +84436,6 @@ class ListNodeTemplatesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -83903,10 +84473,6 @@ class ListNodeTemplatesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -83914,8 +84480,8 @@ class ListNodeTemplatesRequest(proto.Message): ) -class ListNodeTypesRequest(proto.Message): - r"""A request message for NodeTypes.List. See the method +class ListNodeGroupsRequest(proto.Message): + r"""A request message for NodeGroups.List. See the method description for details. @@ -84077,8 +84643,8 @@ class ListNodeTypesRequest(proto.Message): ) -class ListNodesNodeGroupsRequest(proto.Message): - r"""A request message for NodeGroups.ListNodes. See the method +class ListNodeTemplatesRequest(proto.Message): + r"""A request message for NodeTemplates.List. See the method description for details. @@ -84165,9 +84731,6 @@ class ListNodesNodeGroupsRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. - node_group (str): - Name of the NodeGroup resource whose nodes - you want to list. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -84193,6 +84756,8 @@ class ListNodesNodeGroupsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -84204,8 +84769,6 @@ class ListNodesNodeGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -84218,10 +84781,6 @@ class ListNodesNodeGroupsRequest(proto.Message): number=54715419, optional=True, ) - node_group: str = proto.Field( - proto.STRING, - number=469958146, - ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -84236,20 +84795,20 @@ class ListNodesNodeGroupsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListOrganizationSecurityPoliciesRequest(proto.Message): - r"""A request message for OrganizationSecurityPolicies.List. See - the method description for details. +class ListNodeTypesRequest(proto.Message): + r"""A request message for NodeTypes.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -84358,10 +84917,8 @@ class ListOrganizationSecurityPoliciesRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_id (str): - Parent ID for this request. - - This field is a member of `oneof`_ ``_parent_id``. + project (str): + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -84373,6 +84930,8 @@ class ListOrganizationSecurityPoliciesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -84395,20 +84954,23 @@ class ListOrganizationSecurityPoliciesRequest(proto.Message): number=19994697, optional=True, ) - parent_id: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=459714768, - optional=True, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListPacketMirroringsRequest(proto.Message): - r"""A request message for PacketMirrorings.List. See the method +class ListNodesNodeGroupsRequest(proto.Message): + r"""A request message for NodeGroups.ListNodes. See the method description for details. @@ -84495,6 +85057,9 @@ class ListPacketMirroringsRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. + node_group (str): + Name of the NodeGroup resource whose nodes + you want to list. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -84520,8 +85085,6 @@ class ListPacketMirroringsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -84533,6 +85096,8 @@ class ListPacketMirroringsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -84545,6 +85110,10 @@ class ListPacketMirroringsRequest(proto.Message): number=54715419, optional=True, ) + node_group: str = proto.Field( + proto.STRING, + number=469958146, + ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -84559,31 +85128,25 @@ class ListPacketMirroringsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListPeeringRoutesNetworksRequest(proto.Message): - r"""A request message for Networks.ListPeeringRoutes. See the - method description for details. +class ListOrganizationSecurityPoliciesRequest(proto.Message): + r"""A request message for OrganizationSecurityPolicies.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - direction (str): - The direction of the exchanged routes. - Check the Direction enum for the list of - possible values. - - This field is a member of `oneof`_ ``_direction``. filter (str): A filter expression that filters resources listed in the response. Most Compute resources support two types of filter @@ -84664,8 +85227,6 @@ class ListPeeringRoutesNetworksRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. - network (str): - Name of the network for this request. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -84689,19 +85250,10 @@ class ListPeeringRoutesNetworksRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - peering_name (str): - The response will show routes exchanged over - the given peering connection. - - This field is a member of `oneof`_ ``_peering_name``. - project (str): - Project ID for this request. - region (str): - The region of the request. The response will - include all subnet routes, static routes and - dynamic routes in the region. + parent_id (str): + Parent ID for this request. - This field is a member of `oneof`_ ``_region``. + This field is a member of `oneof`_ ``_parent_id``. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -84715,28 +85267,6 @@ class ListPeeringRoutesNetworksRequest(proto.Message): This field is a member of `oneof`_ ``_return_partial_success``. """ - class Direction(proto.Enum): - r"""The direction of the exchanged routes. - - Values: - UNDEFINED_DIRECTION (0): - A value indicating that the enum field is not - set. - INCOMING (338552870): - For routes exported from peer network. - OUTGOING (307438444): - For routes exported from local network. - """ - - UNDEFINED_DIRECTION = 0 - INCOMING = 338552870 - OUTGOING = 307438444 - - direction: str = proto.Field( - proto.STRING, - number=111150975, - optional=True, - ) filter: str = proto.Field( proto.STRING, number=336120696, @@ -84747,10 +85277,6 @@ class Direction(proto.Enum): number=54715419, optional=True, ) - network: str = proto.Field( - proto.STRING, - number=232872494, - ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -84761,18 +85287,9 @@ class Direction(proto.Enum): number=19994697, optional=True, ) - peering_name: str = proto.Field( - proto.STRING, - number=249571370, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( + parent_id: str = proto.Field( proto.STRING, - number=138946292, + number=459714768, optional=True, ) return_partial_success: bool = proto.Field( @@ -84782,9 +85299,8 @@ class Direction(proto.Enum): ) -class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): - r"""A request message for - InstanceGroupManagers.ListPerInstanceConfigs. See the method +class ListPacketMirroringsRequest(proto.Message): + r"""A request message for PacketMirrorings.List. See the method description for details. @@ -84862,9 +85378,6 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. - instance_group_manager (str): - The name of the managed instance group. It - should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -84899,6 +85412,8 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -84910,10 +85425,6 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of thezone - where the managed instance group is located. - It should conform to RFC1035. """ filter: str = proto.Field( @@ -84921,10 +85432,6 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): number=336120696, optional=True, ) - instance_group_manager: str = proto.Field( - proto.STRING, - number=249363395, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -84944,26 +85451,31 @@ class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): - r"""A request message for - RegionInstanceGroupManagers.ListPerInstanceConfigs. See the +class ListPeeringRoutesNetworksRequest(proto.Message): + r"""A request message for Networks.ListPeeringRoutes. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + direction (str): + The direction of the exchanged routes. + Check the Direction enum for the list of + possible values. + + This field is a member of `oneof`_ ``_direction``. filter (str): A filter expression that filters resources listed in the response. Most Compute resources support two types of filter @@ -85035,9 +85547,6 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. - instance_group_manager (str): - The name of the managed instance group. It - should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -85047,6 +85556,8 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): ``500``, inclusive. (Default: ``500``) This field is a member of `oneof`_ ``_max_results``. + network (str): + Name of the network for this request. order_by (str): Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource @@ -85070,11 +85581,19 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. + peering_name (str): + The response will show routes exchanged over + the given peering connection. + + This field is a member of `oneof`_ ``_peering_name``. project (str): Project ID for this request. region (str): - Name of the region scoping this request, - should conform to RFC1035. + The region of the request. The response will + include all subnet routes, static routes and + dynamic routes in the region. + + This field is a member of `oneof`_ ``_region``. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -85088,20 +85607,42 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): This field is a member of `oneof`_ ``_return_partial_success``. """ - filter: str = proto.Field( + class Direction(proto.Enum): + r"""The direction of the exchanged routes. + + Values: + UNDEFINED_DIRECTION (0): + A value indicating that the enum field is not + set. + INCOMING (338552870): + For routes exported from peer network. + OUTGOING (307438444): + For routes exported from local network. + """ + + UNDEFINED_DIRECTION = 0 + INCOMING = 338552870 + OUTGOING = 307438444 + + direction: str = proto.Field( proto.STRING, - number=336120696, + number=111150975, optional=True, ) - instance_group_manager: str = proto.Field( + filter: str = proto.Field( proto.STRING, - number=249363395, + number=336120696, + optional=True, ) max_results: int = proto.Field( proto.UINT32, number=54715419, optional=True, ) + network: str = proto.Field( + proto.STRING, + number=232872494, + ) order_by: str = proto.Field( proto.STRING, number=160562920, @@ -85112,6 +85653,11 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): number=19994697, optional=True, ) + peering_name: str = proto.Field( + proto.STRING, + number=249571370, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -85119,6 +85665,7 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): region: str = proto.Field( proto.STRING, number=138946292, + optional=True, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -85127,10 +85674,10 @@ class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): ) -class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.Message): +class ListPerInstanceConfigsInstanceGroupManagersRequest(proto.Message): r"""A request message for - OrganizationSecurityPolicies.ListPreconfiguredExpressionSets. - See the method description for details. + InstanceGroupManagers.ListPerInstanceConfigs. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -85207,6 +85754,9 @@ class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.M regular expressions. This field is a member of `oneof`_ ``_filter``. + instance_group_manager (str): + The name of the managed instance group. It + should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -85239,10 +85789,8 @@ class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.M the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_id (str): - Parent ID for this request. - - This field is a member of `oneof`_ ``_parent_id``. + project (str): + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -85254,6 +85802,10 @@ class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.M resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of thezone + where the managed instance group is located. + It should conform to RFC1035. """ filter: str = proto.Field( @@ -85261,6 +85813,10 @@ class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.M number=336120696, optional=True, ) + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -85276,22 +85832,25 @@ class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.M number=19994697, optional=True, ) - parent_id: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=459714768, - optional=True, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): +class ListPerInstanceConfigsRegionInstanceGroupManagersRequest(proto.Message): r"""A request message for - SecurityPolicies.ListPreconfiguredExpressionSets. See the method - description for details. + RegionInstanceGroupManagers.ListPerInstanceConfigs. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -85368,6 +85927,9 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. + instance_group_manager (str): + The name of the managed instance group. It + should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -85402,6 +85964,9 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request, + should conform to RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -85420,6 +85985,10 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): number=336120696, optional=True, ) + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -85439,6 +86008,10 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -85446,9 +86019,171 @@ class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): ) -class ListPreviewFeaturesRequest(proto.Message): - r"""A request message for PreviewFeatures.List. See the method - description for details. +class ListPreconfiguredExpressionSetsOrganizationSecurityPoliciesRequest(proto.Message): + r"""A request message for + OrganizationSecurityPolicies.ListPreconfiguredExpressionSets. + 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``. + 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``. + parent_id (str): + Parent ID for this request. + + This field is a member of `oneof`_ ``_parent_id``. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + parent_id: str = proto.Field( + proto.STRING, + number=459714768, + optional=True, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListPreconfiguredExpressionSetsSecurityPoliciesRequest(proto.Message): + r"""A request message for + SecurityPolicies.ListPreconfiguredExpressionSets. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -85603,9 +86338,9 @@ class ListPreviewFeaturesRequest(proto.Message): ) -class ListPublicAdvertisedPrefixesRequest(proto.Message): - r"""A request message for PublicAdvertisedPrefixes.List. See the - method description for details. +class ListPreviewFeaturesRequest(proto.Message): + r"""A request message for PreviewFeatures.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -85760,8 +86495,8 @@ class ListPublicAdvertisedPrefixesRequest(proto.Message): ) -class ListPublicDelegatedPrefixesRequest(proto.Message): - r"""A request message for PublicDelegatedPrefixes.List. See the +class ListPublicAdvertisedPrefixesRequest(proto.Message): + r"""A request message for PublicAdvertisedPrefixes.List. See the method description for details. @@ -85873,8 +86608,6 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -85912,10 +86645,6 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -85923,9 +86652,9 @@ class ListPublicDelegatedPrefixesRequest(proto.Message): ) -class ListReferrersInstancesRequest(proto.Message): - r"""A request message for Instances.ListReferrers. See the method - description for details. +class ListPublicDelegatedPrefixesRequest(proto.Message): + r"""A request message for PublicDelegatedPrefixes.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -86002,10 +86731,6 @@ class ListReferrersInstancesRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. - instance (str): - Name of the target instance scoping this - request, or '-' if the request should span over - all instances in the container. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -86040,6 +86765,8 @@ class ListReferrersInstancesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -86051,8 +86778,6 @@ class ListReferrersInstancesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -86060,10 +86785,6 @@ class ListReferrersInstancesRequest(proto.Message): number=336120696, optional=True, ) - instance: str = proto.Field( - proto.STRING, - number=18257045, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -86083,19 +86804,19 @@ class ListReferrersInstancesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListRegionAutoscalersRequest(proto.Message): - r"""A request message for RegionAutoscalers.List. See the method +class ListReferrersInstancesRequest(proto.Message): + r"""A request message for Instances.ListReferrers. See the method description for details. @@ -86173,6 +86894,10 @@ class ListRegionAutoscalersRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. + instance (str): + Name of the target instance scoping this + request, or '-' if the request should span over + all instances in the container. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -86207,8 +86932,6 @@ class ListRegionAutoscalersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -86220,6 +86943,8 @@ class ListRegionAutoscalersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -86227,6 +86952,10 @@ class ListRegionAutoscalersRequest(proto.Message): number=336120696, optional=True, ) + instance: str = proto.Field( + proto.STRING, + number=18257045, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -86246,20 +86975,20 @@ class ListRegionAutoscalersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListRegionBackendBucketsRequest(proto.Message): - r"""A request message for RegionBackendBuckets.List. See the - method description for details. +class ListRegionAutoscalersRequest(proto.Message): + r"""A request message for RegionAutoscalers.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -86371,7 +87100,7 @@ class ListRegionBackendBucketsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region of this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -86420,8 +87149,8 @@ class ListRegionBackendBucketsRequest(proto.Message): ) -class ListRegionBackendServicesRequest(proto.Message): - r"""A request message for RegionBackendServices.List. See the +class ListRegionBackendBucketsRequest(proto.Message): + r"""A request message for RegionBackendBuckets.List. See the method description for details. @@ -86534,7 +87263,7 @@ class ListRegionBackendServicesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -86583,9 +87312,9 @@ class ListRegionBackendServicesRequest(proto.Message): ) -class ListRegionCommitmentsRequest(proto.Message): - r"""A request message for RegionCommitments.List. See the method - description for details. +class ListRegionBackendServicesRequest(proto.Message): + r"""A request message for RegionBackendServices.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -86697,7 +87426,7 @@ class ListRegionCommitmentsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -86746,9 +87475,9 @@ class ListRegionCommitmentsRequest(proto.Message): ) -class ListRegionCompositeHealthChecksRequest(proto.Message): - r"""A request message for RegionCompositeHealthChecks.List. See - the method description for details. +class ListRegionCommitmentsRequest(proto.Message): + r"""A request message for RegionCommitments.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -86860,7 +87589,7 @@ class ListRegionCompositeHealthChecksRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -86909,9 +87638,9 @@ class ListRegionCompositeHealthChecksRequest(proto.Message): ) -class ListRegionDiskTypesRequest(proto.Message): - r"""A request message for RegionDiskTypes.List. See the method - description for details. +class ListRegionCompositeHealthChecksRequest(proto.Message): + r"""A request message for RegionCompositeHealthChecks.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -87023,7 +87752,7 @@ class ListRegionDiskTypesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -87072,8 +87801,8 @@ class ListRegionDiskTypesRequest(proto.Message): ) -class ListRegionDisksRequest(proto.Message): - r"""A request message for RegionDisks.List. See the method +class ListRegionDiskTypesRequest(proto.Message): + r"""A request message for RegionDiskTypes.List. See the method description for details. @@ -87186,170 +87915,7 @@ class ListRegionDisksRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. - - This field is a member of `oneof`_ ``_return_partial_success``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - - -class ListRegionHealthAggregationPoliciesRequest(proto.Message): - r"""A request message for RegionHealthAggregationPolicies.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``. - 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 scoping this request. + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -87398,9 +87964,9 @@ class ListRegionHealthAggregationPoliciesRequest(proto.Message): ) -class ListRegionHealthCheckServicesRequest(proto.Message): - r"""A request message for RegionHealthCheckServices.List. See the - method description for details. +class ListRegionDisksRequest(proto.Message): + r"""A request message for RegionDisks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -87512,7 +88078,7 @@ class ListRegionHealthCheckServicesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -87561,9 +88127,9 @@ class ListRegionHealthCheckServicesRequest(proto.Message): ) -class ListRegionHealthChecksRequest(proto.Message): - r"""A request message for RegionHealthChecks.List. See the method - description for details. +class ListRegionHealthAggregationPoliciesRequest(proto.Message): + r"""A request message for RegionHealthAggregationPolicies.List. + See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -87724,8 +88290,8 @@ class ListRegionHealthChecksRequest(proto.Message): ) -class ListRegionHealthSourcesRequest(proto.Message): - r"""A request message for RegionHealthSources.List. See the +class ListRegionHealthCheckServicesRequest(proto.Message): + r"""A request message for RegionHealthCheckServices.List. See the method description for details. @@ -87887,9 +88453,8 @@ class ListRegionHealthSourcesRequest(proto.Message): ) -class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): - r"""A request message for - RegionInstanceGroupManagerResizeRequests.List. See the method +class ListRegionHealthChecksRequest(proto.Message): + r"""A request message for RegionHealthChecks.List. See the method description for details. @@ -87967,9 +88532,6 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. - instance_group_manager (str): - The name of the managed instance group. The - name should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -88005,9 +88567,7 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region - scoping this request. Name should conform to - RFC1035. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88026,10 +88586,6 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): number=336120696, optional=True, ) - instance_group_manager: str = proto.Field( - proto.STRING, - number=249363395, - ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -88060,9 +88616,9 @@ class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): ) -class ListRegionInstanceGroupManagersRequest(proto.Message): - r"""A request message for RegionInstanceGroupManagers.List. See - the method description for details. +class ListRegionHealthSourcesRequest(proto.Message): + r"""A request message for RegionHealthSources.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -88223,9 +88779,10 @@ class ListRegionInstanceGroupManagersRequest(proto.Message): ) -class ListRegionInstanceGroupsRequest(proto.Message): - r"""A request message for RegionInstanceGroups.List. See the - method description for details. +class ListRegionInstanceGroupManagerResizeRequestsRequest(proto.Message): + r"""A request message for + RegionInstanceGroupManagerResizeRequests.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -88302,6 +88859,9 @@ class ListRegionInstanceGroupsRequest(proto.Message): regular expressions. This field is a member of `oneof`_ ``_filter``. + instance_group_manager (str): + The name of the managed instance group. The + name should conform to RFC1035. max_results (int): The maximum number of results per page that should be returned. If the number of available results is larger than @@ -88337,7 +88897,9 @@ class ListRegionInstanceGroupsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region + scoping this request. Name should conform to + RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88356,6 +88918,10 @@ class ListRegionInstanceGroupsRequest(proto.Message): number=336120696, optional=True, ) + instance_group_manager: str = proto.Field( + proto.STRING, + number=249363395, + ) max_results: int = proto.Field( proto.UINT32, number=54715419, @@ -88386,9 +88952,9 @@ class ListRegionInstanceGroupsRequest(proto.Message): ) -class ListRegionInstanceTemplatesRequest(proto.Message): - r"""A request message for RegionInstanceTemplates.List. See the - method description for details. +class ListRegionInstanceGroupManagersRequest(proto.Message): + r"""A request message for RegionInstanceGroupManagers.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -88500,7 +89066,7 @@ class ListRegionInstanceTemplatesRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the regions for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88549,9 +89115,9 @@ class ListRegionInstanceTemplatesRequest(proto.Message): ) -class ListRegionInstantSnapshotGroupsRequest(proto.Message): - r"""A request message for RegionInstantSnapshotGroups.List. See - the method description for details. +class ListRegionInstanceGroupsRequest(proto.Message): + r"""A request message for RegionInstanceGroups.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -88663,7 +89229,7 @@ class ListRegionInstantSnapshotGroupsRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88712,8 +89278,8 @@ class ListRegionInstantSnapshotGroupsRequest(proto.Message): ) -class ListRegionInstantSnapshotsRequest(proto.Message): - r"""A request message for RegionInstantSnapshots.List. See the +class ListRegionInstanceTemplatesRequest(proto.Message): + r"""A request message for RegionInstanceTemplates.List. See the method description for details. @@ -88826,7 +89392,7 @@ class ListRegionInstantSnapshotsRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of the region for this request. + The name of the regions for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -88875,8 +89441,8 @@ class ListRegionInstantSnapshotsRequest(proto.Message): ) -class ListRegionNetworkEndpointGroupsRequest(proto.Message): - r"""A request message for RegionNetworkEndpointGroups.List. See +class ListRegionInstantSnapshotGroupsRequest(proto.Message): + r"""A request message for RegionInstantSnapshotGroups.List. See the method description for details. @@ -88989,9 +89555,7 @@ class ListRegionNetworkEndpointGroupsRequest(proto.Message): project (str): Project ID for this request. region (str): - The name of theregion - where the network endpoint group is located. It - should comply with RFC1035. + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -89040,9 +89604,9 @@ class ListRegionNetworkEndpointGroupsRequest(proto.Message): ) -class ListRegionNetworkFirewallPoliciesRequest(proto.Message): - r"""A request message for RegionNetworkFirewallPolicies.List. See - the method description for details. +class ListRegionInstantSnapshotsRequest(proto.Message): + r"""A request message for RegionInstantSnapshots.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -89154,7 +89718,7 @@ class ListRegionNetworkFirewallPoliciesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -89203,8 +89767,8 @@ class ListRegionNetworkFirewallPoliciesRequest(proto.Message): ) -class ListRegionNotificationEndpointsRequest(proto.Message): - r"""A request message for RegionNotificationEndpoints.List. See +class ListRegionNetworkEndpointGroupsRequest(proto.Message): + r"""A request message for RegionNetworkEndpointGroups.List. See the method description for details. @@ -89317,7 +89881,9 @@ class ListRegionNotificationEndpointsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + The name of theregion + where the network endpoint group is located. It + should comply with RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -89366,9 +89932,9 @@ class ListRegionNotificationEndpointsRequest(proto.Message): ) -class ListRegionOperationsRequest(proto.Message): - r"""A request message for RegionOperations.List. See the method - description for details. +class ListRegionNetworkFirewallPoliciesRequest(proto.Message): + r"""A request message for RegionNetworkFirewallPolicies.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -89480,7 +90046,7 @@ class ListRegionOperationsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -89529,9 +90095,9 @@ class ListRegionOperationsRequest(proto.Message): ) -class ListRegionSecurityPoliciesRequest(proto.Message): - r"""A request message for RegionSecurityPolicies.List. See the - method description for details. +class ListRegionNotificationEndpointsRequest(proto.Message): + r"""A request message for RegionNotificationEndpoints.List. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -89692,8 +90258,8 @@ class ListRegionSecurityPoliciesRequest(proto.Message): ) -class ListRegionSnapshotsRequest(proto.Message): - r"""A request message for RegionSnapshots.List. See the method +class ListRegionOperationsRequest(proto.Message): + r"""A request message for RegionOperations.List. See the method description for details. @@ -89855,8 +90421,8 @@ class ListRegionSnapshotsRequest(proto.Message): ) -class ListRegionSslCertificatesRequest(proto.Message): - r"""A request message for RegionSslCertificates.List. See the +class ListRegionSecurityPoliciesRequest(proto.Message): + r"""A request message for RegionSecurityPolicies.List. See the method description for details. @@ -90018,8 +90584,8 @@ class ListRegionSslCertificatesRequest(proto.Message): ) -class ListRegionSslPoliciesRequest(proto.Message): - r"""A request message for RegionSslPolicies.List. See the method +class ListRegionSnapshotsRequest(proto.Message): + r"""A request message for RegionSnapshots.List. See the method description for details. @@ -90132,7 +90698,7 @@ class ListRegionSslPoliciesRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region scoping this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -90181,8 +90747,8 @@ class ListRegionSslPoliciesRequest(proto.Message): ) -class ListRegionTargetHttpProxiesRequest(proto.Message): - r"""A request message for RegionTargetHttpProxies.List. See the +class ListRegionSslCertificatesRequest(proto.Message): + r"""A request message for RegionSslCertificates.List. See the method description for details. @@ -90344,9 +90910,9 @@ class ListRegionTargetHttpProxiesRequest(proto.Message): ) -class ListRegionTargetHttpsProxiesRequest(proto.Message): - r"""A request message for RegionTargetHttpsProxies.List. See the - method description for details. +class ListRegionSslPoliciesRequest(proto.Message): + r"""A request message for RegionSslPolicies.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -90507,8 +91073,8 @@ class ListRegionTargetHttpsProxiesRequest(proto.Message): ) -class ListRegionTargetTcpProxiesRequest(proto.Message): - r"""A request message for RegionTargetTcpProxies.List. See the +class ListRegionTargetHttpProxiesRequest(proto.Message): + r"""A request message for RegionTargetHttpProxies.List. See the method description for details. @@ -90670,9 +91236,9 @@ class ListRegionTargetTcpProxiesRequest(proto.Message): ) -class ListRegionUrlMapsRequest(proto.Message): - r"""A request message for RegionUrlMaps.List. See the method - description for details. +class ListRegionTargetHttpsProxiesRequest(proto.Message): + r"""A request message for RegionTargetHttpsProxies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -90833,9 +91399,9 @@ class ListRegionUrlMapsRequest(proto.Message): ) -class ListRegionZonesRequest(proto.Message): - r"""A request message for RegionZones.List. See the method - description for details. +class ListRegionTargetTcpProxiesRequest(proto.Message): + r"""A request message for RegionTargetTcpProxies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -90947,7 +91513,7 @@ class ListRegionZonesRequest(proto.Message): project (str): Project ID for this request. region (str): - Region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -90996,8 +91562,8 @@ class ListRegionZonesRequest(proto.Message): ) -class ListRegionsRequest(proto.Message): - r"""A request message for Regions.List. See the method +class ListRegionUrlMapsRequest(proto.Message): + r"""A request message for RegionUrlMaps.List. See the method description for details. @@ -91109,6 +91675,8 @@ class ListRegionsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91146,6 +91714,10 @@ class ListRegionsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -91153,8 +91725,8 @@ class ListRegionsRequest(proto.Message): ) -class ListReservationBlocksRequest(proto.Message): - r"""A request message for ReservationBlocks.List. See the method +class ListRegionZonesRequest(proto.Message): + r"""A request message for RegionZones.List. See the method description for details. @@ -91266,10 +91838,8 @@ class ListReservationBlocksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - reservation (str): - The name of the reservation. - Name should conform to RFC1035 or be a resource - ID. + region (str): + Region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91281,9 +91851,6 @@ class ListReservationBlocksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. """ filter: str = proto.Field( @@ -91310,23 +91877,19 @@ class ListReservationBlocksRequest(proto.Message): proto.STRING, number=227560217, ) - reservation: str = proto.Field( + region: str = proto.Field( proto.STRING, - number=47530956, + number=138946292, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListReservationSlotsRequest(proto.Message): - r"""A request message for ReservationSlots.List. See the method +class ListRegionsRequest(proto.Message): + r"""A request message for Regions.List. See the method description for details. @@ -91436,12 +91999,8 @@ class ListReservationSlotsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_name (str): - The name of the parent reservation and parent block, - formatted as - reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} project (str): - The project ID for this request. + Project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91453,9 +92012,6 @@ class ListReservationSlotsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request, - formatted as RFC1035. """ filter: str = proto.Field( @@ -91478,10 +92034,6 @@ class ListReservationSlotsRequest(proto.Message): number=19994697, optional=True, ) - parent_name: str = proto.Field( - proto.STRING, - number=478151936, - ) project: str = proto.Field( proto.STRING, number=227560217, @@ -91491,15 +92043,11 @@ class ListReservationSlotsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListReservationSubBlocksRequest(proto.Message): - r"""A request message for ReservationSubBlocks.List. See the - method description for details. +class ListReservationBlocksRequest(proto.Message): + r"""A request message for ReservationBlocks.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -91608,12 +92156,12 @@ class ListReservationSubBlocksRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. - parent_name (str): - The name of the parent reservation and parent block. In the - format of - reservations/{reservation_name}/reservationBlocks/{reservation_block_name} project (str): Project ID for this request. + reservation (str): + The name of the reservation. + Name should conform to RFC1035 or be a resource + ID. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91650,14 +92198,14 @@ class ListReservationSubBlocksRequest(proto.Message): number=19994697, optional=True, ) - parent_name: str = proto.Field( - proto.STRING, - number=478151936, - ) project: str = proto.Field( proto.STRING, number=227560217, ) + reservation: str = proto.Field( + proto.STRING, + number=47530956, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -91669,8 +92217,8 @@ class ListReservationSubBlocksRequest(proto.Message): ) -class ListReservationsRequest(proto.Message): - r"""A request message for Reservations.List. See the method +class ListReservationSlotsRequest(proto.Message): + r"""A request message for ReservationSlots.List. See the method description for details. @@ -91780,8 +92328,12 @@ class ListReservationsRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. + parent_name (str): + The name of the parent reservation and parent block, + formatted as + reservations/{reservation_name}/reservationBlocks/{reservation_block_name}/reservationSubBlocks/{reservation_sub_block_name} project (str): - Project ID for this request. + The project ID for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91794,7 +92346,8 @@ class ListReservationsRequest(proto.Message): This field is a member of `oneof`_ ``_return_partial_success``. zone (str): - Name of the zone for this request. + The name of the zone for this request, + formatted as RFC1035. """ filter: str = proto.Field( @@ -91817,6 +92370,10 @@ class ListReservationsRequest(proto.Message): number=19994697, optional=True, ) + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -91832,9 +92389,9 @@ class ListReservationsRequest(proto.Message): ) -class ListResourcePoliciesRequest(proto.Message): - r"""A request message for ResourcePolicies.List. See the method - description for details. +class ListReservationSubBlocksRequest(proto.Message): + r"""A request message for ReservationSubBlocks.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -91943,10 +92500,12 @@ class ListResourcePoliciesRequest(proto.Message): the next page of results. This field is a member of `oneof`_ ``_page_token``. + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -91958,6 +92517,9 @@ class ListResourcePoliciesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. """ filter: str = proto.Field( @@ -91980,23 +92542,27 @@ class ListResourcePoliciesRequest(proto.Message): number=19994697, optional=True, ) - project: str = proto.Field( + parent_name: str = proto.Field( proto.STRING, - number=227560217, + number=478151936, ) - region: str = proto.Field( + project: str = proto.Field( proto.STRING, - number=138946292, + number=227560217, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListRolloutPlansRequest(proto.Message): - r"""A request message for RolloutPlans.List. See the method +class ListReservationsRequest(proto.Message): + r"""A request message for Reservations.List. See the method description for details. @@ -92119,6 +92685,8 @@ class ListRolloutPlansRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for this request. """ filter: str = proto.Field( @@ -92150,10 +92718,14 @@ class ListRolloutPlansRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListRolloutsRequest(proto.Message): - r"""A request message for Rollouts.List. See the method +class ListResourcePoliciesRequest(proto.Message): + r"""A request message for ResourcePolicies.List. See the method description for details. @@ -92265,6 +92837,8 @@ class ListRolloutsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92302,6 +92876,10 @@ class ListRolloutsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -92309,9 +92887,9 @@ class ListRolloutsRequest(proto.Message): ) -class ListRoutePoliciesRoutersRequest(proto.Message): - r"""A request message for Routers.ListRoutePolicies. See the - method description for details. +class ListRolloutPlansRequest(proto.Message): + r"""A request message for RolloutPlans.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -92422,8 +93000,6 @@ class ListRoutePoliciesRoutersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92435,9 +93011,6 @@ class ListRoutePoliciesRoutersRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - router (str): - Name or id of the resource for this request. - Name should conform to RFC1035. """ filter: str = proto.Field( @@ -92464,23 +93037,15 @@ class ListRoutePoliciesRoutersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - router: str = proto.Field( - proto.STRING, - number=148608841, - ) -class ListRoutersRequest(proto.Message): - r"""A request message for Routers.List. See the method +class ListRolloutsRequest(proto.Message): + r"""A request message for Rollouts.List. See the method description for details. @@ -92592,8 +93157,6 @@ class ListRoutersRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92631,10 +93194,6 @@ class ListRoutersRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -92642,9 +93201,9 @@ class ListRoutersRequest(proto.Message): ) -class ListRoutesRequest(proto.Message): - r"""A request message for Routes.List. See the method description - for details. +class ListRoutePoliciesRoutersRequest(proto.Message): + r"""A request message for Routers.ListRoutePolicies. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -92755,6 +93314,8 @@ class ListRoutesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -92766,6 +93327,9 @@ class ListRoutesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + router (str): + Name or id of the resource for this request. + Name should conform to RFC1035. """ filter: str = proto.Field( @@ -92792,172 +93356,23 @@ class ListRoutesRequest(proto.Message): proto.STRING, number=227560217, ) - return_partial_success: bool = proto.Field( - proto.BOOL, - number=517198390, - optional=True, - ) - - -class ListSecurityPoliciesRequest(proto.Message): - r"""A request message for SecurityPolicies.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``. - order_by (str): - Sorts list results by a certain order. By default, results - are returned in alphanumerical order based on the resource - name. - - You can also sort results in descending order based on the - creation timestamp using - ``orderBy="creationTimestamp desc"``. This sorts results - based on the ``creationTimestamp`` field in reverse - chronological order (newest result first). Use this to sort - resources like operations so that the newest operation is - returned first. - - Currently, only sorting by ``name`` or - ``creationTimestamp desc`` is supported. - - This field is a member of `oneof`_ ``_order_by``. - page_token (str): - Specifies a page token to use. Set ``pageToken`` to the - ``nextPageToken`` returned by a previous list request to get - the next page of results. - - This field is a member of `oneof`_ ``_page_token``. - project (str): - Project ID for this request. - return_partial_success (bool): - Opt-in for partial success behavior which - provides partial results in case of failure. The - default value is false. - - For example, when partial success behavior is - enabled, aggregatedList for a single zone scope - either returns all resources in the zone or no - resources, with an error code. - - This field is a member of `oneof`_ ``_return_partial_success``. - """ - - filter: str = proto.Field( - proto.STRING, - number=336120696, - optional=True, - ) - max_results: int = proto.Field( - proto.UINT32, - number=54715419, - optional=True, - ) - order_by: str = proto.Field( - proto.STRING, - number=160562920, - optional=True, - ) - page_token: str = proto.Field( - proto.STRING, - number=19994697, - optional=True, - ) - project: str = proto.Field( + region: str = proto.Field( proto.STRING, - number=227560217, + number=138946292, ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) -class ListServiceAttachmentsRequest(proto.Message): - r"""A request message for ServiceAttachments.List. See the method +class ListRoutersRequest(proto.Message): + r"""A request message for Routers.List. See the method description for details. @@ -93070,7 +93485,7 @@ class ListServiceAttachmentsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region of this request. + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -93119,9 +93534,9 @@ class ListServiceAttachmentsRequest(proto.Message): ) -class ListSnapshotsRequest(proto.Message): - r"""A request message for Snapshots.List. See the method - description for details. +class ListRoutesRequest(proto.Message): + r"""A request message for Routes.List. See the method description + for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -93276,8 +93691,8 @@ class ListSnapshotsRequest(proto.Message): ) -class ListSslCertificatesRequest(proto.Message): - r"""A request message for SslCertificates.List. See the method +class ListSecurityPoliciesRequest(proto.Message): + r"""A request message for SecurityPolicies.List. See the method description for details. @@ -93433,8 +93848,8 @@ class ListSslCertificatesRequest(proto.Message): ) -class ListSslPoliciesRequest(proto.Message): - r"""A request message for SslPolicies.List. See the method +class ListServiceAttachmentsRequest(proto.Message): + r"""A request message for ServiceAttachments.List. See the method description for details. @@ -93546,6 +93961,8 @@ class ListSslPoliciesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region of this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -93583,6 +94000,10 @@ class ListSslPoliciesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -93590,8 +94011,8 @@ class ListSslPoliciesRequest(proto.Message): ) -class ListStoragePoolTypesRequest(proto.Message): - r"""A request message for StoragePoolTypes.List. See the method +class ListSnapshotsRequest(proto.Message): + r"""A request message for Snapshots.List. See the method description for details. @@ -93714,8 +94135,6 @@ class ListStoragePoolTypesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -93747,14 +94166,10 @@ class ListStoragePoolTypesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListStoragePoolsRequest(proto.Message): - r"""A request message for StoragePools.List. See the method +class ListSslCertificatesRequest(proto.Message): + r"""A request message for SslCertificates.List. See the method description for details. @@ -93877,8 +94292,6 @@ class ListStoragePoolsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - The name of the zone for this request. """ filter: str = proto.Field( @@ -93910,14 +94323,10 @@ class ListStoragePoolsRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.List. See the method +class ListSslPoliciesRequest(proto.Message): + r"""A request message for SslPolicies.List. See the method description for details. @@ -94029,8 +94438,6 @@ class ListSubnetworksRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -94042,43 +94449,8 @@ class ListSubnetworksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - views (str): - Defines the extra views returned back in the subnetwork - resource. Supported values: - - :: - - - WITH_UTILIZATION: Utilization data is included in the - response. - - Check the Views enum for the list of possible values. - - This field is a member of `oneof`_ ``_views``. """ - class Views(proto.Enum): - r"""Defines the extra views returned back in the subnetwork resource. - Supported values: - - :: - - - WITH_UTILIZATION: Utilization data is included in the - response. - - Values: - UNDEFINED_VIEWS (0): - A value indicating that the enum field is not - set. - DEFAULT (115302945): - No description available. - WITH_UTILIZATION (504090633): - Utilization data is included in the response. - """ - - UNDEFINED_VIEWS = 0 - DEFAULT = 115302945 - WITH_UTILIZATION = 504090633 - filter: str = proto.Field( proto.STRING, number=336120696, @@ -94103,24 +94475,15 @@ class Views(proto.Enum): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - views: str = proto.Field( - proto.STRING, - number=112204398, - optional=True, - ) -class ListTargetGrpcProxiesRequest(proto.Message): - r"""A request message for TargetGrpcProxies.List. See the method +class ListStoragePoolTypesRequest(proto.Message): + r"""A request message for StoragePoolTypes.List. See the method description for details. @@ -94243,6 +94606,8 @@ class ListTargetGrpcProxiesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -94274,10 +94639,14 @@ class ListTargetGrpcProxiesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetHttpProxiesRequest(proto.Message): - r"""A request message for TargetHttpProxies.List. See the method +class ListStoragePoolsRequest(proto.Message): + r"""A request message for StoragePools.List. See the method description for details. @@ -94400,6 +94769,8 @@ class ListTargetHttpProxiesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + The name of the zone for this request. """ filter: str = proto.Field( @@ -94431,10 +94802,14 @@ class ListTargetHttpProxiesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetHttpsProxiesRequest(proto.Message): - r"""A request message for TargetHttpsProxies.List. See the method +class ListSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.List. See the method description for details. @@ -94546,6 +94921,8 @@ class ListTargetHttpsProxiesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -94557,8 +94934,43 @@ class ListTargetHttpsProxiesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + views (str): + Defines the extra views returned back in the subnetwork + resource. Supported values: + + :: + + - WITH_UTILIZATION: Utilization data is included in the + response. + + Check the Views enum for the list of possible values. + + This field is a member of `oneof`_ ``_views``. """ + class Views(proto.Enum): + r"""Defines the extra views returned back in the subnetwork resource. + Supported values: + + :: + + - WITH_UTILIZATION: Utilization data is included in the + response. + + Values: + UNDEFINED_VIEWS (0): + A value indicating that the enum field is not + set. + DEFAULT (115302945): + No description available. + WITH_UTILIZATION (504090633): + Utilization data is included in the response. + """ + + UNDEFINED_VIEWS = 0 + DEFAULT = 115302945 + WITH_UTILIZATION = 504090633 + filter: str = proto.Field( proto.STRING, number=336120696, @@ -94583,15 +94995,24 @@ class ListTargetHttpsProxiesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) + views: str = proto.Field( + proto.STRING, + number=112204398, + optional=True, + ) -class ListTargetInstancesRequest(proto.Message): - r"""A request message for TargetInstances.List. See the method +class ListTargetGrpcProxiesRequest(proto.Message): + r"""A request message for TargetGrpcProxies.List. See the method description for details. @@ -94714,8 +95135,6 @@ class ListTargetInstancesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone scoping this request. """ filter: str = proto.Field( @@ -94747,14 +95166,10 @@ class ListTargetInstancesRequest(proto.Message): number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListTargetPoolsRequest(proto.Message): - r"""A request message for TargetPools.List. See the method +class ListTargetHttpProxiesRequest(proto.Message): + r"""A request message for TargetHttpProxies.List. See the method description for details. @@ -94866,8 +95281,6 @@ class ListTargetPoolsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -94905,10 +95318,6 @@ class ListTargetPoolsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -94916,8 +95325,8 @@ class ListTargetPoolsRequest(proto.Message): ) -class ListTargetSslProxiesRequest(proto.Message): - r"""A request message for TargetSslProxies.List. See the method +class ListTargetHttpsProxiesRequest(proto.Message): + r"""A request message for TargetHttpsProxies.List. See the method description for details. @@ -95073,8 +95482,8 @@ class ListTargetSslProxiesRequest(proto.Message): ) -class ListTargetTcpProxiesRequest(proto.Message): - r"""A request message for TargetTcpProxies.List. See the method +class ListTargetInstancesRequest(proto.Message): + r"""A request message for TargetInstances.List. See the method description for details. @@ -95197,6 +95606,8 @@ class ListTargetTcpProxiesRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone scoping this request. """ filter: str = proto.Field( @@ -95228,10 +95639,14 @@ class ListTargetTcpProxiesRequest(proto.Message): number=517198390, optional=True, ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) -class ListTargetVpnGatewaysRequest(proto.Message): - r"""A request message for TargetVpnGateways.List. See the method +class ListTargetPoolsRequest(proto.Message): + r"""A request message for TargetPools.List. See the method description for details. @@ -95344,7 +95759,7 @@ class ListTargetVpnGatewaysRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -95393,8 +95808,8 @@ class ListTargetVpnGatewaysRequest(proto.Message): ) -class ListUrlMapsRequest(proto.Message): - r"""A request message for UrlMaps.List. See the method +class ListTargetSslProxiesRequest(proto.Message): + r"""A request message for TargetSslProxies.List. See the method description for details. @@ -95550,9 +95965,9 @@ class ListUrlMapsRequest(proto.Message): ) -class ListUsableBackendBucketsRequest(proto.Message): - r"""A request message for BackendBuckets.ListUsable. See the - method description for details. +class ListTargetTcpProxiesRequest(proto.Message): + r"""A request message for TargetTcpProxies.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -95707,9 +96122,9 @@ class ListUsableBackendBucketsRequest(proto.Message): ) -class ListUsableBackendServicesRequest(proto.Message): - r"""A request message for BackendServices.ListUsable. See the - method description for details. +class ListTargetVpnGatewaysRequest(proto.Message): + r"""A request message for TargetVpnGateways.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -95820,6 +96235,8 @@ class ListUsableBackendServicesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -95857,6 +96274,10 @@ class ListUsableBackendServicesRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -95864,9 +96285,9 @@ class ListUsableBackendServicesRequest(proto.Message): ) -class ListUsableRegionBackendBucketsRequest(proto.Message): - r"""A request message for RegionBackendBuckets.ListUsable. See - the method description for details. +class ListUrlMapsRequest(proto.Message): + r"""A request message for UrlMaps.List. See the method + description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -95977,10 +96398,6 @@ class ListUsableRegionBackendBucketsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. - It must be a string that meets the requirements - in RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -96018,10 +96435,6 @@ class ListUsableRegionBackendBucketsRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -96029,9 +96442,9 @@ class ListUsableRegionBackendBucketsRequest(proto.Message): ) -class ListUsableRegionBackendServicesRequest(proto.Message): - r"""A request message for RegionBackendServices.ListUsable. See - the method description for details. +class ListUsableBackendBucketsRequest(proto.Message): + r"""A request message for BackendBuckets.ListUsable. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -96142,10 +96555,6 @@ class ListUsableRegionBackendServicesRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - region (str): - Name of the region scoping this request. - It must be a string that meets the requirements - in RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -96183,10 +96592,6 @@ class ListUsableRegionBackendServicesRequest(proto.Message): proto.STRING, number=227560217, ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, @@ -96194,9 +96599,9 @@ class ListUsableRegionBackendServicesRequest(proto.Message): ) -class ListUsableSubnetworksRequest(proto.Message): - r"""A request message for Subnetworks.ListUsable. See the method - description for details. +class ListUsableBackendServicesRequest(proto.Message): + r"""A request message for BackendServices.ListUsable. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -96318,13 +96723,6 @@ class ListUsableSubnetworksRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - service_project (str): - The project id or project number in which the subnetwork is - intended to be used. Only applied for Shared VPC. See - `Shared VPC - documentation `__ - - This field is a member of `oneof`_ ``_service_project``. """ filter: str = proto.Field( @@ -96356,16 +96754,11 @@ class ListUsableSubnetworksRequest(proto.Message): number=517198390, optional=True, ) - service_project: str = proto.Field( - proto.STRING, - number=530592655, - optional=True, - ) -class ListVpnGatewaysRequest(proto.Message): - r"""A request message for VpnGateways.List. See the method - description for details. +class ListUsableRegionBackendBucketsRequest(proto.Message): + r"""A request message for RegionBackendBuckets.ListUsable. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -96477,7 +96870,9 @@ class ListVpnGatewaysRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. + It must be a string that meets the requirements + in RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -96526,9 +96921,9 @@ class ListVpnGatewaysRequest(proto.Message): ) -class ListVpnTunnelsRequest(proto.Message): - r"""A request message for VpnTunnels.List. See the method - description for details. +class ListUsableRegionBackendServicesRequest(proto.Message): + r"""A request message for RegionBackendServices.ListUsable. See + the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -96640,7 +97035,9 @@ class ListVpnTunnelsRequest(proto.Message): project (str): Project ID for this request. region (str): - Name of the region for this request. + Name of the region scoping this request. + It must be a string that meets the requirements + in RFC1035. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -96689,16 +97086,14 @@ class ListVpnTunnelsRequest(proto.Message): ) -class ListWireGroupsRequest(proto.Message): - r"""A request message for WireGroups.List. See the method +class ListUsableSubnetworksRequest(proto.Message): + r"""A request message for Subnetworks.ListUsable. See the method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - cross_site_network (str): - filter (str): A filter expression that filters resources listed in the response. Most Compute resources support two types of filter @@ -96815,12 +97210,15 @@ class ListWireGroupsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. + service_project (str): + The project id or project number in which the subnetwork is + intended to be used. Only applied for Shared VPC. See + `Shared VPC + documentation `__ + + This field is a member of `oneof`_ ``_service_project``. """ - cross_site_network: str = proto.Field( - proto.STRING, - number=108192469, - ) filter: str = proto.Field( proto.STRING, number=336120696, @@ -96850,10 +97248,15 @@ class ListWireGroupsRequest(proto.Message): number=517198390, optional=True, ) + service_project: str = proto.Field( + proto.STRING, + number=530592655, + optional=True, + ) -class ListXpnHostsProjectsRequest(proto.Message): - r"""A request message for Projects.ListXpnHosts. See the method +class ListVpnGatewaysRequest(proto.Message): + r"""A request message for VpnGateways.List. See the method description for details. @@ -96965,8 +97368,8 @@ class ListXpnHostsProjectsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. - projects_list_xpn_hosts_request_resource (google.cloud.compute_v1.types.ProjectsListXpnHostsRequest): - The body resource for this request + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -97004,12 +97407,9 @@ class ListXpnHostsProjectsRequest(proto.Message): proto.STRING, number=227560217, ) - projects_list_xpn_hosts_request_resource: "ProjectsListXpnHostsRequest" = ( - proto.Field( - proto.MESSAGE, - number=238266391, - message="ProjectsListXpnHostsRequest", - ) + region: str = proto.Field( + proto.STRING, + number=138946292, ) return_partial_success: bool = proto.Field( proto.BOOL, @@ -97018,8 +97418,8 @@ class ListXpnHostsProjectsRequest(proto.Message): ) -class ListZoneOperationsRequest(proto.Message): - r"""A request message for ZoneOperations.List. See the method +class ListVpnTunnelsRequest(proto.Message): + r"""A request message for VpnTunnels.List. See the method description for details. @@ -97131,6 +97531,8 @@ class ListZoneOperationsRequest(proto.Message): This field is a member of `oneof`_ ``_page_token``. project (str): Project ID for this request. + region (str): + Name of the region for this request. return_partial_success (bool): Opt-in for partial success behavior which provides partial results in case of failure. The @@ -97142,8 +97544,6 @@ class ListZoneOperationsRequest(proto.Message): resources, with an error code. This field is a member of `oneof`_ ``_return_partial_success``. - zone (str): - Name of the zone for request. """ filter: str = proto.Field( @@ -97170,20 +97570,512 @@ class ListZoneOperationsRequest(proto.Message): proto.STRING, number=227560217, ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) return_partial_success: bool = proto.Field( proto.BOOL, number=517198390, optional=True, ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) -class ListZoneVmExtensionPoliciesRequest(proto.Message): - r"""A request message for ZoneVmExtensionPolicies.List. See the - method description for details. +class ListWireGroupsRequest(proto.Message): + r"""A request message for WireGroups.List. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + cross_site_network (str): + + 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``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + cross_site_network: str = proto.Field( + proto.STRING, + number=108192469, + ) + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListXpnHostsProjectsRequest(proto.Message): + r"""A request message for Projects.ListXpnHosts. 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``. + 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. + projects_list_xpn_hosts_request_resource (google.cloud.compute_v1.types.ProjectsListXpnHostsRequest): + The body resource for this request + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + projects_list_xpn_hosts_request_resource: "ProjectsListXpnHostsRequest" = ( + proto.Field( + proto.MESSAGE, + number=238266391, + message="ProjectsListXpnHostsRequest", + ) + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + + +class ListZoneOperationsRequest(proto.Message): + r"""A request message for ZoneOperations.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``. + order_by (str): + Sorts list results by a certain order. By default, results + are returned in alphanumerical order based on the resource + name. + + You can also sort results in descending order based on the + creation timestamp using + ``orderBy="creationTimestamp desc"``. This sorts results + based on the ``creationTimestamp`` field in reverse + chronological order (newest result first). Use this to sort + resources like operations so that the newest operation is + returned first. + + Currently, only sorting by ``name`` or + ``creationTimestamp desc`` is supported. + + This field is a member of `oneof`_ ``_order_by``. + page_token (str): + Specifies a page token to use. Set ``pageToken`` to the + ``nextPageToken`` returned by a previous list request to get + the next page of results. + + This field is a member of `oneof`_ ``_page_token``. + project (str): + Project ID for this request. + return_partial_success (bool): + Opt-in for partial success behavior which + provides partial results in case of failure. The + default value is false. + + For example, when partial success behavior is + enabled, aggregatedList for a single zone scope + either returns all resources in the zone or no + resources, with an error code. + + This field is a member of `oneof`_ ``_return_partial_success``. + zone (str): + Name of the zone for request. + """ + + filter: str = proto.Field( + proto.STRING, + number=336120696, + optional=True, + ) + max_results: int = proto.Field( + proto.UINT32, + number=54715419, + optional=True, + ) + order_by: str = proto.Field( + proto.STRING, + number=160562920, + optional=True, + ) + page_token: str = proto.Field( + proto.STRING, + number=19994697, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + return_partial_success: bool = proto.Field( + proto.BOOL, + number=517198390, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class ListZoneVmExtensionPoliciesRequest(proto.Message): + r"""A request message for ZoneVmExtensionPolicies.List. See the + method description for details. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -98630,6 +99522,18 @@ class ManagedInstance(proto.Message): this instance resulting from InstanceFlexibilityPolicy. This field is a member of `oneof`_ ``_properties_from_flexibility_policy``. + scheduling (google.cloud.compute_v1.types.ManagedInstanceScheduling): + Output only. Information about the + termination timestamp of the instance, if + applicable. + + This field is a member of `oneof`_ ``_scheduling``. + shutdown_details (google.cloud.compute_v1.types.ManagedInstanceShutdownDetails): + Output only. Specifies the graceful shutdown details if the + instance is in ``PENDING_STOP`` state or there is a + programmed stop scheduled. + + This field is a member of `oneof`_ ``_shutdown_details``. version (google.cloud.compute_v1.types.ManagedInstanceVersion): Output only. [Output Only] Intended version of this instance. @@ -98853,6 +99757,18 @@ class InstanceStatus(proto.Enum): optional=True, message="ManagedInstancePropertiesFromFlexibilityPolicy", ) + scheduling: "ManagedInstanceScheduling" = proto.Field( + proto.MESSAGE, + number=386688404, + optional=True, + message="ManagedInstanceScheduling", + ) + shutdown_details: "ManagedInstanceShutdownDetails" = proto.Field( + proto.MESSAGE, + number=15198553, + optional=True, + message="ManagedInstanceShutdownDetails", + ) version: "ManagedInstanceVersion" = proto.Field( proto.MESSAGE, number=351608024, @@ -98989,6 +99905,70 @@ class ManagedInstancePropertiesFromFlexibilityPolicy(proto.Message): ) +class ManagedInstanceScheduling(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + graceful_shutdown_timestamp (str): + Output only. The timestamp at which the + underlying instance will be triggered for + graceful shutdown if it is configured. This is + in RFC3339 text format. + + This field is a member of `oneof`_ ``_graceful_shutdown_timestamp``. + termination_timestamp (str): + Output only. The timestamp at which the + managed instance will be terminated. This is in + RFC3339 text format. + + This field is a member of `oneof`_ ``_termination_timestamp``. + """ + + graceful_shutdown_timestamp: str = proto.Field( + proto.STRING, + number=403022375, + optional=True, + ) + termination_timestamp: str = proto.Field( + proto.STRING, + number=364180891, + optional=True, + ) + + +class ManagedInstanceShutdownDetails(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + max_duration (google.cloud.compute_v1.types.Duration): + Output only. The duration for graceful shutdown. Only + applicable when the instance is in ``PENDING_STOP`` state. + + This field is a member of `oneof`_ ``_max_duration``. + request_timestamp (str): + Output only. Past timestamp indicating the beginning of + ``PENDING_STOP`` state of instance in RFC3339 text format. + + This field is a member of `oneof`_ ``_request_timestamp``. + """ + + max_duration: "Duration" = proto.Field( + proto.MESSAGE, + number=39954959, + optional=True, + message="Duration", + ) + request_timestamp: str = proto.Field( + proto.STRING, + number=521301862, + optional=True, + ) + + class ManagedInstanceVersion(proto.Message): r""" @@ -99570,6 +100550,92 @@ class NamedPort(proto.Message): ) +class NamedSet(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + description (str): + An optional description of named set. + + This field is a member of `oneof`_ ``_description``. + elements (MutableSequence[google.cloud.compute_v1.types.Expr]): + CEL expressions that are comparable to + constructs of this set's type (see Policy + Language). + fingerprint (str): + A fingerprint for the Named Set being applied + to this Router, which is essentially a hash of + the Named Set used for optimistic locking. The + fingerprint is initially generated by Compute + Engine and changes after every request to modify + or update the Named Set. You must always provide + an up-to-date fingerprint hash in order to + update or change labels. + + To see the latest fingerprint, make a + getNamedSet() request to retrieve a Named Set. + + This field is a member of `oneof`_ ``_fingerprint``. + name (str): + This set's name, which must be a resource ID + segment and unique within all named sets owned + by the Router. Name should conform to RFC1035. + + This field is a member of `oneof`_ ``_name``. + type_ (str): + This named set's type + Check the Type enum for the list of possible + values. + + This field is a member of `oneof`_ ``_type``. + """ + + class Type(proto.Enum): + r"""This named set's type + + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + NAMED_SET_TYPE_COMMUNITY (263444871): + The Named Set is a Community Named Set. + NAMED_SET_TYPE_PREFIX (228038036): + The Named Set is a Prefix Named Set. + """ + + UNDEFINED_TYPE = 0 + NAMED_SET_TYPE_COMMUNITY = 263444871 + NAMED_SET_TYPE_PREFIX = 228038036 + + description: str = proto.Field( + proto.STRING, + number=422937596, + optional=True, + ) + elements: MutableSequence["Expr"] = proto.RepeatedField( + proto.MESSAGE, + number=528531703, + message="Expr", + ) + fingerprint: str = proto.Field( + proto.STRING, + number=234678500, + optional=True, + ) + name: str = proto.Field( + proto.STRING, + number=3373707, + optional=True, + ) + type_: str = proto.Field( + proto.STRING, + number=3575610, + optional=True, + ) + + class NatIpInfo(proto.Message): r"""Contains NAT IP information of a NAT config (i.e. usage status, mode). @@ -100035,13 +101101,15 @@ class NetworkAttachment(proto.Message): This field is a member of `oneof`_ ``_network``. producer_accept_lists (MutableSequence[str]): - Projects that are allowed to connect to this - network attachment. The project can be specified - using its id or number. + Projects or service class ids that are allowed to connect to + this network attachment. The project can be specified using + its id or number. Service class id can be specified as + "serviceclasses/{service_class_id}". producer_reject_lists (MutableSequence[str]): - Projects that are not allowed to connect to - this network attachment. The project can be - specified using its id or number. + Projects or service class ids that are not allowed to + connect to this network attachment. The project can be + specified using its id or number. Service class id can be + specified as "serviceclasses/{service_class_id}". region (str): Output only. [Output Only] URL of the region where the network attachment resides. This field applies only to the @@ -100918,9 +101986,14 @@ class NetworkEndpointGroup(proto.Message): This field is a member of `oneof`_ ``_name``. network (str): - The URL of the network to which all network - endpoints in the NEG belong. Uses default - project network if unspecified. + The URL of the network to which all network endpoints in the + NEG belong. For networkEndpointType + GCE_VM_IP_PORT,GCE_VM_IP_PORTMAP or NON_GCP_PRIVATE_IP_PORT, + if this field is not specified, a default network will be + used. This field cannot be set for NEGs with + networkEndpointType set toSERVERLESS or + PRIVATE_SERVICE_CONNECT and for global NEGs. For all other + network endpoint types, this field is required. This field is a member of `oneof`_ ``_network``. network_endpoint_type (str): @@ -101882,6 +102955,10 @@ class NetworkInterface(proto.Message): An array of alias IP ranges for this network interface. You can only specify this field for network interfaces in VPC networks. + alias_ipv6_ranges (MutableSequence[google.cloud.compute_v1.types.AliasIpRange]): + An array of alias IPv6 ranges for this + network interface. You can only specify this + field for network interfaces in VPC networks. enable_vpc_scoped_dns (bool): Optional. If true, DNS resolution will be enabled over this interface. Only valid with network_attachment. @@ -102164,6 +103241,11 @@ class StackType(proto.Enum): number=165085631, message="AliasIpRange", ) + alias_ipv6_ranges: MutableSequence["AliasIpRange"] = proto.RepeatedField( + proto.MESSAGE, + number=104028351, + message="AliasIpRange", + ) enable_vpc_scoped_dns: bool = proto.Field( proto.BOOL, number=283425868, @@ -109511,6 +110593,71 @@ class PatchInterconnectRequest(proto.Message): ) +class PatchNamedSetRouterRequest(proto.Message): + r"""A request message for Routers.PatchNamedSet. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + named_set_resource (google.cloud.compute_v1.types.NamedSet): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + router (str): + Name of the Router resource where Named Set + is defined. + """ + + named_set_resource: "NamedSet" = proto.Field( + proto.MESSAGE, + number=408608401, + message="NamedSet", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + router: str = proto.Field( + proto.STRING, + number=148608841, + ) + + class PatchNetworkAttachmentRequest(proto.Message): r"""A request message for NetworkAttachments.Patch. See the method description for details. @@ -112840,6 +113987,70 @@ class PathRule(proto.Message): ) +class PauseRolloutRequest(proto.Message): + r"""A request message for Rollouts.Pause. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + The etag of the Rollout. + If this is provided, the request will only + succeed if the etag matches the current etag of + the Rollout. + + This field is a member of `oneof`_ ``_etag``. + project (str): + Required. Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + pause. + """ + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class PerInstanceConfig(proto.Message): r""" @@ -113100,21 +114311,166 @@ class PerformMaintenanceReservationBlockRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - reservation (str): - The name of the reservation. - Name should conform to RFC1035 or be a resource - ID. - reservation_block (str): - The name of the reservation block. + reservation (str): + The name of the reservation. + Name should conform to RFC1035 or be a resource + ID. + reservation_block (str): + The name of the reservation block. + Name should conform to RFC1035 or be a resource + ID. + reservations_blocks_perform_maintenance_request_resource (google.cloud.compute_v1.types.ReservationsBlocksPerformMaintenanceRequest): + The body resource for this request + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + reservation: str = proto.Field( + proto.STRING, + number=47530956, + ) + reservation_block: str = proto.Field( + proto.STRING, + number=532832858, + ) + reservations_blocks_perform_maintenance_request_resource: "ReservationsBlocksPerformMaintenanceRequest" = proto.Field( + proto.MESSAGE, + number=485823625, + message="ReservationsBlocksPerformMaintenanceRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class PerformMaintenanceReservationRequest(proto.Message): + r"""A request message for Reservations.PerformMaintenance. See + the method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + reservation (str): + The name of the reservation. + Name should conform to RFC1035 or be a resource + ID. + reservations_perform_maintenance_request_resource (google.cloud.compute_v1.types.ReservationsPerformMaintenanceRequest): + The body resource for this request + zone (str): + Name of the zone for this request. Zone name + should conform to RFC1035. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + reservation: str = proto.Field( + proto.STRING, + number=47530956, + ) + reservations_perform_maintenance_request_resource: "ReservationsPerformMaintenanceRequest" = proto.Field( + proto.MESSAGE, + number=29702816, + message="ReservationsPerformMaintenanceRequest", + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class PerformMaintenanceReservationSubBlockRequest(proto.Message): + r"""A request message for + ReservationSubBlocks.PerformMaintenance. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent_name (str): + The name of the parent reservation and parent block. In the + format of + reservations/{reservation_name}/reservationBlocks/{reservation_block_name} + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + reservation_sub_block (str): + The name of the reservation subBlock. Name should conform to RFC1035 or be a resource ID. - reservations_blocks_perform_maintenance_request_resource (google.cloud.compute_v1.types.ReservationsBlocksPerformMaintenanceRequest): - The body resource for this request zone (str): Name of the zone for this request. Zone name should conform to RFC1035. """ + parent_name: str = proto.Field( + proto.STRING, + number=478151936, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -113124,18 +114480,9 @@ class PerformMaintenanceReservationBlockRequest(proto.Message): number=37109963, optional=True, ) - reservation: str = proto.Field( - proto.STRING, - number=47530956, - ) - reservation_block: str = proto.Field( + reservation_sub_block: str = proto.Field( proto.STRING, - number=532832858, - ) - reservations_blocks_perform_maintenance_request_resource: "ReservationsBlocksPerformMaintenanceRequest" = proto.Field( - proto.MESSAGE, - number=485823625, - message="ReservationsBlocksPerformMaintenanceRequest", + number=22750491, ) zone: str = proto.Field( proto.STRING, @@ -113143,139 +114490,120 @@ class PerformMaintenanceReservationBlockRequest(proto.Message): ) -class PerformMaintenanceReservationRequest(proto.Message): - r"""A request message for Reservations.PerformMaintenance. See - the method description for details. +class PeriodicPartialMaintenanceSchedule(proto.Message): + r"""The periodic partial maintenance schedule includes 52 weeks + worth of maintenance windows. + LINT.IfChange(PeriodicPartialMaintenanceSchedule) .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + sub_type (str): + The maintenance type in which the zone is + during the given window. Check the SubType enum + for the list of possible values. - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + This field is a member of `oneof`_ ``_sub_type``. + target_resource (str): + The target resource that the maintenance + window is for. For example, + "projects/my-project/zones/us-central1-a". - This field is a member of `oneof`_ ``_request_id``. - reservation (str): - The name of the reservation. - Name should conform to RFC1035 or be a resource - ID. - reservations_perform_maintenance_request_resource (google.cloud.compute_v1.types.ReservationsPerformMaintenanceRequest): - The body resource for this request - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. - """ + This field is a member of `oneof`_ ``_target_resource``. + type_ (str): + Check the Type enum for the list of possible + values. - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - reservation: str = proto.Field( - proto.STRING, - number=47530956, - ) - reservations_perform_maintenance_request_resource: "ReservationsPerformMaintenanceRequest" = proto.Field( - proto.MESSAGE, - number=29702816, - message="ReservationsPerformMaintenanceRequest", - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) + This field is a member of `oneof`_ ``_type``. + window_end_time (google.cloud.compute_v1.types.DateTime): + The end civil timestamp of the window (not + inclusive). This contains a time zone. + This field is a member of `oneof`_ ``_window_end_time``. + window_start_time (google.cloud.compute_v1.types.DateTime): + The start civil timestamp of the window. + This contains a time zone. -class PerformMaintenanceReservationSubBlockRequest(proto.Message): - r"""A request message for - ReservationSubBlocks.PerformMaintenance. See the method - description for details. + This field is a member of `oneof`_ ``_window_start_time``. + """ + class SubType(proto.Enum): + r"""The maintenance type in which the zone is during the given + window. - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + Values: + UNDEFINED_SUB_TYPE (0): + A value indicating that the enum field is not + set. + MAINTENANCE_SUBTYPE_UNSPECIFIED (294853734): + Default value. + MAINTENANCE_TYPE_CUSTOMER_MAINTENANCE (431585707): + A dedicated window for customers to perform their own + maintenance. This often runs concurrently with a + DISRUPTIVE_UPGRADE. + MAINTENANCE_TYPE_DISRUPTIVE_UPGRADE (385079609): + For disruptive updates, including host + machine kernel or firmware upgrades. + MAINTENANCE_TYPE_STABLE (141316244): + A post-maintenance window for customers to + conduct final testing and performance validation + before resuming full business operations. + MAINTENANCE_TYPE_TRANSITION (348575278): + For preliminary, non-disruptive tasks such as + key rotations. + """ - Attributes: - parent_name (str): - The name of the parent reservation and parent block. In the - format of - reservations/{reservation_name}/reservationBlocks/{reservation_block_name} - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. + UNDEFINED_SUB_TYPE = 0 + MAINTENANCE_SUBTYPE_UNSPECIFIED = 294853734 + MAINTENANCE_TYPE_CUSTOMER_MAINTENANCE = 431585707 + MAINTENANCE_TYPE_DISRUPTIVE_UPGRADE = 385079609 + MAINTENANCE_TYPE_STABLE = 141316244 + MAINTENANCE_TYPE_TRANSITION = 348575278 - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. + class Type(proto.Enum): + r""" - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). + Values: + UNDEFINED_TYPE (0): + A value indicating that the enum field is not + set. + MAINTENANCE_TYPE_UNSPECIFIED (351550814): + Default value. + PRIVATE_ZONE_MAINTENANCE (55583292): + The zone is in a private maintenance window. + """ - This field is a member of `oneof`_ ``_request_id``. - reservation_sub_block (str): - The name of the reservation subBlock. - Name should conform to RFC1035 or be a resource - ID. - zone (str): - Name of the zone for this request. Zone name - should conform to RFC1035. - """ + UNDEFINED_TYPE = 0 + MAINTENANCE_TYPE_UNSPECIFIED = 351550814 + PRIVATE_ZONE_MAINTENANCE = 55583292 - parent_name: str = proto.Field( + sub_type: str = proto.Field( proto.STRING, - number=478151936, + number=67924441, + optional=True, ) - project: str = proto.Field( + target_resource: str = proto.Field( proto.STRING, - number=227560217, + number=467318524, + optional=True, ) - request_id: str = proto.Field( + type_: str = proto.Field( proto.STRING, - number=37109963, + number=3575610, optional=True, ) - reservation_sub_block: str = proto.Field( - proto.STRING, - number=22750491, + window_end_time: "DateTime" = proto.Field( + proto.MESSAGE, + number=271816480, + optional=True, + message="DateTime", ) - zone: str = proto.Field( - proto.STRING, - number=3744684, + window_start_time: "DateTime" = proto.Field( + proto.MESSAGE, + number=473061433, + optional=True, + message="DateTime", ) @@ -116724,6 +118052,12 @@ class RecreateInstancesInstanceGroupManagerRequest(proto.Message): The name of the managed instance group. instance_group_managers_recreate_instances_request_resource (google.cloud.compute_v1.types.InstanceGroupManagersRecreateInstancesRequest): The body resource for this request + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance recreation even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. request_id (str): @@ -116762,6 +118096,11 @@ class RecreateInstancesInstanceGroupManagerRequest(proto.Message): number=21405952, message="InstanceGroupManagersRecreateInstancesRequest", ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -116788,6 +118127,12 @@ class RecreateInstancesRegionInstanceGroupManagerRequest(proto.Message): Attributes: instance_group_manager (str): Name of the managed instance group. + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance recreation even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. region (str): @@ -116822,6 +118167,11 @@ class RecreateInstancesRegionInstanceGroupManagerRequest(proto.Message): proto.STRING, number=249363395, ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -124178,6 +125528,11 @@ class ResourceStatusPhysicalHostTopology(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + additional_attributes (google.cloud.compute_v1.types.ResourceStatusPhysicalHostTopologyAdditionalAttributes): + Output only. [Output Only] Additional location information + of the running instance. + + This field is a member of `oneof`_ ``_additional_attributes``. block (str): [Output Only] The ID of the block in which the running instance is located. Instances within the same block @@ -124204,6 +125559,14 @@ class ResourceStatusPhysicalHostTopology(proto.Message): This field is a member of `oneof`_ ``_subblock``. """ + additional_attributes: "ResourceStatusPhysicalHostTopologyAdditionalAttributes" = ( + proto.Field( + proto.MESSAGE, + number=74463343, + optional=True, + message="ResourceStatusPhysicalHostTopologyAdditionalAttributes", + ) + ) block: str = proto.Field( proto.STRING, number=93832333, @@ -124226,6 +125589,25 @@ class ResourceStatusPhysicalHostTopology(proto.Message): ) +class ResourceStatusPhysicalHostTopologyAdditionalAttributes(proto.Message): + r"""Additional location information of the running instance. + + Attributes: + accelerator_topology_ids (MutableMapping[str, str]): + Output only. The IDs of the accelerator + topologies the instance belongs to. For example + The key will be topologies like "4x4", "2x2x2" + and the value will be the location ID of the + topologies. + """ + + accelerator_topology_ids: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=338216508, + ) + + class ResourceStatusReservationConsumptionInfo(proto.Message): r"""Reservation consumption information that the instance is consuming from. @@ -124458,6 +125840,70 @@ class ResumeInstancesRegionInstanceGroupManagerRequest(proto.Message): ) +class ResumeRolloutRequest(proto.Message): + r"""A request message for Rollouts.Resume. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + The etag of the Rollout. + If this is provided, the request will only + succeed if the etag matches the current etag of + the Rollout. + + This field is a member of `oneof`_ ``_etag``. + project (str): + Required. Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + rollout (str): + Required. Name of the Rollout resource to + resume. + """ + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + rollout: str = proto.Field( + proto.STRING, + number=303366577, + ) + + class Rollout(proto.Message): r"""Rollout resource. @@ -124521,6 +125967,16 @@ class Rollout(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + pause_time (str): + Output only. The timestamp at which the + Rollout was paused. + + This field is a member of `oneof`_ ``_pause_time``. + resume_time (str): + Output only. The timestamp at which the + Rollout was resumed. + + This field is a member of `oneof`_ ``_resume_time``. rollout_entity (google.cloud.compute_v1.types.RolloutRolloutEntity): Required. The resource being rolled out. @@ -124672,6 +126128,16 @@ class State(proto.Enum): number=3373707, optional=True, ) + pause_time: str = proto.Field( + proto.STRING, + number=489697142, + optional=True, + ) + resume_time: str = proto.Field( + proto.STRING, + number=457856927, + optional=True, + ) rollout_entity: "RolloutRolloutEntity" = proto.Field( proto.MESSAGE, number=70633009, @@ -126430,6 +127896,10 @@ class Router(proto.Message): nats (MutableSequence[google.cloud.compute_v1.types.RouterNat]): A list of NAT services created in this router. + ncc_gateway (str): + URI of the ncc_gateway to which this router associated. + + This field is a member of `oneof`_ ``_ncc_gateway``. network (str): URI of the network to which this router belongs. @@ -126510,6 +127980,11 @@ class Router(proto.Message): number=3373938, message="RouterNat", ) + ncc_gateway: str = proto.Field( + proto.STRING, + number=174876755, + optional=True, + ) network: str = proto.Field( proto.STRING, number=232872494, @@ -127656,6 +129131,14 @@ class RouterNat(proto.Message): IPs that have been assigned to the NAT. These IPs should be used for updating/patching a NAT only. + effective_tcp_time_wait_timeout_sec (int): + Output only. Effective timeout (in seconds) for TCP + connections that are in TIME_WAIT state. This value is equal + to tcp_time_wait_timeout_sec. If tcp_time_wait_timeout_sec + isn't set, the effective timeout is 30s or 120s. The field + is output only. + + This field is a member of `oneof`_ ``_effective_tcp_time_wait_timeout_sec``. enable_dynamic_port_allocation (bool): Enable Dynamic Port Allocation. @@ -128013,6 +129496,11 @@ class Type(proto.Enum): proto.STRING, number=504078535, ) + effective_tcp_time_wait_timeout_sec: int = proto.Field( + proto.INT32, + number=248089957, + optional=True, + ) enable_dynamic_port_allocation: bool = proto.Field( proto.BOOL, number=532106402, @@ -128444,6 +129932,10 @@ class RouterStatus(proto.Message): nat_status (MutableSequence[google.cloud.compute_v1.types.RouterStatusNatStatus]): + ncc_gateway (str): + URI of the ncc_gateway to which this router associated. + + This field is a member of `oneof`_ ``_ncc_gateway``. network (str): URI of the network to which this router belongs. @@ -128471,6 +129963,11 @@ class RouterStatus(proto.Message): number=63098064, message="RouterStatusNatStatus", ) + ncc_gateway: str = proto.Field( + proto.STRING, + number=174876755, + optional=True, + ) network: str = proto.Field( proto.STRING, number=232872494, @@ -128915,6 +130412,34 @@ class RouterStatusResponse(proto.Message): ) +class RoutersGetNamedSetResponse(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + end_interface: MixerGetResponseWithEtagBuilder + + This field is a member of `oneof`_ ``_etag``. + resource (google.cloud.compute_v1.types.NamedSet): + + This field is a member of `oneof`_ ``_resource``. + """ + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + resource: "NamedSet" = proto.Field( + proto.MESSAGE, + number=195806222, + optional=True, + message="NamedSet", + ) + + class RoutersGetRoutePolicyResponse(proto.Message): r""" @@ -129023,6 +130548,95 @@ def raw_page(self): ) +class RoutersListNamedSets(proto.Message): + r""" + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + etag (str): + + This field is a member of `oneof`_ ``_etag``. + id (str): + [Output Only] The unique identifier for the resource. This + identifier is defined by the server. + + This field is a member of `oneof`_ ``_id``. + kind (str): + Output only. [Output Only] Type of resource. + Alwayscompute#routersListNamedSets for lists of named sets. + + This field is a member of `oneof`_ ``_kind``. + next_page_token (str): + [Output Only] 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``. + result (MutableSequence[google.cloud.compute_v1.types.NamedSet]): + [Output Only] A list of named sets. + self_link (str): + Output only. [Output Only] Server-defined URL for this + resource. + + This field is a member of `oneof`_ ``_self_link``. + unreachables (MutableSequence[str]): + Output only. [Output Only] Unreachable resources. + warning (google.cloud.compute_v1.types.Warning): + [Output Only] Informational warning message. + + This field is a member of `oneof`_ ``_warning``. + """ + + @property + def raw_page(self): + return self + + etag: str = proto.Field( + proto.STRING, + number=3123477, + optional=True, + ) + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + kind: str = proto.Field( + proto.STRING, + number=3292052, + optional=True, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=79797525, + optional=True, + ) + result: MutableSequence["NamedSet"] = proto.RepeatedField( + proto.MESSAGE, + number=139315229, + message="NamedSet", + ) + self_link: str = proto.Field( + proto.STRING, + number=456214797, + optional=True, + ) + unreachables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=243372063, + ) + warning: "Warning" = proto.Field( + proto.MESSAGE, + number=50704284, + optional=True, + message="Warning", + ) + + class RoutersListRoutePolicies(proto.Message): r""" @@ -131096,6 +132710,36 @@ class SecurityPolicyDdosProtectionConfig(proto.Message): .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + ddos_adaptive_protection (str): + Check the DdosAdaptiveProtection enum for the + list of possible values. + + This field is a member of `oneof`_ ``_ddos_adaptive_protection``. + ddos_impacted_baseline_threshold (float): + DDoS Protection for Network Load Balancers + (and VMs with public IPs) builds DDoS + mitigations that minimize collateral damage. It + quantifies this as the fraction of a non-abuse + baseline that's inadvertently blocked. + + Rules whose collateral damage exceeds + ddosImpactedBaselineThreshold will not be + deployed. Using a lower value will prioritize + keeping collateral damage low, possibly at the + cost of its effectiveness in rate limiting some + or all of the attack. It should typically be + unset, so Advanced DDoS (and Adaptive + Protection) uses the best mitigation it can + find. Setting the threshold is advised if there + are logs for false positive detections with high + collateral damage, and will cause Advanced DDoS + to attempt to find a less aggressive rule that + satisfies the constraint. If a suitable rule + cannot be found, the system falls back to either + no mitigation for smaller attacks or broader + network throttles for larger ones. + + This field is a member of `oneof`_ ``_ddos_impacted_baseline_threshold``. ddos_protection (str): Check the DdosProtection enum for the list of possible values. @@ -131103,6 +132747,32 @@ class SecurityPolicyDdosProtectionConfig(proto.Message): This field is a member of `oneof`_ ``_ddos_protection``. """ + class DdosAdaptiveProtection(proto.Enum): + r""" + + Values: + UNDEFINED_DDOS_ADAPTIVE_PROTECTION (0): + A value indicating that the enum field is not + set. + DDOS_ADAPTIVE_PROTECTION_UNSPECIFIED (314527935): + No description available. + DISABLED (516696700): + No description available. + ENABLED (182130465): + No description available. + PREVIEW (399798184): + No description available. + UNSPECIFIED_ADAPTIVE_PROTECTION (86330138): + No description available. + """ + + UNDEFINED_DDOS_ADAPTIVE_PROTECTION = 0 + DDOS_ADAPTIVE_PROTECTION_UNSPECIFIED = 314527935 + DISABLED = 516696700 + ENABLED = 182130465 + PREVIEW = 399798184 + UNSPECIFIED_ADAPTIVE_PROTECTION = 86330138 + class DdosProtection(proto.Enum): r""" @@ -131123,6 +132793,16 @@ class DdosProtection(proto.Enum): ADVANCED_PREVIEW = 40905867 STANDARD = 484642493 + ddos_adaptive_protection: str = proto.Field( + proto.STRING, + number=96895463, + optional=True, + ) + ddos_impacted_baseline_threshold: float = proto.Field( + proto.FLOAT, + number=192689584, + optional=True, + ) ddos_protection: str = proto.Field( proto.STRING, number=275173268, @@ -132861,6 +134541,12 @@ class ServiceAttachment(proto.Message): except the last character, which cannot be a dash. This field is a member of `oneof`_ ``_name``. + nat_ips_per_endpoint (int): + The number of NAT IP addresses to be + allocated per connected endpoint. If not + specified, the default value is 1. + + This field is a member of `oneof`_ ``_nat_ips_per_endpoint``. nat_subnets (MutableSequence[str]): An array of URLs where each entry is the URL of a subnet provided by the service producer to @@ -133028,6 +134714,11 @@ class ConnectionPreference(proto.Enum): number=3373707, optional=True, ) + nat_ips_per_endpoint: int = proto.Field( + proto.UINT32, + number=371459848, + optional=True, + ) nat_subnets: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=374785944, @@ -139370,13 +141061,15 @@ class Snapshot(proto.Message): This field is a member of `oneof`_ ``_storage_bytes``. storage_bytes_status (str): - Output only. [Output Only] An indicator whether storageBytes - is in a stable state or it is being adjusted as a result of - shared storage reallocation. This status can either be - UPDATING, meaning the size of the snapshot is being updated, - or UP_TO_DATE, meaning the size of the snapshot is - up-to-date. Check the StorageBytesStatus enum for the list - of possible values. + Output only. [Deprecated] Instead, check the storageBytes + field. After snapshot creation, the storageBytesStatus field + is alwaysUP_TO_DATE. [Output Only] An indicator whether + storageBytes is in a stable state or it is being adjusted as + a result of shared storage reallocation. This status can + either be unset, meaning the snapshot is being created, or + UP_TO_DATE, meaning the size of the snapshot is up-to-date. + Check the StorageBytesStatus enum for the list of possible + values. This field is a member of `oneof`_ ``_storage_bytes_status``. storage_locations (MutableSequence[str]): @@ -139451,11 +141144,13 @@ class Status(proto.Enum): UPLOADING = 267603489 class StorageBytesStatus(proto.Enum): - r"""Output only. [Output Only] An indicator whether storageBytes is in a - stable state or it is being adjusted as a result of shared storage - reallocation. This status can either be UPDATING, meaning the size - of the snapshot is being updated, or UP_TO_DATE, meaning the size of - the snapshot is up-to-date. + r"""Output only. [Deprecated] Instead, check the storageBytes field. + After snapshot creation, the storageBytesStatus field is + alwaysUP_TO_DATE. [Output Only] An indicator whether storageBytes is + in a stable state or it is being adjusted as a result of shared + storage reallocation. This status can either be unset, meaning the + snapshot is being created, or UP_TO_DATE, meaning the size of the + snapshot is up-to-date. Values: UNDEFINED_STORAGE_BYTES_STATUS (0): @@ -141354,9 +143049,6 @@ class SslPolicyReference(proto.Message): Attributes: ssl_policy (str): - URL of the SSL policy resource. Set this to - empty string to clear any existing SSL policy - associated with the target proxy resource. This field is a member of `oneof`_ ``_ssl_policy``. """ @@ -142274,6 +143966,12 @@ class StopInstancesInstanceGroupManagerRequest(proto.Message): The name of the managed instance group. instance_group_managers_stop_instances_request_resource (google.cloud.compute_v1.types.InstanceGroupManagersStopInstancesRequest): The body resource for this request + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance stopping even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. request_id (str): @@ -142312,6 +144010,11 @@ class StopInstancesInstanceGroupManagerRequest(proto.Message): number=37556877, message="InstanceGroupManagersStopInstancesRequest", ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -142338,6 +144041,12 @@ class StopInstancesRegionInstanceGroupManagerRequest(proto.Message): Attributes: instance_group_manager (str): The name of the managed instance group. + no_graceful_shutdown (bool): + When set, graceful shutdown is skipped for + instance stopping even if it's configured for + the instances. + + This field is a member of `oneof`_ ``_no_graceful_shutdown``. project (str): Project ID for this request. region (str): @@ -142372,6 +144081,11 @@ class StopInstancesRegionInstanceGroupManagerRequest(proto.Message): proto.STRING, number=249363395, ) + no_graceful_shutdown: bool = proto.Field( + proto.BOOL, + number=336255890, + optional=True, + ) project: str = proto.Field( proto.STRING, number=227560217, @@ -144765,6 +146479,21 @@ class SubnetworkSecondaryRange(proto.Message): the ``ipCollection`` field. This field is a member of `oneof`_ ``_ip_cidr_range``. + ip_collection (str): + Reference to a Public Delegated Prefix (PDP) for BYOIP. This + field should be specified for configuring BYOGUA internal + IPv6 secondary range. When specified along with the + ip_cidr_range, the ip_cidr_range must lie within the PDP + referenced by the ``ipCollection`` field. When specified + without the ip_cidr_range, the range is auto-allocated from + the PDP referenced by the ``ipCollection`` field. + + This field is a member of `oneof`_ ``_ip_collection``. + ip_version (str): + Check the IpVersion enum for the list of + possible values. + + This field is a member of `oneof`_ ``_ip_version``. range_name (str): The name associated with this subnetwork secondary range, used when adding an alias @@ -144780,11 +146509,41 @@ class SubnetworkSecondaryRange(proto.Message): This field is a member of `oneof`_ ``_reserved_internal_range``. """ + class IpVersion(proto.Enum): + r""" + + Values: + UNDEFINED_IP_VERSION (0): + A value indicating that the enum field is not + set. + IPV4 (2254341): + No description available. + IPV6 (2254343): + No description available. + IP_VERSION_UNSPECIFIED (92360440): + Treated as IPV4 for backward-compatibility. + """ + + UNDEFINED_IP_VERSION = 0 + IPV4 = 2254341 + IPV6 = 2254343 + IP_VERSION_UNSPECIFIED = 92360440 + ip_cidr_range: str = proto.Field( proto.STRING, number=98117322, optional=True, ) + ip_collection: str = proto.Field( + proto.STRING, + number=176818358, + optional=True, + ) + ip_version: str = proto.Field( + proto.STRING, + number=294959552, + optional=True, + ) range_name: str = proto.Field( proto.STRING, number=332216397, @@ -148221,6 +149980,13 @@ class TargetTcpProxy(proto.Message): Alwayscompute#targetTcpProxy for target TCP proxies. This field is a member of `oneof`_ ``_kind``. + load_balancing_scheme (str): + Specifies the type of load balancing scheme + used by this target proxy. Check the + LoadBalancingScheme enum for the list of + possible values. + + This field is a member of `oneof`_ ``_load_balancing_scheme``. name (str): Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, @@ -148271,6 +150037,30 @@ class TargetTcpProxy(proto.Message): This field is a member of `oneof`_ ``_service``. """ + class LoadBalancingScheme(proto.Enum): + r"""Specifies the type of load balancing scheme used by this + target proxy. + + Values: + UNDEFINED_LOAD_BALANCING_SCHEME (0): + A value indicating that the enum field is not + set. + EXTERNAL (35607499): + No description available. + EXTERNAL_MANAGED (512006923): + No description available. + INTERNAL_MANAGED (37350397): + No description available. + LOAD_BALANCING_SCHEME_UNSPECIFIED (526507452): + No description available. + """ + + UNDEFINED_LOAD_BALANCING_SCHEME = 0 + EXTERNAL = 35607499 + EXTERNAL_MANAGED = 512006923 + INTERNAL_MANAGED = 37350397 + LOAD_BALANCING_SCHEME_UNSPECIFIED = 526507452 + class ProxyHeader(proto.Enum): r"""Specifies the type of proxy header to append before sending data to the backend, either NONE or PROXY_V1. The default is NONE. @@ -148309,6 +150099,11 @@ class ProxyHeader(proto.Enum): number=3292052, optional=True, ) + load_balancing_scheme: str = proto.Field( + proto.STRING, + number=363890244, + optional=True, + ) name: str = proto.Field( proto.STRING, number=3373707, @@ -150883,6 +152678,38 @@ class TestPermissionsResponse(proto.Message): ) +class TimeZone(proto.Message): + r"""Represents a time zone from the `IANA Time Zone + Database `__. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + id (str): + IANA Time Zone Database time zone. For example + "America/New_York". + + This field is a member of `oneof`_ ``_id``. + version (str): + Optional. IANA Time Zone Database version + number. For example "2019a". + + This field is a member of `oneof`_ ``_version``. + """ + + id: str = proto.Field( + proto.STRING, + number=3355, + optional=True, + ) + version: str = proto.Field( + proto.STRING, + number=351608024, + optional=True, + ) + + class Uint128(proto.Message): r""" @@ -151940,142 +153767,341 @@ class UpdateKmsKeyDiskRequest(proto.Message): (00000000-0000-0000-0000-000000000000). This field is a member of `oneof`_ ``_request_id``. - zone (str): - The name of the zone for this request. + zone (str): + The name of the zone for this request. + """ + + disk: str = proto.Field( + proto.STRING, + number=3083677, + ) + disk_update_kms_key_request_resource: "DiskUpdateKmsKeyRequest" = proto.Field( + proto.MESSAGE, + number=178025952, + message="DiskUpdateKmsKeyRequest", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + zone: str = proto.Field( + proto.STRING, + number=3744684, + ) + + +class UpdateKmsKeyRegionDiskRequest(proto.Message): + r"""A request message for RegionDisks.UpdateKmsKey. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + disk (str): + Name of the Disk resource, should conform to + RFC1035. + project (str): + Project ID for this request. + region (str): + The name of the region for this request. + region_disk_update_kms_key_request_resource (google.cloud.compute_v1.types.RegionDiskUpdateKmsKeyRequest): + The body resource for this request + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + """ + + disk: str = proto.Field( + proto.STRING, + number=3083677, + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_disk_update_kms_key_request_resource: "RegionDiskUpdateKmsKeyRequest" = ( + proto.Field( + proto.MESSAGE, + number=10015819, + message="RegionDiskUpdateKmsKeyRequest", + ) + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + + +class UpdateKmsKeyRegionSnapshotRequest(proto.Message): + r"""A request message for RegionSnapshots.UpdateKmsKey. See the + method description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + region_snapshot_update_kms_key_request_resource (google.cloud.compute_v1.types.RegionSnapshotUpdateKmsKeyRequest): + The body resource for this request + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + snapshot (str): + Name of the snapshot resource to update. + Should conform to RFC1035. + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + region: str = proto.Field( + proto.STRING, + number=138946292, + ) + region_snapshot_update_kms_key_request_resource: "RegionSnapshotUpdateKmsKeyRequest" = proto.Field( + proto.MESSAGE, + number=279384818, + message="RegionSnapshotUpdateKmsKeyRequest", + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + snapshot: str = proto.Field( + proto.STRING, + number=284874180, + ) + + +class UpdateKmsKeySnapshotRequest(proto.Message): + r"""A request message for Snapshots.UpdateKmsKey. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + snapshot (str): + Name of the snapshot resource to update. + Should conform to RFC1035. + snapshot_update_kms_key_request_resource (google.cloud.compute_v1.types.SnapshotUpdateKmsKeyRequest): + The body resource for this request + """ + + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + snapshot: str = proto.Field( + proto.STRING, + number=284874180, + ) + snapshot_update_kms_key_request_resource: "SnapshotUpdateKmsKeyRequest" = ( + proto.Field( + proto.MESSAGE, + number=103145991, + message="SnapshotUpdateKmsKeyRequest", + ) + ) + + +class UpdateLicenseRequest(proto.Message): + r"""A request message for Licenses.Update. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + license_ (str): + The license name for this request. + license_resource (google.cloud.compute_v1.types.License): + The body resource for this request + project (str): + Project ID for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + update_mask (str): + update_mask indicates fields to be updated as part of this + request. + + This field is a member of `oneof`_ ``_update_mask``. + """ + + license_: str = proto.Field( + proto.STRING, + number=166757441, + ) + license_resource: "License" = proto.Field( + proto.MESSAGE, + number=437955148, + message="License", + ) + project: str = proto.Field( + proto.STRING, + number=227560217, + ) + request_id: str = proto.Field( + proto.STRING, + number=37109963, + optional=True, + ) + update_mask: str = proto.Field( + proto.STRING, + number=500079778, + optional=True, + ) + + +class UpdateNamedSetRouterRequest(proto.Message): + r"""A request message for Routers.UpdateNamedSet. See the method + description for details. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + named_set_resource (google.cloud.compute_v1.types.NamedSet): + The body resource for this request + project (str): + Project ID for this request. + region (str): + Name of the region for this request. + request_id (str): + An optional request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server will know to + ignore the request if it has already been + completed. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be + a valid UUID with the exception that zero UUID + is not supported + (00000000-0000-0000-0000-000000000000). + + This field is a member of `oneof`_ ``_request_id``. + router (str): + Name of the Router resource where Named Set + is defined. """ - disk: str = proto.Field( - proto.STRING, - number=3083677, - ) - disk_update_kms_key_request_resource: "DiskUpdateKmsKeyRequest" = proto.Field( + named_set_resource: "NamedSet" = proto.Field( proto.MESSAGE, - number=178025952, - message="DiskUpdateKmsKeyRequest", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - zone: str = proto.Field( - proto.STRING, - number=3744684, - ) - - -class UpdateKmsKeyRegionDiskRequest(proto.Message): - r"""A request message for RegionDisks.UpdateKmsKey. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - disk (str): - Name of the Disk resource, should conform to - RFC1035. - project (str): - Project ID for this request. - region (str): - The name of the region for this request. - region_disk_update_kms_key_request_resource (google.cloud.compute_v1.types.RegionDiskUpdateKmsKeyRequest): - The body resource for this request - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - """ - - disk: str = proto.Field( - proto.STRING, - number=3083677, - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - region: str = proto.Field( - proto.STRING, - number=138946292, - ) - region_disk_update_kms_key_request_resource: "RegionDiskUpdateKmsKeyRequest" = ( - proto.Field( - proto.MESSAGE, - number=10015819, - message="RegionDiskUpdateKmsKeyRequest", - ) - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, + number=408608401, + message="NamedSet", ) - - -class UpdateKmsKeyRegionSnapshotRequest(proto.Message): - r"""A request message for RegionSnapshots.UpdateKmsKey. See the - method description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - project (str): - Project ID for this request. - region (str): - Name of the region for this request. - region_snapshot_update_kms_key_request_resource (google.cloud.compute_v1.types.RegionSnapshotUpdateKmsKeyRequest): - The body resource for this request - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - snapshot (str): - Name of the snapshot resource to update. - Should conform to RFC1035. - """ - project: str = proto.Field( proto.STRING, number=227560217, @@ -152084,148 +154110,14 @@ class UpdateKmsKeyRegionSnapshotRequest(proto.Message): proto.STRING, number=138946292, ) - region_snapshot_update_kms_key_request_resource: "RegionSnapshotUpdateKmsKeyRequest" = proto.Field( - proto.MESSAGE, - number=279384818, - message="RegionSnapshotUpdateKmsKeyRequest", - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - snapshot: str = proto.Field( - proto.STRING, - number=284874180, - ) - - -class UpdateKmsKeySnapshotRequest(proto.Message): - r"""A request message for Snapshots.UpdateKmsKey. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - snapshot (str): - Name of the snapshot resource to update. - Should conform to RFC1035. - snapshot_update_kms_key_request_resource (google.cloud.compute_v1.types.SnapshotUpdateKmsKeyRequest): - The body resource for this request - """ - - project: str = proto.Field( - proto.STRING, - number=227560217, - ) - request_id: str = proto.Field( - proto.STRING, - number=37109963, - optional=True, - ) - snapshot: str = proto.Field( - proto.STRING, - number=284874180, - ) - snapshot_update_kms_key_request_resource: "SnapshotUpdateKmsKeyRequest" = ( - proto.Field( - proto.MESSAGE, - number=103145991, - message="SnapshotUpdateKmsKeyRequest", - ) - ) - - -class UpdateLicenseRequest(proto.Message): - r"""A request message for Licenses.Update. See the method - description for details. - - - .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields - - Attributes: - license_ (str): - The license name for this request. - license_resource (google.cloud.compute_v1.types.License): - The body resource for this request - project (str): - Project ID for this request. - request_id (str): - An optional request ID to identify requests. - Specify a unique request ID so that if you must - retry your request, the server will know to - ignore the request if it has already been - completed. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be - a valid UUID with the exception that zero UUID - is not supported - (00000000-0000-0000-0000-000000000000). - - This field is a member of `oneof`_ ``_request_id``. - update_mask (str): - update_mask indicates fields to be updated as part of this - request. - - This field is a member of `oneof`_ ``_update_mask``. - """ - - license_: str = proto.Field( - proto.STRING, - number=166757441, - ) - license_resource: "License" = proto.Field( - proto.MESSAGE, - number=437955148, - message="License", - ) - project: str = proto.Field( - proto.STRING, - number=227560217, - ) request_id: str = proto.Field( proto.STRING, number=37109963, optional=True, ) - update_mask: str = proto.Field( + router: str = proto.Field( proto.STRING, - number=500079778, - optional=True, + number=148608841, ) @@ -158498,6 +160390,9 @@ class Zone(proto.Message): the zone. This field is a member of `oneof`_ ``_region``. + resource_status (google.cloud.compute_v1.types.ZoneResourceStatus): + + This field is a member of `oneof`_ ``_resource_status``. self_link (str): [Output Only] Server-defined URL for the resource. @@ -158570,6 +160465,12 @@ class Status(proto.Enum): number=138946292, optional=True, ) + resource_status: "ZoneResourceStatus" = proto.Field( + proto.MESSAGE, + number=249429315, + optional=True, + message="ZoneResourceStatus", + ) self_link: str = proto.Field( proto.STRING, number=456214797, @@ -158661,6 +160562,24 @@ def raw_page(self): ) +class ZoneResourceStatus(proto.Message): + r""" + + Attributes: + upcoming_maintenances (MutableSequence[google.cloud.compute_v1.types.PeriodicPartialMaintenanceSchedule]): + Output only. [Output Only] The upcoming maintenance + schedule. + """ + + upcoming_maintenances: MutableSequence["PeriodicPartialMaintenanceSchedule"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=68484611, + message="PeriodicPartialMaintenanceSchedule", + ) + ) + + class ZoneSetLabelsRequest(proto.Message): r""" diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_advance_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_advance_sync.py new file mode 100644 index 000000000000..3b552d6c1713 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_advance_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Advance +# 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 + + +# [START compute_v1_generated_Rollouts_Advance_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_v1 + + +def sample_advance(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.AdvanceRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.advance(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Rollouts_Advance_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_pause_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_pause_sync.py new file mode 100644 index 000000000000..2383c587ad91 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_pause_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Pause +# 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 + + +# [START compute_v1_generated_Rollouts_Pause_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_v1 + + +def sample_pause(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.PauseRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.pause(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Rollouts_Pause_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_resume_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_resume_sync.py new file mode 100644 index 000000000000..ba656425a64b --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_rollouts_resume_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 Resume +# 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 + + +# [START compute_v1_generated_Rollouts_Resume_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_v1 + + +def sample_resume(): + # Create a client + client = compute_v1.RolloutsClient() + + # Initialize request argument(s) + request = compute_v1.ResumeRolloutRequest( + project="project_value", + rollout="rollout_value", + ) + + # Make the request + response = client.resume(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Rollouts_Resume_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_delete_named_set_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_delete_named_set_sync.py new file mode 100644 index 000000000000..5802f4ff02c2 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_delete_named_set_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteNamedSet +# 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 + + +# [START compute_v1_generated_Routers_DeleteNamedSet_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_v1 + + +def sample_delete_named_set(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.DeleteNamedSetRouterRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + response = client.delete_named_set(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Routers_DeleteNamedSet_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_get_named_set_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_get_named_set_sync.py new file mode 100644 index 000000000000..f5fe9a5f0cd8 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_get_named_set_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetNamedSet +# 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 + + +# [START compute_v1_generated_Routers_GetNamedSet_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_v1 + + +def sample_get_named_set(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.GetNamedSetRouterRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + response = client.get_named_set(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Routers_GetNamedSet_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_list_named_sets_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_list_named_sets_sync.py new file mode 100644 index 000000000000..f2c3a2eae859 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_list_named_sets_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListNamedSets +# 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 + + +# [START compute_v1_generated_Routers_ListNamedSets_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_v1 + + +def sample_list_named_sets(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.ListNamedSetsRoutersRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + page_result = client.list_named_sets(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END compute_v1_generated_Routers_ListNamedSets_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_patch_named_set_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_patch_named_set_sync.py new file mode 100644 index 000000000000..2c7edbebbdb4 --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_patch_named_set_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 PatchNamedSet +# 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 + + +# [START compute_v1_generated_Routers_PatchNamedSet_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_v1 + + +def sample_patch_named_set(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.PatchNamedSetRouterRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + response = client.patch_named_set(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Routers_PatchNamedSet_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_update_named_set_sync.py b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_update_named_set_sync.py new file mode 100644 index 000000000000..7eb19f42261d --- /dev/null +++ b/packages/google-cloud-compute/samples/generated_samples/compute_v1_generated_routers_update_named_set_sync.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 UpdateNamedSet +# 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 + + +# [START compute_v1_generated_Routers_UpdateNamedSet_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_v1 + + +def sample_update_named_set(): + # Create a client + client = compute_v1.RoutersClient() + + # Initialize request argument(s) + request = compute_v1.UpdateNamedSetRouterRequest( + project="project_value", + region="region_value", + router="router_value", + ) + + # Make the request + response = client.update_named_set(request=request) + + # Handle the response + print(response) + + +# [END compute_v1_generated_Routers_UpdateNamedSet_sync] diff --git a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json index 9affd8eff6bb..cdf0af8b07eb 100644 --- a/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json +++ b/packages/google-cloud-compute/samples/generated_samples/snippet_metadata_google.cloud.compute.v1.json @@ -67855,6 +67855,90 @@ ], "title": "compute_v1_generated_rollout_plans_list_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" + }, + "fullName": "google.cloud.compute_v1.RolloutsClient.advance", + "method": { + "fullName": "google.cloud.compute.v1.Rollouts.Advance", + "service": { + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" + }, + "shortName": "Advance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.AdvanceRolloutRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "rollout", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "advance" + }, + "description": "Sample for Advance", + "file": "compute_v1_generated_rollouts_advance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Rollouts_Advance_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_rollouts_advance_sync.py" + }, { "canonical": true, "clientMethod": { @@ -68187,6 +68271,174 @@ ], "title": "compute_v1_generated_rollouts_list_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" + }, + "fullName": "google.cloud.compute_v1.RolloutsClient.pause", + "method": { + "fullName": "google.cloud.compute.v1.Rollouts.Pause", + "service": { + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" + }, + "shortName": "Pause" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PauseRolloutRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "rollout", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "pause" + }, + "description": "Sample for Pause", + "file": "compute_v1_generated_rollouts_pause_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Rollouts_Pause_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_rollouts_pause_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RolloutsClient", + "shortName": "RolloutsClient" + }, + "fullName": "google.cloud.compute_v1.RolloutsClient.resume", + "method": { + "fullName": "google.cloud.compute.v1.Rollouts.Resume", + "service": { + "fullName": "google.cloud.compute.v1.Rollouts", + "shortName": "Rollouts" + }, + "shortName": "Resume" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ResumeRolloutRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "rollout", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "resume" + }, + "description": "Sample for Resume", + "file": "compute_v1_generated_rollouts_resume_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Rollouts_Resume_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_rollouts_resume_sync.py" + }, { "canonical": true, "clientMethod": { @@ -68267,6 +68519,94 @@ ], "title": "compute_v1_generated_routers_aggregated_list_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RoutersClient", + "shortName": "RoutersClient" + }, + "fullName": "google.cloud.compute_v1.RoutersClient.delete_named_set", + "method": { + "fullName": "google.cloud.compute.v1.Routers.DeleteNamedSet", + "service": { + "fullName": "google.cloud.compute.v1.Routers", + "shortName": "Routers" + }, + "shortName": "DeleteNamedSet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteNamedSetRouterRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "router", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "delete_named_set" + }, + "description": "Sample for DeleteNamedSet", + "file": "compute_v1_generated_routers_delete_named_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Routers_DeleteNamedSet_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_routers_delete_named_set_sync.py" + }, { "canonical": true, "clientMethod": { @@ -68320,7 +68660,95 @@ "file": "compute_v1_generated_routers_delete_route_policy_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Routers_DeleteRoutePolicy_sync", + "regionTag": "compute_v1_generated_Routers_DeleteRoutePolicy_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_routers_delete_route_policy_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RoutersClient", + "shortName": "RoutersClient" + }, + "fullName": "google.cloud.compute_v1.RoutersClient.delete", + "method": { + "fullName": "google.cloud.compute.v1.Routers.Delete", + "service": { + "fullName": "google.cloud.compute.v1.Routers", + "shortName": "Routers" + }, + "shortName": "Delete" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.DeleteRouterRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "router", + "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.api_core.extended_operation.ExtendedOperation", + "shortName": "delete" + }, + "description": "Sample for Delete", + "file": "compute_v1_generated_routers_delete_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Routers_Delete_sync", "segments": [ { "end": 53, @@ -68353,7 +68781,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_routers_delete_route_policy_sync.py" + "title": "compute_v1_generated_routers_delete_sync.py" }, { "canonical": true, @@ -68362,19 +68790,19 @@ "fullName": "google.cloud.compute_v1.RoutersClient", "shortName": "RoutersClient" }, - "fullName": "google.cloud.compute_v1.RoutersClient.delete", + "fullName": "google.cloud.compute_v1.RoutersClient.get_named_set", "method": { - "fullName": "google.cloud.compute.v1.Routers.Delete", + "fullName": "google.cloud.compute.v1.Routers.GetNamedSet", "service": { "fullName": "google.cloud.compute.v1.Routers", "shortName": "Routers" }, - "shortName": "Delete" + "shortName": "GetNamedSet" }, "parameters": [ { "name": "request", - "type": "google.cloud.compute_v1.types.DeleteRouterRequest" + "type": "google.cloud.compute_v1.types.GetNamedSetRouterRequest" }, { "name": "project", @@ -68401,14 +68829,14 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.extended_operation.ExtendedOperation", - "shortName": "delete" + "resultType": "google.cloud.compute_v1.types.RoutersGetNamedSetResponse", + "shortName": "get_named_set" }, - "description": "Sample for Delete", - "file": "compute_v1_generated_routers_delete_sync.py", + "description": "Sample for GetNamedSet", + "file": "compute_v1_generated_routers_get_named_set_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "compute_v1_generated_Routers_Delete_sync", + "regionTag": "compute_v1_generated_Routers_GetNamedSet_sync", "segments": [ { "end": 53, @@ -68441,7 +68869,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "compute_v1_generated_routers_delete_sync.py" + "title": "compute_v1_generated_routers_get_named_set_sync.py" }, { "canonical": true, @@ -69059,6 +69487,94 @@ ], "title": "compute_v1_generated_routers_list_bgp_routes_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RoutersClient", + "shortName": "RoutersClient" + }, + "fullName": "google.cloud.compute_v1.RoutersClient.list_named_sets", + "method": { + "fullName": "google.cloud.compute.v1.Routers.ListNamedSets", + "service": { + "fullName": "google.cloud.compute.v1.Routers", + "shortName": "Routers" + }, + "shortName": "ListNamedSets" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.ListNamedSetsRoutersRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "router", + "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_v1.services.routers.pagers.ListNamedSetsPager", + "shortName": "list_named_sets" + }, + "description": "Sample for ListNamedSets", + "file": "compute_v1_generated_routers_list_named_sets_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Routers_ListNamedSets_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_v1_generated_routers_list_named_sets_sync.py" + }, { "canonical": true, "clientMethod": { @@ -69231,6 +69747,98 @@ ], "title": "compute_v1_generated_routers_list_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RoutersClient", + "shortName": "RoutersClient" + }, + "fullName": "google.cloud.compute_v1.RoutersClient.patch_named_set", + "method": { + "fullName": "google.cloud.compute.v1.Routers.PatchNamedSet", + "service": { + "fullName": "google.cloud.compute.v1.Routers", + "shortName": "Routers" + }, + "shortName": "PatchNamedSet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.PatchNamedSetRouterRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "router", + "type": "str" + }, + { + "name": "named_set_resource", + "type": "google.cloud.compute_v1.types.NamedSet" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "patch_named_set" + }, + "description": "Sample for PatchNamedSet", + "file": "compute_v1_generated_routers_patch_named_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Routers_PatchNamedSet_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_routers_patch_named_set_sync.py" + }, { "canonical": true, "clientMethod": { @@ -69507,6 +70115,98 @@ ], "title": "compute_v1_generated_routers_preview_sync.py" }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.compute_v1.RoutersClient", + "shortName": "RoutersClient" + }, + "fullName": "google.cloud.compute_v1.RoutersClient.update_named_set", + "method": { + "fullName": "google.cloud.compute.v1.Routers.UpdateNamedSet", + "service": { + "fullName": "google.cloud.compute.v1.Routers", + "shortName": "Routers" + }, + "shortName": "UpdateNamedSet" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.compute_v1.types.UpdateNamedSetRouterRequest" + }, + { + "name": "project", + "type": "str" + }, + { + "name": "region", + "type": "str" + }, + { + "name": "router", + "type": "str" + }, + { + "name": "named_set_resource", + "type": "google.cloud.compute_v1.types.NamedSet" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.extended_operation.ExtendedOperation", + "shortName": "update_named_set" + }, + "description": "Sample for UpdateNamedSet", + "file": "compute_v1_generated_routers_update_named_set_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "compute_v1_generated_Routers_UpdateNamedSet_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "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": 54, + "start": 51, + "type": "RESPONSE_HANDLING" + } + ], + "title": "compute_v1_generated_routers_update_named_set_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py index e973881bd118..3922a18e6b33 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_backend_services.py @@ -8156,6 +8156,8 @@ def test_insert_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -8870,6 +8872,8 @@ def test_patch_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -10278,6 +10282,8 @@ def test_update_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py index 7160dfe2aabd..3d4f5bbc4870 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_firewall_policies.py @@ -6931,12 +6931,17 @@ def test_add_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -7970,8 +7975,10 @@ def test_get_rule_rest_call_success(request_type): rule_name="rule_name_value", rule_tuple_count=1737, security_profile_group="security_profile_group_value", + target_forwarding_rules=["target_forwarding_rules_value"], target_resources=["target_resources_value"], target_service_accounts=["target_service_accounts_value"], + target_type="target_type_value", tls_inspect=True, ) @@ -7999,8 +8006,10 @@ def test_get_rule_rest_call_success(request_type): assert response.rule_name == "rule_name_value" assert response.rule_tuple_count == 1737 assert response.security_profile_group == "security_profile_group_value" + assert response.target_forwarding_rules == ["target_forwarding_rules_value"] assert response.target_resources == ["target_resources_value"] assert response.target_service_accounts == ["target_service_accounts_value"] + assert response.target_type == "target_type_value" assert response.tls_inspect is True @@ -8180,6 +8189,10 @@ def test_insert_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": [ "target_resources_value1", "target_resources_value2", @@ -8189,6 +8202,7 @@ def test_insert_rest_call_success(request_type): "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } ], @@ -8954,6 +8968,10 @@ def test_patch_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": [ "target_resources_value1", "target_resources_value2", @@ -8963,6 +8981,7 @@ def test_patch_rest_call_success(request_type): "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } ], @@ -9268,12 +9287,17 @@ def test_patch_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py index aaa84c61f17c..a06adf8a664a 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_forwarding_rules.py @@ -1936,6 +1936,8 @@ def test_get_rest_required_fields(request_type=compute.GetForwardingRuleRequest) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1995,7 +1997,7 @@ def test_get_rest_unset_required_fields(): unset_fields = transport.get._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("view",)) & set( ( "forwardingRule", @@ -4703,6 +4705,7 @@ def test_insert_rest_call_success(request_type): "all_ports": True, "allow_global_access": True, "allow_psc_global_access": True, + "attached_extensions": [{"reference": "reference_value"}], "backend_service": "backend_service_value", "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", @@ -5135,6 +5138,7 @@ def test_patch_rest_call_success(request_type): "all_ports": True, "allow_global_access": True, "allow_psc_global_access": True, + "attached_extensions": [{"reference": "reference_value"}], "backend_service": "backend_service_value", "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py index 567a59f044c5..1064d7967464 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_global_forwarding_rules.py @@ -1663,6 +1663,8 @@ def test_get_rest_required_fields(request_type=compute.GetGlobalForwardingRuleRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1720,7 +1722,7 @@ def test_get_rest_unset_required_fields(): unset_fields = transport.get._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("view",)) & set( ( "forwardingRule", @@ -4178,6 +4180,7 @@ def test_insert_rest_call_success(request_type): "all_ports": True, "allow_global_access": True, "allow_psc_global_access": True, + "attached_extensions": [{"reference": "reference_value"}], "backend_service": "backend_service_value", "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", @@ -4604,6 +4607,7 @@ def test_patch_rest_call_success(request_type): "all_ports": True, "allow_global_access": True, "allow_psc_global_access": True, + "attached_extensions": [{"reference": "reference_value"}], "backend_service": "backend_service_value", "base_forwarding_rule": "base_forwarding_rule_value", "creation_timestamp": "creation_timestamp_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py index 902236aa74c6..e8c0ebe54100 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_manager_resize_requests.py @@ -3749,6 +3749,19 @@ def test_insert_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "description": "description_value", "id": 205, + "instances": [ + { + "fingerprint": "fingerprint_value", + "name": "name_value", + "preserved_state": { + "disks": {}, + "external_i_ps": {}, + "internal_i_ps": {}, + "metadata": {}, + }, + "status": "status_value", + } + ], "kind": "kind_value", "name": "name_value", "region": "region_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py index f42eb8ceb534..6a45d7f84c19 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_group_managers.py @@ -2873,7 +2873,12 @@ def test_delete_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2933,7 +2938,12 @@ def test_delete_rest_unset_required_fields(): unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -3082,7 +3092,12 @@ def test_delete_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3142,7 +3157,12 @@ def test_delete_unary_rest_unset_required_fields(): unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -3293,7 +3313,12 @@ def test_delete_instances_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3354,7 +3379,12 @@ def test_delete_instances_rest_unset_required_fields(): unset_fields = transport.delete_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -3512,7 +3542,12 @@ def test_delete_instances_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3573,7 +3608,12 @@ def test_delete_instances_unary_rest_unset_required_fields(): unset_fields = transport.delete_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -6875,7 +6915,12 @@ def test_recreate_instances_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).recreate_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6936,7 +6981,12 @@ def test_recreate_instances_rest_unset_required_fields(): unset_fields = transport.recreate_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -7096,7 +7146,12 @@ def test_recreate_instances_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).recreate_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -7157,7 +7212,12 @@ def test_recreate_instances_unary_rest_unset_required_fields(): unset_fields = transport.recreate_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -9535,7 +9595,12 @@ def test_stop_instances_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).stop_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9596,7 +9661,12 @@ def test_stop_instances_rest_unset_required_fields(): unset_fields = transport.stop_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -9752,7 +9822,12 @@ def test_stop_instances_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).stop_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9813,7 +9888,12 @@ def test_stop_instances_unary_rest_unset_required_fields(): unset_fields = transport.stop_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -12799,6 +12879,7 @@ def test_insert_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -13782,6 +13863,7 @@ def test_patch_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py index 8d2e0650e860..cce529d74eae 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instance_templates.py @@ -4111,6 +4111,7 @@ def test_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -4140,6 +4141,7 @@ def test_insert_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py index b3b48b72bcde..430f1cfd8ec0 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_instances.py @@ -21500,6 +21500,7 @@ def test_add_network_interface_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", @@ -22534,6 +22535,7 @@ def test_bulk_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -22563,6 +22565,7 @@ def test_bulk_insert_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", @@ -23586,6 +23589,7 @@ def test_get_rest_call_success(request_type): last_start_timestamp="last_start_timestamp_value", last_stop_timestamp="last_stop_timestamp_value", last_suspended_timestamp="last_suspended_timestamp_value", + local_ssd_encryption_mode="local_ssd_encryption_mode_value", machine_type="machine_type_value", min_cpu_platform="min_cpu_platform_value", name="name_value", @@ -23629,6 +23633,7 @@ def test_get_rest_call_success(request_type): assert response.last_start_timestamp == "last_start_timestamp_value" assert response.last_stop_timestamp == "last_stop_timestamp_value" assert response.last_suspended_timestamp == "last_suspended_timestamp_value" + assert response.local_ssd_encryption_mode == "local_ssd_encryption_mode_value" assert response.machine_type == "machine_type_value" assert response.min_cpu_platform == "min_cpu_platform_value" assert response.name == "name_value" @@ -24627,6 +24632,7 @@ def test_insert_rest_call_success(request_type): "last_start_timestamp": "last_start_timestamp_value", "last_stop_timestamp": "last_stop_timestamp_value", "last_suspended_timestamp": "last_suspended_timestamp_value", + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -24657,6 +24663,7 @@ def test_insert_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", @@ -24706,6 +24713,7 @@ def test_insert_rest_call_success(request_type): }, "physical_host": "physical_host_value", "physical_host_topology": { + "additional_attributes": {"accelerator_topology_ids": {}}, "block": "block_value", "cluster": "cluster_value", "host": "host_value", @@ -30990,6 +30998,7 @@ def test_update_rest_call_success(request_type): "last_start_timestamp": "last_start_timestamp_value", "last_stop_timestamp": "last_stop_timestamp_value", "last_suspended_timestamp": "last_suspended_timestamp_value", + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -31020,6 +31029,7 @@ def test_update_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", @@ -31069,6 +31079,7 @@ def test_update_rest_call_success(request_type): }, "physical_host": "physical_host_value", "physical_host_topology": { + "additional_attributes": {"accelerator_topology_ids": {}}, "block": "block_value", "cluster": "cluster_value", "host": "host_value", @@ -31891,6 +31902,7 @@ def test_update_network_interface_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py index 7ea0234d6b5b..aa11fb4c9f4f 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_interconnects.py @@ -3885,6 +3885,7 @@ def test_get_rest_call_success(request_type): creation_timestamp="creation_timestamp_value", customer_name="customer_name_value", description="description_value", + effective_location="effective_location_value", google_ip_address="google_ip_address_value", google_reference_id="google_reference_id_value", id=205, @@ -3931,6 +3932,7 @@ def test_get_rest_call_success(request_type): assert response.creation_timestamp == "creation_timestamp_value" assert response.customer_name == "customer_name_value" assert response.description == "description_value" + assert response.effective_location == "effective_location_value" assert response.google_ip_address == "google_ip_address_value" assert response.google_reference_id == "google_reference_id_value" assert response.id == 205 @@ -4349,6 +4351,7 @@ def test_insert_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "customer_name": "customer_name_value", "description": "description_value", + "effective_location": "effective_location_value", "expected_outages": [ { "affected_circuits": [ @@ -4800,6 +4803,7 @@ def test_patch_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "customer_name": "customer_name_value", "description": "description_value", + "effective_location": "effective_location_value", "expected_outages": [ { "affected_circuits": [ diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py index 6af9533658ab..da57e24c29b3 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_machine_images.py @@ -4082,6 +4082,7 @@ def test_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -4111,6 +4112,7 @@ def test_insert_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py index d1ad5b1c1fd8..3095d4648af9 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_network_firewall_policies.py @@ -8668,12 +8668,17 @@ def test_add_packet_mirroring_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -8976,12 +8981,17 @@ def test_add_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -10168,8 +10178,10 @@ def test_get_packet_mirroring_rule_rest_call_success(request_type): rule_name="rule_name_value", rule_tuple_count=1737, security_profile_group="security_profile_group_value", + target_forwarding_rules=["target_forwarding_rules_value"], target_resources=["target_resources_value"], target_service_accounts=["target_service_accounts_value"], + target_type="target_type_value", tls_inspect=True, ) @@ -10197,8 +10209,10 @@ def test_get_packet_mirroring_rule_rest_call_success(request_type): assert response.rule_name == "rule_name_value" assert response.rule_tuple_count == 1737 assert response.security_profile_group == "security_profile_group_value" + assert response.target_forwarding_rules == ["target_forwarding_rules_value"] assert response.target_resources == ["target_resources_value"] assert response.target_service_accounts == ["target_service_accounts_value"] + assert response.target_type == "target_type_value" assert response.tls_inspect is True @@ -10325,8 +10339,10 @@ def test_get_rule_rest_call_success(request_type): rule_name="rule_name_value", rule_tuple_count=1737, security_profile_group="security_profile_group_value", + target_forwarding_rules=["target_forwarding_rules_value"], target_resources=["target_resources_value"], target_service_accounts=["target_service_accounts_value"], + target_type="target_type_value", tls_inspect=True, ) @@ -10354,8 +10370,10 @@ def test_get_rule_rest_call_success(request_type): assert response.rule_name == "rule_name_value" assert response.rule_tuple_count == 1737 assert response.security_profile_group == "security_profile_group_value" + assert response.target_forwarding_rules == ["target_forwarding_rules_value"] assert response.target_resources == ["target_resources_value"] assert response.target_service_accounts == ["target_service_accounts_value"] + assert response.target_type == "target_type_value" assert response.tls_inspect is True @@ -10538,6 +10556,10 @@ def test_insert_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": [ "target_resources_value1", "target_resources_value2", @@ -10547,6 +10569,7 @@ def test_insert_rest_call_success(request_type): "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } ], @@ -11007,6 +11030,10 @@ def test_patch_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": [ "target_resources_value1", "target_resources_value2", @@ -11016,6 +11043,7 @@ def test_patch_rest_call_success(request_type): "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } ], @@ -11322,12 +11350,17 @@ def test_patch_packet_mirroring_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -11632,12 +11665,17 @@ def test_patch_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py index 7a83ebe21671..b23297899266 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_organization_security_policies.py @@ -7532,7 +7532,11 @@ def test_insert_rest_call_success(request_type): } ], "creation_timestamp": "creation_timestamp_value", - "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "ddos_protection_config": { + "ddos_adaptive_protection": "ddos_adaptive_protection_value", + "ddos_impacted_baseline_threshold": 0.33580000000000004, + "ddos_protection": "ddos_protection_value", + }, "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, @@ -8559,7 +8563,11 @@ def test_patch_rest_call_success(request_type): } ], "creation_timestamp": "creation_timestamp_value", - "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "ddos_protection_config": { + "ddos_adaptive_protection": "ddos_adaptive_protection_value", + "ddos_impacted_baseline_threshold": 0.33580000000000004, + "ddos_protection": "ddos_protection_value", + }, "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py index 4943eb9a971f..d3ba6c8a3165 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_backend_services.py @@ -5924,6 +5924,8 @@ def test_insert_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -6649,6 +6651,8 @@ def test_patch_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, @@ -7824,6 +7828,8 @@ def test_update_rest_call_success(request_type): "locality_lb_policy": "locality_lb_policy_value", "log_config": { "enable": True, + "logging_http_request_headers": [{"header_name": "header_name_value"}], + "logging_http_response_headers": {}, "optional_fields": ["optional_fields_value1", "optional_fields_value2"], "optional_mode": "optional_mode_value", "sample_rate": 0.1165, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_manager_resize_requests.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_manager_resize_requests.py index 8e839d227e0c..5f3f59c660d3 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_manager_resize_requests.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_manager_resize_requests.py @@ -3756,6 +3756,19 @@ def test_insert_rest_call_success(request_type): "creation_timestamp": "creation_timestamp_value", "description": "description_value", "id": 205, + "instances": [ + { + "fingerprint": "fingerprint_value", + "name": "name_value", + "preserved_state": { + "disks": {}, + "external_i_ps": {}, + "internal_i_ps": {}, + "metadata": {}, + }, + "status": "status_value", + } + ], "kind": "kind_value", "name": "name_value", "region": "region_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py index 445c48863029..32bb0e35ccc1 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_group_managers.py @@ -2631,7 +2631,12 @@ def test_delete_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2691,7 +2696,12 @@ def test_delete_rest_unset_required_fields(): unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -2840,7 +2850,12 @@ def test_delete_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2900,7 +2915,12 @@ def test_delete_unary_rest_unset_required_fields(): unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -3051,7 +3071,12 @@ def test_delete_instances_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3112,7 +3137,12 @@ def test_delete_instances_rest_unset_required_fields(): unset_fields = transport.delete_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -3270,7 +3300,12 @@ def test_delete_instances_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).delete_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3331,7 +3366,12 @@ def test_delete_instances_unary_rest_unset_required_fields(): unset_fields = transport.delete_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -6642,7 +6682,12 @@ def test_recreate_instances_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).recreate_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6703,7 +6748,12 @@ def test_recreate_instances_rest_unset_required_fields(): unset_fields = transport.recreate_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -6863,7 +6913,12 @@ def test_recreate_instances_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).recreate_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -6924,7 +6979,12 @@ def test_recreate_instances_unary_rest_unset_required_fields(): unset_fields = transport.recreate_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -9302,7 +9362,12 @@ def test_stop_instances_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).stop_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9363,7 +9428,12 @@ def test_stop_instances_rest_unset_required_fields(): unset_fields = transport.stop_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -9519,7 +9589,12 @@ def test_stop_instances_unary_rest_required_fields( credentials=ga_credentials.AnonymousCredentials() ).stop_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "no_graceful_shutdown", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -9580,7 +9655,12 @@ def test_stop_instances_unary_rest_unset_required_fields(): unset_fields = transport.stop_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "noGracefulShutdown", + "requestId", + ) + ) & set( ( "instanceGroupManager", @@ -12438,6 +12518,7 @@ def test_insert_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", @@ -13434,6 +13515,7 @@ def test_patch_rest_call_success(request_type): "default_action_on_failure": "default_action_on_failure_value", "force_update_on_repair": "force_update_on_repair_value", "on_failed_health_check": "on_failed_health_check_value", + "on_repair": {"allow_changing_zone": "allow_changing_zone_value"}, }, "instance_template": "instance_template_value", "kind": "kind_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py index 7d6ba027f45b..0e6ce70e4b0d 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instance_templates.py @@ -3058,6 +3058,7 @@ def test_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -3087,6 +3088,7 @@ def test_insert_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py index 00f1ed6062cd..2c27d4d71a17 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_instances.py @@ -1794,6 +1794,7 @@ def test_bulk_insert_rest_call_success(request_type): ], "key_revocation_action_type": "key_revocation_action_type_value", "labels": {}, + "local_ssd_encryption_mode": "local_ssd_encryption_mode_value", "machine_type": "machine_type_value", "metadata": { "fingerprint": "fingerprint_value", @@ -1823,6 +1824,7 @@ def test_bulk_insert_rest_call_success(request_type): "subnetwork_range_name": "subnetwork_range_name_value", } ], + "alias_ipv6_ranges": {}, "enable_vpc_scoped_dns": True, "fingerprint": "fingerprint_value", "igmp_query": "igmp_query_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py index 112631102b51..c3cb1826fead 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_network_firewall_policies.py @@ -7431,12 +7431,17 @@ def test_add_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. @@ -8673,8 +8678,10 @@ def test_get_rule_rest_call_success(request_type): rule_name="rule_name_value", rule_tuple_count=1737, security_profile_group="security_profile_group_value", + target_forwarding_rules=["target_forwarding_rules_value"], target_resources=["target_resources_value"], target_service_accounts=["target_service_accounts_value"], + target_type="target_type_value", tls_inspect=True, ) @@ -8702,8 +8709,10 @@ def test_get_rule_rest_call_success(request_type): assert response.rule_name == "rule_name_value" assert response.rule_tuple_count == 1737 assert response.security_profile_group == "security_profile_group_value" + assert response.target_forwarding_rules == ["target_forwarding_rules_value"] assert response.target_resources == ["target_resources_value"] assert response.target_service_accounts == ["target_service_accounts_value"] + assert response.target_type == "target_type_value" assert response.tls_inspect is True @@ -8886,6 +8895,10 @@ def test_insert_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": [ "target_resources_value1", "target_resources_value2", @@ -8895,6 +8908,7 @@ def test_insert_rest_call_success(request_type): "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } ], @@ -9368,6 +9382,10 @@ def test_patch_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": [ "target_resources_value1", "target_resources_value2", @@ -9377,6 +9395,7 @@ def test_patch_rest_call_success(request_type): "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } ], @@ -9691,12 +9710,17 @@ def test_patch_rule_rest_call_success(request_type): "rule_name": "rule_name_value", "rule_tuple_count": 1737, "security_profile_group": "security_profile_group_value", + "target_forwarding_rules": [ + "target_forwarding_rules_value1", + "target_forwarding_rules_value2", + ], "target_resources": ["target_resources_value1", "target_resources_value2"], "target_secure_tags": {}, "target_service_accounts": [ "target_service_accounts_value1", "target_service_accounts_value2", ], + "target_type": "target_type_value", "tls_inspect": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py index 443c57cbb65b..145acb5936ce 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_security_policies.py @@ -5976,7 +5976,11 @@ def test_insert_rest_call_success(request_type): } ], "creation_timestamp": "creation_timestamp_value", - "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "ddos_protection_config": { + "ddos_adaptive_protection": "ddos_adaptive_protection_value", + "ddos_impacted_baseline_threshold": 0.33580000000000004, + "ddos_protection": "ddos_protection_value", + }, "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, @@ -6540,7 +6544,11 @@ def test_patch_rest_call_success(request_type): } ], "creation_timestamp": "creation_timestamp_value", - "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "ddos_protection_config": { + "ddos_adaptive_protection": "ddos_adaptive_protection_value", + "ddos_impacted_baseline_threshold": 0.33580000000000004, + "ddos_protection": "ddos_protection_value", + }, "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py index 2a122535a134..4984fc39b3db 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_region_target_tcp_proxies.py @@ -2832,6 +2832,7 @@ def test_get_rest_call_success(request_type): description="description_value", id=205, kind="kind_value", + load_balancing_scheme="load_balancing_scheme_value", name="name_value", proxy_bind=True, proxy_header="proxy_header_value", @@ -2858,6 +2859,7 @@ def test_get_rest_call_success(request_type): assert response.description == "description_value" assert response.id == 205 assert response.kind == "kind_value" + assert response.load_balancing_scheme == "load_balancing_scheme_value" assert response.name == "name_value" assert response.proxy_bind is True assert response.proxy_header == "proxy_header_value" @@ -2975,6 +2977,7 @@ def test_insert_rest_call_success(request_type): "description": "description_value", "id": 205, "kind": "kind_value", + "load_balancing_scheme": "load_balancing_scheme_value", "name": "name_value", "proxy_bind": True, "proxy_header": "proxy_header_value", diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py index 4ee3dfeae184..280f73440884 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_rollouts.py @@ -1121,7 +1121,7 @@ def test_rollouts_client_client_options_credentials_file( ) -def test_cancel_rest_use_cached_wrapped_rpc(): +def test_advance_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: @@ -1135,17 +1135,17 @@ def test_cancel_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.cancel in client._transport._wrapped_methods + assert client._transport.advance 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.cancel] = mock_rpc + client._transport._wrapped_methods[client._transport.advance] = mock_rpc request = {} - client.cancel(request) + client.advance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1154,14 +1154,14 @@ def test_cancel_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.cancel(request) + client.advance(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_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): +def test_advance_rest_required_fields(request_type=compute.AdvanceRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1177,7 +1177,7 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1187,12 +1187,12 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "current_wave_number", "request_id", - "rollback", ) ) jsonified_request.update(unset_fields) @@ -1222,7 +1222,7 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1238,24 +1238,24 @@ def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.cancel(request) + response = client.advance(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_cancel_rest_unset_required_fields(): +def test_advance_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.cancel._get_unset_required_fields({}) + unset_fields = transport.advance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( + "currentWaveNumber", "requestId", - "rollback", ) ) & set( @@ -1267,7 +1267,7 @@ def test_cancel_rest_unset_required_fields(): ) -def test_cancel_rest_flattened(): +def test_advance_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1298,20 +1298,20 @@ def test_cancel_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel(**mock_args) + client.advance(**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/v1/projects/{project}/global/rollouts/{rollout}" + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}/advance" % client.transport._host, args[1], ) -def test_cancel_rest_flattened_error(transport: str = "rest"): +def test_advance_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1320,14 +1320,14 @@ def test_cancel_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.cancel( - compute.CancelRolloutRequest(), + client.advance( + compute.AdvanceRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_cancel_unary_rest_use_cached_wrapped_rpc(): +def test_advance_unary_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: @@ -1341,17 +1341,17 @@ def test_cancel_unary_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.cancel in client._transport._wrapped_methods + assert client._transport.advance 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.cancel] = mock_rpc + client._transport._wrapped_methods[client._transport.advance] = mock_rpc request = {} - client.cancel_unary(request) + client.advance_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1360,14 +1360,14 @@ def test_cancel_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.cancel_unary(request) + client.advance_unary(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_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutRequest): +def test_advance_unary_rest_required_fields(request_type=compute.AdvanceRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1383,7 +1383,7 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1393,12 +1393,12 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).cancel._get_unset_required_fields(jsonified_request) + ).advance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( + "current_wave_number", "request_id", - "rollback", ) ) jsonified_request.update(unset_fields) @@ -1428,7 +1428,7 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1444,24 +1444,24 @@ def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutReq req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.cancel_unary(request) + response = client.advance_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_cancel_unary_rest_unset_required_fields(): +def test_advance_unary_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.cancel._get_unset_required_fields({}) + unset_fields = transport.advance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( + "currentWaveNumber", "requestId", - "rollback", ) ) & set( @@ -1473,7 +1473,7 @@ def test_cancel_unary_rest_unset_required_fields(): ) -def test_cancel_unary_rest_flattened(): +def test_advance_unary_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1504,20 +1504,20 @@ def test_cancel_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_unary(**mock_args) + client.advance_unary(**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/v1/projects/{project}/global/rollouts/{rollout}" + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}/advance" % client.transport._host, args[1], ) -def test_cancel_unary_rest_flattened_error(transport: str = "rest"): +def test_advance_unary_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1526,14 +1526,14 @@ def test_cancel_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.cancel_unary( - compute.CancelRolloutRequest(), + client.advance_unary( + compute.AdvanceRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_delete_rest_use_cached_wrapped_rpc(): +def test_cancel_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: @@ -1547,17 +1547,17 @@ def test_delete_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete in client._transport._wrapped_methods + assert client._transport.cancel 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.delete] = mock_rpc + client._transport._wrapped_methods[client._transport.cancel] = mock_rpc request = {} - client.delete(request) + client.cancel(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1566,14 +1566,14 @@ def test_delete_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete(request) + client.cancel(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_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): +def test_cancel_rest_required_fields(request_type=compute.CancelRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1589,7 +1589,7 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1599,9 +1599,14 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1629,7 +1634,7 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1645,21 +1650,26 @@ def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete(request) + response = client.cancel(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_rest_unset_required_fields(): +def test_cancel_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete._get_unset_required_fields({}) + unset_fields = transport.cancel._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "requestId", + "rollback", + ) + ) & set( ( "project", @@ -1669,7 +1679,7 @@ def test_delete_rest_unset_required_fields(): ) -def test_delete_rest_flattened(): +def test_cancel_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1700,7 +1710,7 @@ def test_delete_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete(**mock_args) + client.cancel(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -1713,7 +1723,7 @@ def test_delete_rest_flattened(): ) -def test_delete_rest_flattened_error(transport: str = "rest"): +def test_cancel_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1722,14 +1732,14 @@ def test_delete_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete( - compute.DeleteRolloutRequest(), + client.cancel( + compute.CancelRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_delete_unary_rest_use_cached_wrapped_rpc(): +def test_cancel_unary_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: @@ -1743,17 +1753,17 @@ def test_delete_unary_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete in client._transport._wrapped_methods + assert client._transport.cancel 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.delete] = mock_rpc + client._transport._wrapped_methods[client._transport.cancel] = mock_rpc request = {} - client.delete_unary(request) + client.cancel_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1762,14 +1772,14 @@ def test_delete_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_unary(request) + client.cancel_unary(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_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutRequest): +def test_cancel_unary_rest_required_fields(request_type=compute.CancelRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1785,7 +1795,7 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1795,9 +1805,14 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete._get_unset_required_fields(jsonified_request) + ).cancel._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "request_id", + "rollback", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -1825,7 +1840,7 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "patch", "query_params": pb_request, } transcode.return_value = transcode_result @@ -1841,21 +1856,26 @@ def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutReq req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_unary(request) + response = client.cancel_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_unary_rest_unset_required_fields(): +def test_cancel_unary_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete._get_unset_required_fields({}) + unset_fields = transport.cancel._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "requestId", + "rollback", + ) + ) & set( ( "project", @@ -1865,7 +1885,7 @@ def test_delete_unary_rest_unset_required_fields(): ) -def test_delete_unary_rest_flattened(): +def test_cancel_unary_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1896,7 +1916,7 @@ def test_delete_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_unary(**mock_args) + client.cancel_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -1909,7 +1929,7 @@ def test_delete_unary_rest_flattened(): ) -def test_delete_unary_rest_flattened_error(transport: str = "rest"): +def test_cancel_unary_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -1918,14 +1938,14 @@ def test_delete_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_unary( - compute.DeleteRolloutRequest(), + client.cancel_unary( + compute.CancelRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_get_rest_use_cached_wrapped_rpc(): +def test_delete_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: @@ -1939,29 +1959,33 @@ def test_get_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get in client._transport._wrapped_methods + assert client._transport.delete 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 + client._transport._wrapped_methods[client._transport.delete] = mock_rpc request = {} - client.get(request) + client.delete(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete(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.GetRolloutRequest): +def test_delete_rest_required_fields(request_type=compute.DeleteRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} @@ -1977,7 +2001,7 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get._get_unset_required_fields(jsonified_request) + ).delete._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1987,7 +2011,9 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get._get_unset_required_fields(jsonified_request) + ).delete._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2003,7 +2029,7 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Rollout() + return_value = compute.Operation() # 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 @@ -2015,7 +2041,7 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result @@ -2024,28 +2050,28 @@ def test_get_rest_required_fields(request_type=compute.GetRolloutRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Rollout.pb(return_value) + return_value = compute.Operation.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) + response = client.delete(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_rest_unset_required_fields(): +def test_delete_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get._get_unset_required_fields({}) + unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("requestId",)) & set( ( "project", @@ -2055,7 +2081,7 @@ def test_get_rest_unset_required_fields(): ) -def test_get_rest_flattened(): +def test_delete_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2064,7 +2090,7 @@ def test_get_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Rollout() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "rollout": "sample2"} @@ -2080,13 +2106,13 @@ def test_get_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Rollout.pb(return_value) + return_value = compute.Operation.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) + client.delete(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -2099,7 +2125,7 @@ def test_get_rest_flattened(): ) -def test_get_rest_flattened_error(transport: str = "rest"): +def test_delete_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2108,14 +2134,14 @@ def test_get_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get( - compute.GetRolloutRequest(), + client.delete( + compute.DeleteRolloutRequest(), project="project_value", rollout="rollout_value", ) -def test_list_rest_use_cached_wrapped_rpc(): +def test_delete_unary_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: @@ -2129,33 +2155,38 @@ def test_list_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list in client._transport._wrapped_methods + assert client._transport.delete 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 + client._transport._wrapped_methods[client._transport.delete] = mock_rpc request = {} - client.list(request) + client.delete_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_unary(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.ListRolloutsRequest): +def test_delete_unary_rest_required_fields(request_type=compute.DeleteRolloutRequest): transport_class = transports.RolloutsRestTransport request_init = {} request_init["project"] = "" + request_init["rollout"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -2166,31 +2197,26 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list._get_unset_required_fields(jsonified_request) + ).delete._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list._get_unset_required_fields(jsonified_request) + ).delete._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", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2199,7 +2225,7 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RolloutsListResponse() + return_value = compute.Operation() # 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 @@ -2211,7 +2237,7 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "delete", "query_params": pb_request, } transcode.return_value = transcode_result @@ -2220,41 +2246,38 @@ def test_list_rest_required_fields(request_type=compute.ListRolloutsRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RolloutsListResponse.pb(return_value) + return_value = compute.Operation.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) + response = client.delete_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_rest_unset_required_fields(): +def test_delete_unary_rest_unset_required_fields(): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list._get_unset_required_fields({}) + unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(("requestId",)) + & set( ( - "filter", - "maxResults", - "orderBy", - "pageToken", - "returnPartialSuccess", + "project", + "rollout", ) ) - & set(("project",)) ) -def test_list_rest_flattened(): +def test_delete_unary_rest_flattened(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2263,14 +2286,15 @@ def test_list_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RolloutsListResponse() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method - sample_request = {"project": "sample1"} + sample_request = {"project": "sample1", "rollout": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", + rollout="rollout_value", ) mock_args.update(sample_request) @@ -2278,25 +2302,26 @@ def test_list_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RolloutsListResponse.pb(return_value) + return_value = compute.Operation.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) + client.delete_unary(**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/v1/projects/{project}/global/rollouts" % client.transport._host, - args[1], + "%s/compute/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], ) -def test_list_rest_flattened_error(transport: str = "rest"): +def test_delete_unary_rest_flattened_error(transport: str = "rest"): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2305,164 +2330,2009 @@ def test_list_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list( - compute.ListRolloutsRequest(), + client.delete_unary( + compute.DeleteRolloutRequest(), project="project_value", + rollout="rollout_value", ) -def test_list_rest_pager(transport: str = "rest"): +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 = RolloutsClient( + 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.GetRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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["project"] = "project_value" + jsonified_request["rollout"] = "rollout_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) + request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = compute.Rollout() # 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.RolloutsListResponse( - items=[ - compute.Rollout(), - compute.Rollout(), - compute.Rollout(), - ], - next_page_token="abc", - ), - compute.RolloutsListResponse( - items=[], - next_page_token="def", - ), - compute.RolloutsListResponse( - items=[ - compute.Rollout(), - ], - next_page_token="ghi", - ), - compute.RolloutsListResponse( - items=[ - compute.Rollout(), - compute.Rollout(), - ], - ), + # 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.Rollout.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 sorted(expected_params) == sorted(actual_params) + + +def test_get_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "rollout", + ) ) - # Two responses for two calls - response = response + response + ) - # Wrap the values into proper Response objs - response = tuple(compute.RolloutsListResponse.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"} +def test_get_rest_flattened(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - pager = client.list(request=sample_request) + # 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.Rollout() - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, compute.Rollout) for i in results) + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_value", + ) + mock_args.update(sample_request) - 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 + # 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.Rollout.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/v1/projects/{project}/global/rollouts/{rollout}" + % client.transport._host, + args[1], + ) + + +def test_get_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.GetRolloutRequest(), + project="project_value", + rollout="rollout_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 = RolloutsClient( + 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.ListRolloutsRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + 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["project"] = "project_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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RolloutsListResponse() + # 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.RolloutsListResponse.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 sorted(expected_params) == sorted(actual_params) + + +def test_list_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) + & set(("project",)) + ) + + +def test_list_rest_flattened(): + client = RolloutsClient( + 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.RolloutsListResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_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.RolloutsListResponse.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/v1/projects/{project}/global/rollouts" % client.transport._host, + args[1], + ) + + +def test_list_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.ListRolloutsRequest(), + project="project_value", + ) + + +def test_list_rest_pager(transport: str = "rest"): + client = RolloutsClient( + 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.RolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + compute.Rollout(), + ], + next_page_token="abc", + ), + compute.RolloutsListResponse( + items=[], + next_page_token="def", + ), + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + ], + next_page_token="ghi", + ), + compute.RolloutsListResponse( + items=[ + compute.Rollout(), + compute.Rollout(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RolloutsListResponse.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"} + + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.Rollout) 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_pause_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 = RolloutsClient( + 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.pause 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.pause] = mock_rpc + + request = {} + client.pause(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.pause(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_pause_rest_required_fields(request_type=compute.PauseRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).pause._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.pause(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_pause_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.pause._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_pause_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.pause(**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/v1/projects/{project}/global/rollouts/{rollout}/pause" + % client.transport._host, + args[1], + ) + + +def test_pause_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.pause( + compute.PauseRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_pause_unary_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 = RolloutsClient( + 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.pause 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.pause] = mock_rpc + + request = {} + client.pause_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.pause_unary(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_pause_unary_rest_required_fields(request_type=compute.PauseRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).pause._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).pause._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.pause_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_pause_unary_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.pause._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_pause_unary_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.pause_unary(**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/v1/projects/{project}/global/rollouts/{rollout}/pause" + % client.transport._host, + args[1], + ) + + +def test_pause_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.pause_unary( + compute.PauseRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_resume_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 = RolloutsClient( + 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.resume 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.resume] = mock_rpc + + request = {} + client.resume(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.resume(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_resume_rest_required_fields(request_type=compute.ResumeRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).resume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.resume(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_resume_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resume._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_resume_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.resume(**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/v1/projects/{project}/global/rollouts/{rollout}/resume" + % client.transport._host, + args[1], + ) + + +def test_resume_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.resume( + compute.ResumeRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_resume_unary_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 = RolloutsClient( + 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.resume 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.resume] = mock_rpc + + request = {} + client.resume_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.resume_unary(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_resume_unary_rest_required_fields(request_type=compute.ResumeRolloutRequest): + transport_class = transports.RolloutsRestTransport + + request_init = {} + request_init["project"] = "" + request_init["rollout"] = "" + 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() + ).resume._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["rollout"] = "rollout_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).resume._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "rollout" in jsonified_request + assert jsonified_request["rollout"] == "rollout_value" + + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.resume_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_resume_unary_rest_unset_required_fields(): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.resume._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "requestId", + ) + ) + & set( + ( + "project", + "rollout", + ) + ) + ) + + +def test_resume_unary_rest_flattened(): + client = RolloutsClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = {"project": "sample1", "rollout": "sample2"} + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + rollout="rollout_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.Operation.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.resume_unary(**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/v1/projects/{project}/global/rollouts/{rollout}/resume" + % client.transport._host, + args[1], + ) + + +def test_resume_unary_rest_flattened_error(transport: str = "rest"): + client = RolloutsClient( + 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.resume_unary( + compute.ResumeRolloutRequest(), + project="project_value", + rollout="rollout_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RolloutsClient( + 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 = RolloutsClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RolloutsClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RolloutsClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RolloutsRestTransport, + ], +) +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 = RolloutsClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_advance_rest_bad_request(request_type=compute.AdvanceRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.advance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AdvanceRolloutRequest, + dict, + ], +) +def test_advance_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.advance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_advance_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(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.RolloutsRestInterceptor, "post_advance") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_advance_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_advance") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AdvanceRolloutRequest.pb(compute.AdvanceRolloutRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.AdvanceRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.advance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.cancel(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.CancelRolloutRequest, + dict, + ], +) +def test_cancel_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.cancel(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_cancel_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(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.RolloutsRestInterceptor, "post_cancel") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_cancel_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_cancel") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.CancelRolloutRequest.pb(compute.CancelRolloutRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.CancelRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.cancel( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRolloutRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RolloutsRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + ) + client = RolloutsClient(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.RolloutsRestInterceptor, "post_delete") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_delete") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRolloutRequest.pb(compute.DeleteRolloutRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRolloutRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - with pytest.raises(ValueError): - client = RolloutsClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RolloutsClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "rollout": "sample2"} + request = request_type(**request_init) - # It is an error to provide an api_key and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RolloutsClient( - client_options=options, - transport=transport, + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.Rollout( + cancellation_time="cancellation_time_value", + completion_time="completion_time_value", + creation_timestamp="creation_timestamp_value", + current_wave_number=2045, + description="description_value", + etag="etag_value", + id=205, + kind="kind_value", + name="name_value", + pause_time="pause_time_value", + resume_time="resume_time_value", + rollout_plan="rollout_plan_value", + self_link="self_link_value", + self_link_with_id="self_link_with_id_value", + state="state_value", ) - # 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 = RolloutsClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - # It is an error to provide scopes and a transport instance. - transport = transports.RolloutsRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RolloutsClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, - ) + # Convert return value to protobuf type + return_value = compute.Rollout.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.Rollout) + assert response.cancellation_time == "cancellation_time_value" + assert response.completion_time == "completion_time_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.current_wave_number == 2045 + assert response.description == "description_value" + assert response.etag == "etag_value" + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.pause_time == "pause_time_value" + assert response.resume_time == "resume_time_value" + assert response.rollout_plan == "rollout_plan_value" + assert response.self_link == "self_link_value" + assert response.self_link_with_id == "self_link_with_id_value" + assert response.state == "state_value" -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), ) client = RolloutsClient(transport=transport) - assert client.transport is transport + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RolloutsRestInterceptor, "post_get") as post, + mock.patch.object( + transports.RolloutsRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRolloutRequest.pb(compute.GetRolloutRequest()) + 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.Rollout.to_json(compute.Rollout()) + req.return_value.content = return_value -@pytest.mark.parametrize( - "transport_class", - [ - transports.RolloutsRestTransport, - ], -) -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() + request = compute.GetRolloutRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Rollout() + post_with_metadata.return_value = compute.Rollout(), metadata + client.get( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) -def test_transport_kind_rest(): - transport = RolloutsClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): +def test_list_rest_bad_request(request_type=compute.ListRolloutsRequest): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "rollout": "sample2"} + request_init = {"project": "sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -2478,51 +4348,34 @@ def test_cancel_rest_bad_request(request_type=compute.CancelRolloutRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel(request) + client.list(request) @pytest.mark.parametrize( "request_type", [ - compute.CancelRolloutRequest, + compute.ListRolloutsRequest, dict, ], ) -def test_cancel_rest_call_success(request_type): +def test_list_rest_call_success(request_type): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "rollout": "sample2"} + request_init = {"project": "sample1"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation( - client_operation_id="client_operation_id_value", - creation_timestamp="creation_timestamp_value", - description="description_value", - end_time="end_time_value", - http_error_message="http_error_message_value", - http_error_status_code=2374, - id=205, - insert_time="insert_time_value", - kind="kind_value", - name="name_value", - operation_group_id="operation_group_id_value", - operation_type="operation_type_value", - progress=885, - region="region_value", + return_value = compute.RolloutsListResponse( + etag="etag_value", + id="id_value", + next_page_token="next_page_token_value", self_link="self_link_value", - start_time="start_time_value", - status=compute.Operation.Status.DONE, - status_message="status_message_value", - target_id=947, - target_link="target_link_value", - user="user_value", - zone="zone_value", + unreachables=["unreachables_value"], ) # Wrap the value into a proper Response obj @@ -2530,41 +4383,24 @@ def test_cancel_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RolloutsListResponse.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.cancel(request) + response = client.list(request) # Establish that the response is the type that we expect. - assert isinstance(response, extended_operation.ExtendedOperation) - assert response.client_operation_id == "client_operation_id_value" - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.end_time == "end_time_value" - assert response.http_error_message == "http_error_message_value" - assert response.http_error_status_code == 2374 - assert response.id == 205 - assert response.insert_time == "insert_time_value" - assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.operation_group_id == "operation_group_id_value" - assert response.operation_type == "operation_type_value" - assert response.progress == 885 - assert response.region == "region_value" + assert isinstance(response, pagers.ListPager) + assert response.etag == "etag_value" + assert response.id == "id_value" + assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" - assert response.start_time == "start_time_value" - assert response.status == compute.Operation.Status.DONE - assert response.status_message == "status_message_value" - assert response.target_id == 947 - assert response.target_link == "target_link_value" - assert response.user == "user_value" - assert response.zone == "zone_value" + assert response.unreachables == ["unreachables_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_cancel_rest_interceptors(null_interceptor): +def test_list_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), @@ -2574,16 +4410,16 @@ def test_cancel_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RolloutsRestInterceptor, "post_cancel") as post, + mock.patch.object(transports.RolloutsRestInterceptor, "post_list") as post, mock.patch.object( - transports.RolloutsRestInterceptor, "post_cancel_with_metadata" + transports.RolloutsRestInterceptor, "post_list_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_cancel") as pre, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_list") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.CancelRolloutRequest.pb(compute.CancelRolloutRequest()) + pb_message = compute.ListRolloutsRequest.pb(compute.ListRolloutsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2594,19 +4430,21 @@ def test_cancel_rest_interceptors(null_interceptor): 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.Operation.to_json(compute.Operation()) + return_value = compute.RolloutsListResponse.to_json( + compute.RolloutsListResponse() + ) req.return_value.content = return_value - request = compute.CancelRolloutRequest() + request = compute.ListRolloutsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Operation() - post_with_metadata.return_value = compute.Operation(), metadata + post.return_value = compute.RolloutsListResponse() + post_with_metadata.return_value = compute.RolloutsListResponse(), metadata - client.cancel( + client.list( request, metadata=[ ("key", "val"), @@ -2619,7 +4457,7 @@ def test_cancel_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): +def test_pause_rest_bad_request(request_type=compute.PauseRolloutRequest): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2640,17 +4478,17 @@ def test_delete_rest_bad_request(request_type=compute.DeleteRolloutRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete(request) + client.pause(request) @pytest.mark.parametrize( "request_type", [ - compute.DeleteRolloutRequest, + compute.PauseRolloutRequest, dict, ], ) -def test_delete_rest_call_success(request_type): +def test_pause_rest_call_success(request_type): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2697,7 +4535,7 @@ def test_delete_rest_call_success(request_type): 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.delete(request) + response = client.pause(request) # Establish that the response is the type that we expect. assert isinstance(response, extended_operation.ExtendedOperation) @@ -2726,7 +4564,7 @@ def test_delete_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_rest_interceptors(null_interceptor): +def test_pause_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), @@ -2736,16 +4574,16 @@ def test_delete_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RolloutsRestInterceptor, "post_delete") as post, + mock.patch.object(transports.RolloutsRestInterceptor, "post_pause") as post, mock.patch.object( - transports.RolloutsRestInterceptor, "post_delete_with_metadata" + transports.RolloutsRestInterceptor, "post_pause_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_delete") as pre, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_pause") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.DeleteRolloutRequest.pb(compute.DeleteRolloutRequest()) + pb_message = compute.PauseRolloutRequest.pb(compute.PauseRolloutRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2759,7 +4597,7 @@ def test_delete_rest_interceptors(null_interceptor): return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.DeleteRolloutRequest() + request = compute.PauseRolloutRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -2768,7 +4606,7 @@ def test_delete_rest_interceptors(null_interceptor): post.return_value = compute.Operation() post_with_metadata.return_value = compute.Operation(), metadata - client.delete( + client.pause( request, metadata=[ ("key", "val"), @@ -2781,7 +4619,7 @@ def test_delete_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): +def test_resume_rest_bad_request(request_type=compute.ResumeRolloutRequest): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2802,17 +4640,17 @@ def test_get_rest_bad_request(request_type=compute.GetRolloutRequest): 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) + client.resume(request) @pytest.mark.parametrize( "request_type", [ - compute.GetRolloutRequest, + compute.ResumeRolloutRequest, dict, ], ) -def test_get_rest_call_success(request_type): +def test_resume_rest_call_success(request_type): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -2824,20 +4662,29 @@ def test_get_rest_call_success(request_type): # 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.Rollout( - cancellation_time="cancellation_time_value", - completion_time="completion_time_value", + return_value = compute.Operation( + client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", - current_wave_number=2045, description="description_value", - etag="etag_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, id=205, + insert_time="insert_time_value", kind="kind_value", name="name_value", - rollout_plan="rollout_plan_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", self_link="self_link_value", - self_link_with_id="self_link_with_id_value", - state="state_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", ) # Wrap the value into a proper Response obj @@ -2845,32 +4692,41 @@ def test_get_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Rollout.pb(return_value) + return_value = compute.Operation.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) + response = client.resume(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.Rollout) - assert response.cancellation_time == "cancellation_time_value" - assert response.completion_time == "completion_time_value" + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" - assert response.current_wave_number == 2045 assert response.description == "description_value" - assert response.etag == "etag_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 assert response.id == 205 + assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" - assert response.rollout_plan == "rollout_plan_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" assert response.self_link == "self_link_value" - assert response.self_link_with_id == "self_link_with_id_value" - assert response.state == "state_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_rest_interceptors(null_interceptor): +def test_resume_rest_interceptors(null_interceptor): transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), @@ -2880,16 +4736,16 @@ def test_get_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RolloutsRestInterceptor, "post_get") as post, + mock.patch.object(transports.RolloutsRestInterceptor, "post_resume") as post, mock.patch.object( - transports.RolloutsRestInterceptor, "post_get_with_metadata" + transports.RolloutsRestInterceptor, "post_resume_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_get") as pre, + mock.patch.object(transports.RolloutsRestInterceptor, "pre_resume") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetRolloutRequest.pb(compute.GetRolloutRequest()) + pb_message = compute.ResumeRolloutRequest.pb(compute.ResumeRolloutRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -2900,19 +4756,19 @@ def test_get_rest_interceptors(null_interceptor): 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.Rollout.to_json(compute.Rollout()) + return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.GetRolloutRequest() + request = compute.ResumeRolloutRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Rollout() - post_with_metadata.return_value = compute.Rollout(), metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata - client.get( + client.resume( request, metadata=[ ("key", "val"), @@ -2925,141 +4781,30 @@ def test_get_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_rest_bad_request(request_type=compute.ListRolloutsRequest): +def test_initialize_client_w_rest(): client = RolloutsClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = 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) + assert client is not None -@pytest.mark.parametrize( - "request_type", - [ - compute.ListRolloutsRequest, - dict, - ], -) -def test_list_rest_call_success(request_type): +# 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_advance_unary_empty_call_rest(): client = RolloutsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"project": "sample1"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = compute.RolloutsListResponse( - etag="etag_value", - id="id_value", - next_page_token="next_page_token_value", - self_link="self_link_value", - unreachables=["unreachables_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.RolloutsListResponse.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.etag == "etag_value" - assert response.id == "id_value" - assert response.next_page_token == "next_page_token_value" - assert response.self_link == "self_link_value" - assert response.unreachables == ["unreachables_value"] - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_rest_interceptors(null_interceptor): - transport = transports.RolloutsRestTransport( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RolloutsRestInterceptor(), + transport="rest", ) - client = RolloutsClient(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.RolloutsRestInterceptor, "post_list") as post, - mock.patch.object( - transports.RolloutsRestInterceptor, "post_list_with_metadata" - ) as post_with_metadata, - mock.patch.object(transports.RolloutsRestInterceptor, "pre_list") as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = compute.ListRolloutsRequest.pb(compute.ListRolloutsRequest()) - 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.RolloutsListResponse.to_json( - compute.RolloutsListResponse() - ) - req.return_value.content = return_value - - request = compute.ListRolloutsRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = compute.RolloutsListResponse() - post_with_metadata.return_value = compute.RolloutsListResponse(), metadata - - client.list( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.advance), "__call__") as call: + client.advance_unary(request=None) -def test_initialize_client_w_rest(): - client = RolloutsClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - assert client is not None + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.AdvanceRolloutRequest() + assert args[0] == request_msg # This test is a coverage failsafe to make sure that totally empty calls, @@ -3138,6 +4883,44 @@ def test_list_empty_call_rest(): 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_pause_unary_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.pause), "__call__") as call: + client.pause_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PauseRolloutRequest() + 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_resume_unary_empty_call_rest(): + client = RolloutsClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.resume), "__call__") as call: + client.resume_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ResumeRolloutRequest() + assert args[0] == request_msg + + def test_rollouts_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): @@ -3160,10 +4943,13 @@ def test_rollouts_base_transport(): # Every method on the transport should just blindly # raise NotImplementedError. methods = ( + "advance", "cancel", "delete", "get", "list", + "pause", + "resume", ) for method in methods: with pytest.raises(NotImplementedError): @@ -3307,6 +5093,9 @@ def test_rollouts_client_transport_session_collision(transport_name): credentials=creds2, transport=transport_name, ) + session1 = client1.transport.advance._session + session2 = client2.transport.advance._session + assert session1 != session2 session1 = client1.transport.cancel._session session2 = client2.transport.cancel._session assert session1 != session2 @@ -3319,6 +5108,12 @@ def test_rollouts_client_transport_session_collision(transport_name): session1 = client1.transport.list._session session2 = client2.transport.list._session assert session1 != session2 + session1 = client1.transport.pause._session + session2 = client2.transport.pause._session + assert session1 != session2 + session1 = client1.transport.resume._session + session2 = client2.transport.resume._session + assert session1 != session2 def test_common_billing_account_path(): diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py index 5ff3f0608385..fe114325d479 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_routers.py @@ -1802,7 +1802,7 @@ def test_delete_unary_rest_flattened_error(transport: str = "rest"): ) -def test_delete_route_policy_rest_use_cached_wrapped_rpc(): +def test_delete_named_set_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: @@ -1816,21 +1816,19 @@ def test_delete_route_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_route_policy in client._transport._wrapped_methods - ) + assert client._transport.delete_named_set 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.delete_route_policy] = ( + client._transport._wrapped_methods[client._transport.delete_named_set] = ( mock_rpc ) request = {} - client.delete_route_policy(request) + client.delete_named_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -1839,15 +1837,15 @@ def test_delete_route_policy_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_route_policy(request) + client.delete_named_set(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_delete_route_policy_rest_required_fields( - request_type=compute.DeleteRoutePolicyRouterRequest, +def test_delete_named_set_rest_required_fields( + request_type=compute.DeleteNamedSetRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -1865,7 +1863,7 @@ def test_delete_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_route_policy._get_unset_required_fields(jsonified_request) + ).delete_named_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -1876,11 +1874,11 @@ def test_delete_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_route_policy._get_unset_required_fields(jsonified_request) + ).delete_named_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "policy", + "named_set", "request_id", ) ) @@ -1929,23 +1927,23 @@ def test_delete_route_policy_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_route_policy(request) + response = client.delete_named_set(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_route_policy_rest_unset_required_fields(): +def test_delete_named_set_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_route_policy._get_unset_required_fields({}) + unset_fields = transport.delete_named_set._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "policy", + "namedSet", "requestId", ) ) @@ -1959,7 +1957,7 @@ def test_delete_route_policy_rest_unset_required_fields(): ) -def test_delete_route_policy_rest_flattened(): +def test_delete_named_set_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -1995,20 +1993,20 @@ def test_delete_route_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_route_policy(**mock_args) + client.delete_named_set(**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/v1/projects/{project}/regions/{region}/routers/{router}/deleteRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/deleteNamedSet" % client.transport._host, args[1], ) -def test_delete_route_policy_rest_flattened_error(transport: str = "rest"): +def test_delete_named_set_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2017,15 +2015,15 @@ def test_delete_route_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_route_policy( - compute.DeleteRoutePolicyRouterRequest(), + client.delete_named_set( + compute.DeleteNamedSetRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_delete_route_policy_unary_rest_use_cached_wrapped_rpc(): +def test_delete_named_set_unary_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: @@ -2039,21 +2037,19 @@ def test_delete_route_policy_unary_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.delete_route_policy in client._transport._wrapped_methods - ) + assert client._transport.delete_named_set 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.delete_route_policy] = ( + client._transport._wrapped_methods[client._transport.delete_named_set] = ( mock_rpc ) request = {} - client.delete_route_policy_unary(request) + client.delete_named_set_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -2062,15 +2058,15 @@ def test_delete_route_policy_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_route_policy_unary(request) + client.delete_named_set_unary(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_delete_route_policy_unary_rest_required_fields( - request_type=compute.DeleteRoutePolicyRouterRequest, +def test_delete_named_set_unary_rest_required_fields( + request_type=compute.DeleteNamedSetRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -2088,7 +2084,7 @@ def test_delete_route_policy_unary_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_route_policy._get_unset_required_fields(jsonified_request) + ).delete_named_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -2099,11 +2095,11 @@ def test_delete_route_policy_unary_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_route_policy._get_unset_required_fields(jsonified_request) + ).delete_named_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "policy", + "named_set", "request_id", ) ) @@ -2152,23 +2148,23 @@ def test_delete_route_policy_unary_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.delete_route_policy_unary(request) + response = client.delete_named_set_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_route_policy_unary_rest_unset_required_fields(): +def test_delete_named_set_unary_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_route_policy._get_unset_required_fields({}) + unset_fields = transport.delete_named_set._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "policy", + "namedSet", "requestId", ) ) @@ -2182,7 +2178,7 @@ def test_delete_route_policy_unary_rest_unset_required_fields(): ) -def test_delete_route_policy_unary_rest_flattened(): +def test_delete_named_set_unary_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2218,20 +2214,20 @@ def test_delete_route_policy_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_route_policy_unary(**mock_args) + client.delete_named_set_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/deleteRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/deleteNamedSet" % client.transport._host, args[1], ) -def test_delete_route_policy_unary_rest_flattened_error(transport: str = "rest"): +def test_delete_named_set_unary_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2240,15 +2236,15 @@ def test_delete_route_policy_unary_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_route_policy_unary( - compute.DeleteRoutePolicyRouterRequest(), + client.delete_named_set_unary( + compute.DeleteNamedSetRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_get_rest_use_cached_wrapped_rpc(): +def test_delete_route_policy_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: @@ -2262,29 +2258,39 @@ def test_get_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get in client._transport._wrapped_methods + assert ( + client._transport.delete_route_policy 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 + client._transport._wrapped_methods[client._transport.delete_route_policy] = ( + mock_rpc + ) request = {} - client.get(request) + client.delete_route_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_route_policy(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.GetRouterRequest): +def test_delete_route_policy_rest_required_fields( + request_type=compute.DeleteRoutePolicyRouterRequest, +): transport_class = transports.RoutersRestTransport request_init = {} @@ -2301,7 +2307,7 @@ def test_get_rest_required_fields(request_type=compute.GetRouterRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get._get_unset_required_fields(jsonified_request) + ).delete_route_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -2312,7 +2318,14 @@ def test_get_rest_required_fields(request_type=compute.GetRouterRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get._get_unset_required_fields(jsonified_request) + ).delete_route_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "policy", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2330,7 +2343,7 @@ def test_get_rest_required_fields(request_type=compute.GetRouterRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Router() + return_value = compute.Operation() # 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 @@ -2342,7 +2355,7 @@ def test_get_rest_required_fields(request_type=compute.GetRouterRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } transcode.return_value = transcode_result @@ -2351,28 +2364,33 @@ def test_get_rest_required_fields(request_type=compute.GetRouterRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Router.pb(return_value) + return_value = compute.Operation.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) + response = client.delete_route_policy(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_rest_unset_required_fields(): +def test_delete_route_policy_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get._get_unset_required_fields({}) + unset_fields = transport.delete_route_policy._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set( + ( + "policy", + "requestId", + ) + ) & set( ( "project", @@ -2383,7 +2401,7 @@ def test_get_rest_unset_required_fields(): ) -def test_get_rest_flattened(): +def test_delete_route_policy_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2392,7 +2410,7 @@ def test_get_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Router() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method sample_request = { @@ -2413,26 +2431,26 @@ def test_get_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Router.pb(return_value) + return_value = compute.Operation.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) + client.delete_route_policy(**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/v1/projects/{project}/regions/{region}/routers/{router}" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/deleteRoutePolicy" % client.transport._host, args[1], ) -def test_get_rest_flattened_error(transport: str = "rest"): +def test_delete_route_policy_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2441,15 +2459,15 @@ def test_get_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get( - compute.GetRouterRequest(), + client.delete_route_policy( + compute.DeleteRoutePolicyRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_get_nat_ip_info_rest_use_cached_wrapped_rpc(): +def test_delete_route_policy_unary_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: @@ -2463,30 +2481,38 @@ def test_get_nat_ip_info_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_nat_ip_info in client._transport._wrapped_methods + assert ( + client._transport.delete_route_policy 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_nat_ip_info] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_route_policy] = ( + mock_rpc + ) request = {} - client.get_nat_ip_info(request) + client.delete_route_policy_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_nat_ip_info(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_route_policy_unary(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_nat_ip_info_rest_required_fields( - request_type=compute.GetNatIpInfoRouterRequest, +def test_delete_route_policy_unary_rest_required_fields( + request_type=compute.DeleteRoutePolicyRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -2504,7 +2530,7 @@ def test_get_nat_ip_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_nat_ip_info._get_unset_required_fields(jsonified_request) + ).delete_route_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -2515,9 +2541,14 @@ def test_get_nat_ip_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_nat_ip_info._get_unset_required_fields(jsonified_request) + ).delete_route_policy._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("nat_name",)) + assert not set(unset_fields) - set( + ( + "policy", + "request_id", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2535,7 +2566,7 @@ def test_get_nat_ip_info_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.NatIpInfoResponse() + return_value = compute.Operation() # 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 @@ -2547,7 +2578,7 @@ def test_get_nat_ip_info_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } transcode.return_value = transcode_result @@ -2556,28 +2587,33 @@ def test_get_nat_ip_info_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.NatIpInfoResponse.pb(return_value) + return_value = compute.Operation.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_nat_ip_info(request) + response = client.delete_route_policy_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_nat_ip_info_rest_unset_required_fields(): +def test_delete_route_policy_unary_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_nat_ip_info._get_unset_required_fields({}) + unset_fields = transport.delete_route_policy._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("natName",)) + set( + ( + "policy", + "requestId", + ) + ) & set( ( "project", @@ -2588,7 +2624,7 @@ def test_get_nat_ip_info_rest_unset_required_fields(): ) -def test_get_nat_ip_info_rest_flattened(): +def test_delete_route_policy_unary_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2597,7 +2633,7 @@ def test_get_nat_ip_info_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.NatIpInfoResponse() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method sample_request = { @@ -2618,26 +2654,26 @@ def test_get_nat_ip_info_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.NatIpInfoResponse.pb(return_value) + return_value = compute.Operation.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_nat_ip_info(**mock_args) + client.delete_route_policy_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/getNatIpInfo" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/deleteRoutePolicy" % client.transport._host, args[1], ) -def test_get_nat_ip_info_rest_flattened_error(transport: str = "rest"): +def test_delete_route_policy_unary_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2646,15 +2682,15 @@ def test_get_nat_ip_info_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_nat_ip_info( - compute.GetNatIpInfoRouterRequest(), + client.delete_route_policy_unary( + compute.DeleteRoutePolicyRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_get_nat_mapping_info_rest_use_cached_wrapped_rpc(): +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: @@ -2668,35 +2704,29 @@ def test_get_nat_mapping_info_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_nat_mapping_info in client._transport._wrapped_methods - ) + 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_nat_mapping_info] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get] = mock_rpc request = {} - client.get_nat_mapping_info(request) + client.get(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_nat_mapping_info(request) + 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_nat_mapping_info_rest_required_fields( - request_type=compute.GetNatMappingInfoRoutersRequest, -): +def test_get_rest_required_fields(request_type=compute.GetRouterRequest): transport_class = transports.RoutersRestTransport request_init = {} @@ -2713,7 +2743,7 @@ def test_get_nat_mapping_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_nat_mapping_info._get_unset_required_fields(jsonified_request) + ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -2724,18 +2754,7 @@ def test_get_nat_mapping_info_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_nat_mapping_info._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", - "nat_name", - "order_by", - "page_token", - "return_partial_success", - ) - ) + ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -2753,7 +2772,7 @@ def test_get_nat_mapping_info_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.VmEndpointNatMappingsList() + return_value = compute.Router() # 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 @@ -2774,37 +2793,28 @@ def test_get_nat_mapping_info_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.VmEndpointNatMappingsList.pb(return_value) + return_value = compute.Router.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_nat_mapping_info(request) + response = client.get(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_nat_mapping_info_rest_unset_required_fields(): +def test_get_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_nat_mapping_info._get_unset_required_fields({}) + unset_fields = transport.get._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "filter", - "maxResults", - "natName", - "orderBy", - "pageToken", - "returnPartialSuccess", - ) - ) + set(()) & set( ( "project", @@ -2815,7 +2825,7 @@ def test_get_nat_mapping_info_rest_unset_required_fields(): ) -def test_get_nat_mapping_info_rest_flattened(): +def test_get_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -2824,7 +2834,7 @@ def test_get_nat_mapping_info_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.VmEndpointNatMappingsList() + return_value = compute.Router() # get arguments that satisfy an http rule for this method sample_request = { @@ -2845,26 +2855,26 @@ def test_get_nat_mapping_info_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.VmEndpointNatMappingsList.pb(return_value) + return_value = compute.Router.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_nat_mapping_info(**mock_args) + 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/v1/projects/{project}/regions/{region}/routers/{router}/getNatMappingInfo" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}" % client.transport._host, args[1], ) -def test_get_nat_mapping_info_rest_flattened_error(transport: str = "rest"): +def test_get_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2873,83 +2883,15 @@ def test_get_nat_mapping_info_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_nat_mapping_info( - compute.GetNatMappingInfoRoutersRequest(), + client.get( + compute.GetRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_get_nat_mapping_info_rest_pager(transport: str = "rest"): - client = RoutersClient( - 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.VmEndpointNatMappingsList( - result=[ - compute.VmEndpointNatMappings(), - compute.VmEndpointNatMappings(), - compute.VmEndpointNatMappings(), - ], - next_page_token="abc", - ), - compute.VmEndpointNatMappingsList( - result=[], - next_page_token="def", - ), - compute.VmEndpointNatMappingsList( - result=[ - compute.VmEndpointNatMappings(), - ], - next_page_token="ghi", - ), - compute.VmEndpointNatMappingsList( - result=[ - compute.VmEndpointNatMappings(), - compute.VmEndpointNatMappings(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(compute.VmEndpointNatMappingsList.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", - "router": "sample3", - } - - pager = client.get_nat_mapping_info(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, compute.VmEndpointNatMappings) for i in results) - - pages = list(client.get_nat_mapping_info(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_get_route_policy_rest_use_cached_wrapped_rpc(): +def test_get_named_set_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: @@ -2963,32 +2905,30 @@ def test_get_route_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_route_policy in client._transport._wrapped_methods + assert client._transport.get_named_set 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_route_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_named_set] = mock_rpc request = {} - client.get_route_policy(request) + client.get_named_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_route_policy(request) + client.get_named_set(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_route_policy_rest_required_fields( - request_type=compute.GetRoutePolicyRouterRequest, +def test_get_named_set_rest_required_fields( + request_type=compute.GetNamedSetRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -3006,7 +2946,7 @@ def test_get_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_route_policy._get_unset_required_fields(jsonified_request) + ).get_named_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -3017,9 +2957,9 @@ def test_get_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_route_policy._get_unset_required_fields(jsonified_request) + ).get_named_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("policy",)) + assert not set(unset_fields) - set(("named_set",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3037,7 +2977,7 @@ def test_get_route_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RoutersGetRoutePolicyResponse() + return_value = compute.RoutersGetNamedSetResponse() # 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 @@ -3058,28 +2998,28 @@ def test_get_route_policy_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersGetRoutePolicyResponse.pb(return_value) + return_value = compute.RoutersGetNamedSetResponse.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_route_policy(request) + response = client.get_named_set(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_route_policy_rest_unset_required_fields(): +def test_get_named_set_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_route_policy._get_unset_required_fields({}) + unset_fields = transport.get_named_set._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("policy",)) + set(("namedSet",)) & set( ( "project", @@ -3090,7 +3030,7 @@ def test_get_route_policy_rest_unset_required_fields(): ) -def test_get_route_policy_rest_flattened(): +def test_get_named_set_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3099,7 +3039,7 @@ def test_get_route_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RoutersGetRoutePolicyResponse() + return_value = compute.RoutersGetNamedSetResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -3120,26 +3060,26 @@ def test_get_route_policy_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersGetRoutePolicyResponse.pb(return_value) + return_value = compute.RoutersGetNamedSetResponse.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_route_policy(**mock_args) + client.get_named_set(**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/v1/projects/{project}/regions/{region}/routers/{router}/getRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/getNamedSet" % client.transport._host, args[1], ) -def test_get_route_policy_rest_flattened_error(transport: str = "rest"): +def test_get_named_set_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3148,15 +3088,15 @@ def test_get_route_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_route_policy( - compute.GetRoutePolicyRouterRequest(), + client.get_named_set( + compute.GetNamedSetRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_get_router_status_rest_use_cached_wrapped_rpc(): +def test_get_nat_ip_info_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3170,32 +3110,30 @@ def test_get_router_status_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_router_status in client._transport._wrapped_methods + assert client._transport.get_nat_ip_info in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_router_status] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_nat_ip_info] = mock_rpc request = {} - client.get_router_status(request) + client.get_nat_ip_info(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_router_status(request) + client.get_nat_ip_info(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_get_router_status_rest_required_fields( - request_type=compute.GetRouterStatusRouterRequest, +def test_get_nat_ip_info_rest_required_fields( + request_type=compute.GetNatIpInfoRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -3213,7 +3151,7 @@ def test_get_router_status_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_router_status._get_unset_required_fields(jsonified_request) + ).get_nat_ip_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -3224,7 +3162,9 @@ def test_get_router_status_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_router_status._get_unset_required_fields(jsonified_request) + ).get_nat_ip_info._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("nat_name",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3242,7 +3182,7 @@ def test_get_router_status_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RouterStatusResponse() + return_value = compute.NatIpInfoResponse() # 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 @@ -3263,28 +3203,28 @@ def test_get_router_status_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RouterStatusResponse.pb(return_value) + return_value = compute.NatIpInfoResponse.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_router_status(request) + response = client.get_nat_ip_info(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_router_status_rest_unset_required_fields(): +def test_get_nat_ip_info_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_router_status._get_unset_required_fields({}) + unset_fields = transport.get_nat_ip_info._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("natName",)) & set( ( "project", @@ -3295,7 +3235,7 @@ def test_get_router_status_rest_unset_required_fields(): ) -def test_get_router_status_rest_flattened(): +def test_get_nat_ip_info_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3304,7 +3244,7 @@ def test_get_router_status_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RouterStatusResponse() + return_value = compute.NatIpInfoResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -3325,26 +3265,26 @@ def test_get_router_status_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RouterStatusResponse.pb(return_value) + return_value = compute.NatIpInfoResponse.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_router_status(**mock_args) + client.get_nat_ip_info(**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/v1/projects/{project}/regions/{region}/routers/{router}/getRouterStatus" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/getNatIpInfo" % client.transport._host, args[1], ) -def test_get_router_status_rest_flattened_error(transport: str = "rest"): +def test_get_nat_ip_info_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3353,15 +3293,15 @@ def test_get_router_status_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_router_status( - compute.GetRouterStatusRouterRequest(), + client.get_nat_ip_info( + compute.GetNatIpInfoRouterRequest(), project="project_value", region="region_value", router="router_value", ) -def test_insert_rest_use_cached_wrapped_rpc(): +def test_get_nat_mapping_info_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3375,38 +3315,41 @@ def test_insert_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.insert in client._transport._wrapped_methods + assert ( + client._transport.get_nat_mapping_info in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.insert] = mock_rpc + client._transport._wrapped_methods[client._transport.get_nat_mapping_info] = ( + mock_rpc + ) request = {} - client.insert(request) + client.get_nat_mapping_info(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.insert(request) + client.get_nat_mapping_info(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_insert_rest_required_fields(request_type=compute.InsertRouterRequest): +def test_get_nat_mapping_info_rest_required_fields( + request_type=compute.GetNatMappingInfoRoutersRequest, +): transport_class = transports.RoutersRestTransport request_init = {} request_init["project"] = "" request_init["region"] = "" + request_init["router"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3417,19 +3360,29 @@ def test_insert_rest_required_fields(request_type=compute.InsertRouterRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).insert._get_unset_required_fields(jsonified_request) + ).get_nat_mapping_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).insert._get_unset_required_fields(jsonified_request) + ).get_nat_mapping_info._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "filter", + "max_results", + "nat_name", + "order_by", + "page_token", + "return_partial_success", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3437,6 +3390,8 @@ def test_insert_rest_required_fields(request_type=compute.InsertRouterRequest): assert jsonified_request["project"] == "project_value" assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3445,7 +3400,7 @@ def test_insert_rest_required_fields(request_type=compute.InsertRouterRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.VmEndpointNatMappingsList() # 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 @@ -3457,49 +3412,57 @@ def test_insert_rest_required_fields(request_type=compute.InsertRouterRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.VmEndpointNatMappingsList.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.insert(request) + response = client.get_nat_mapping_info(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_insert_rest_unset_required_fields(): +def test_get_nat_mapping_info_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.insert._get_unset_required_fields({}) + unset_fields = transport.get_nat_mapping_info._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "filter", + "maxResults", + "natName", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) & set( ( "project", "region", - "routerResource", + "router", ) ) ) -def test_insert_rest_flattened(): +def test_get_nat_mapping_info_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3508,18 +3471,20 @@ def test_insert_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.VmEndpointNatMappingsList() # get arguments that satisfy an http rule for this method - sample_request = {"project": "sample1", "region": "sample2"} + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } # get truthy value for each flattened field mock_args = dict( project="project_value", region="region_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), + router="router_value", ) mock_args.update(sample_request) @@ -3527,26 +3492,26 @@ def test_insert_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.VmEndpointNatMappingsList.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.insert(**mock_args) + client.get_nat_mapping_info(**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/v1/projects/{project}/regions/{region}/routers" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/getNatMappingInfo" % client.transport._host, args[1], ) -def test_insert_rest_flattened_error(transport: str = "rest"): +def test_get_nat_mapping_info_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3555,62 +3520,129 @@ def test_insert_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.insert( - compute.InsertRouterRequest(), + client.get_nat_mapping_info( + compute.GetNatMappingInfoRoutersRequest(), project="project_value", region="region_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), - ) - - -def test_insert_unary_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 = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + router="router_value", ) - # 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.insert in client._transport._wrapped_methods +def test_get_nat_mapping_info_rest_pager(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Replace cached wrapped function with mock + # 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.VmEndpointNatMappingsList( + result=[ + compute.VmEndpointNatMappings(), + compute.VmEndpointNatMappings(), + compute.VmEndpointNatMappings(), + ], + next_page_token="abc", + ), + compute.VmEndpointNatMappingsList( + result=[], + next_page_token="def", + ), + compute.VmEndpointNatMappingsList( + result=[ + compute.VmEndpointNatMappings(), + ], + next_page_token="ghi", + ), + compute.VmEndpointNatMappingsList( + result=[ + compute.VmEndpointNatMappings(), + compute.VmEndpointNatMappings(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.VmEndpointNatMappingsList.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", + "router": "sample3", + } + + pager = client.get_nat_mapping_info(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.VmEndpointNatMappings) for i in results) + + pages = list(client.get_nat_mapping_info(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_route_policy_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 = RoutersClient( + 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_route_policy 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.insert] = mock_rpc + client._transport._wrapped_methods[client._transport.get_route_policy] = ( + mock_rpc + ) request = {} - client.insert_unary(request) + client.get_route_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.insert_unary(request) + client.get_route_policy(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_insert_unary_rest_required_fields(request_type=compute.InsertRouterRequest): +def test_get_route_policy_rest_required_fields( + request_type=compute.GetRoutePolicyRouterRequest, +): transport_class = transports.RoutersRestTransport request_init = {} request_init["project"] = "" request_init["region"] = "" + request_init["router"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3621,19 +3653,20 @@ def test_insert_unary_rest_required_fields(request_type=compute.InsertRouterRequ unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).insert._get_unset_required_fields(jsonified_request) + ).get_route_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).insert._get_unset_required_fields(jsonified_request) + ).get_route_policy._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set(("policy",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3641,6 +3674,8 @@ def test_insert_unary_rest_required_fields(request_type=compute.InsertRouterRequ assert jsonified_request["project"] == "project_value" assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3649,7 +3684,7 @@ def test_insert_unary_rest_required_fields(request_type=compute.InsertRouterRequ request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersGetRoutePolicyResponse() # 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 @@ -3661,49 +3696,48 @@ def test_insert_unary_rest_required_fields(request_type=compute.InsertRouterRequ pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersGetRoutePolicyResponse.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.insert_unary(request) + response = client.get_route_policy(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_insert_unary_rest_unset_required_fields(): +def test_get_route_policy_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.insert._get_unset_required_fields({}) + unset_fields = transport.get_route_policy._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set(("policy",)) & set( ( "project", "region", - "routerResource", + "router", ) ) ) -def test_insert_unary_rest_flattened(): +def test_get_route_policy_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3712,18 +3746,20 @@ def test_insert_unary_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersGetRoutePolicyResponse() # get arguments that satisfy an http rule for this method - sample_request = {"project": "sample1", "region": "sample2"} + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } # get truthy value for each flattened field mock_args = dict( project="project_value", region="region_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), + router="router_value", ) mock_args.update(sample_request) @@ -3731,26 +3767,26 @@ def test_insert_unary_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersGetRoutePolicyResponse.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.insert_unary(**mock_args) + client.get_route_policy(**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/v1/projects/{project}/regions/{region}/routers" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/getRoutePolicy" % client.transport._host, args[1], ) -def test_insert_unary_rest_flattened_error(transport: str = "rest"): +def test_get_route_policy_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3759,17 +3795,15 @@ def test_insert_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.insert_unary( - compute.InsertRouterRequest(), + client.get_route_policy( + compute.GetRoutePolicyRouterRequest(), project="project_value", region="region_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), + router="router_value", ) -def test_list_rest_use_cached_wrapped_rpc(): +def test_get_router_status_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: @@ -3783,34 +3817,39 @@ def test_list_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list in client._transport._wrapped_methods + assert client._transport.get_router_status 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 + client._transport._wrapped_methods[client._transport.get_router_status] = ( + mock_rpc + ) request = {} - client.list(request) + client.get_router_status(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list(request) + client.get_router_status(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.ListRoutersRequest): +def test_get_router_status_rest_required_fields( + request_type=compute.GetRouterStatusRouterRequest, +): transport_class = transports.RoutersRestTransport request_init = {} request_init["project"] = "" request_init["region"] = "" + request_init["router"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -3821,27 +3860,18 @@ def test_list_rest_required_fields(request_type=compute.ListRoutersRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list._get_unset_required_fields(jsonified_request) + ).get_router_status._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_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", - ) - ) + ).get_router_status._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -3849,6 +3879,8 @@ def test_list_rest_required_fields(request_type=compute.ListRoutersRequest): assert jsonified_request["project"] == "project_value" assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3857,7 +3889,7 @@ def test_list_rest_required_fields(request_type=compute.ListRoutersRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RouterList() + return_value = compute.RouterStatusResponse() # 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 @@ -3878,46 +3910,39 @@ def test_list_rest_required_fields(request_type=compute.ListRoutersRequest): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RouterList.pb(return_value) + return_value = compute.RouterStatusResponse.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) + response = client.get_router_status(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_rest_unset_required_fields(): +def test_get_router_status_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list._get_unset_required_fields({}) + unset_fields = transport.get_router_status._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "filter", - "maxResults", - "orderBy", - "pageToken", - "returnPartialSuccess", - ) - ) + set(()) & set( ( "project", "region", + "router", ) ) ) -def test_list_rest_flattened(): +def test_get_router_status_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -3926,15 +3951,20 @@ def test_list_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RouterList() + return_value = compute.RouterStatusResponse() # get arguments that satisfy an http rule for this method - sample_request = {"project": "sample1", "region": "sample2"} + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } # get truthy value for each flattened field mock_args = dict( project="project_value", region="region_value", + router="router_value", ) mock_args.update(sample_request) @@ -3942,26 +3972,26 @@ def test_list_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RouterList.pb(return_value) + return_value = compute.RouterStatusResponse.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) + client.get_router_status(**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/v1/projects/{project}/regions/{region}/routers" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/getRouterStatus" % client.transport._host, args[1], ) -def test_list_rest_flattened_error(transport: str = "rest"): +def test_get_router_status_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3970,122 +4000,60 @@ def test_list_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list( - compute.ListRoutersRequest(), + client.get_router_status( + compute.GetRouterStatusRouterRequest(), project="project_value", region="region_value", + router="router_value", ) -def test_list_rest_pager(transport: str = "rest"): - client = RoutersClient( - 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.RouterList( - items=[ - compute.Router(), - compute.Router(), - compute.Router(), - ], - next_page_token="abc", - ), - compute.RouterList( - items=[], - next_page_token="def", - ), - compute.RouterList( - items=[ - compute.Router(), - ], - next_page_token="ghi", - ), - compute.RouterList( - items=[ - compute.Router(), - compute.Router(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(compute.RouterList.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"} - - pager = client.list(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, compute.Router) 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_list_bgp_routes_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 = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +def test_insert_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 = RoutersClient( + 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_bgp_routes in client._transport._wrapped_methods + assert client._transport.insert 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_bgp_routes] = mock_rpc + client._transport._wrapped_methods[client._transport.insert] = mock_rpc request = {} - client.list_bgp_routes(request) + client.insert(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_bgp_routes(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert(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_bgp_routes_rest_required_fields( - request_type=compute.ListBgpRoutesRoutersRequest, -): +def test_insert_rest_required_fields(request_type=compute.InsertRouterRequest): transport_class = transports.RoutersRestTransport request_init = {} request_init["project"] = "" request_init["region"] = "" - request_init["router"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4096,33 +4064,19 @@ def test_list_bgp_routes_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_bgp_routes._get_unset_required_fields(jsonified_request) + ).insert._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["region"] = "region_value" - jsonified_request["router"] = "router_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_bgp_routes._get_unset_required_fields(jsonified_request) + ).insert._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "address_family", - "destination_prefix", - "filter", - "max_results", - "order_by", - "page_token", - "peer", - "policy_applied", - "return_partial_success", - "route_type", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4130,8 +4084,6 @@ def test_list_bgp_routes_rest_required_fields( assert jsonified_request["project"] == "project_value" assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" - assert "router" in jsonified_request - assert jsonified_request["router"] == "router_value" client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4140,7 +4092,7 @@ def test_list_bgp_routes_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RoutersListBgpRoutes() + return_value = compute.Operation() # 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 @@ -4152,61 +4104,49 @@ def test_list_bgp_routes_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersListBgpRoutes.pb(return_value) + return_value = compute.Operation.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_bgp_routes(request) + response = client.insert(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_bgp_routes_rest_unset_required_fields(): +def test_insert_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_bgp_routes._get_unset_required_fields({}) + unset_fields = transport.insert._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "addressFamily", - "destinationPrefix", - "filter", - "maxResults", - "orderBy", - "pageToken", - "peer", - "policyApplied", - "returnPartialSuccess", - "routeType", - ) - ) + set(("requestId",)) & set( ( "project", "region", - "router", + "routerResource", ) ) ) -def test_list_bgp_routes_rest_flattened(): +def test_insert_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4215,20 +4155,18 @@ def test_list_bgp_routes_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RoutersListBgpRoutes() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method - sample_request = { - "project": "sample1", - "region": "sample2", - "router": "sample3", - } + sample_request = {"project": "sample1", "region": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", region="region_value", - router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") + ), ) mock_args.update(sample_request) @@ -4236,26 +4174,26 @@ def test_list_bgp_routes_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersListBgpRoutes.pb(return_value) + return_value = compute.Operation.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_bgp_routes(**mock_args) + client.insert(**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/v1/projects/{project}/regions/{region}/routers/{router}/listBgpRoutes" + "%s/compute/v1/projects/{project}/regions/{region}/routers" % client.transport._host, args[1], ) -def test_list_bgp_routes_rest_flattened_error(transport: str = "rest"): +def test_insert_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4264,83 +4202,17 @@ def test_list_bgp_routes_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_bgp_routes( - compute.ListBgpRoutesRoutersRequest(), + client.insert( + compute.InsertRouterRequest(), project="project_value", region="region_value", - router="router_value", - ) - - -def test_list_bgp_routes_rest_pager(transport: str = "rest"): - client = RoutersClient( - 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.RoutersListBgpRoutes( - result=[ - compute.BgpRoute(), - compute.BgpRoute(), - compute.BgpRoute(), - ], - next_page_token="abc", - ), - compute.RoutersListBgpRoutes( - result=[], - next_page_token="def", - ), - compute.RoutersListBgpRoutes( - result=[ - compute.BgpRoute(), - ], - next_page_token="ghi", - ), - compute.RoutersListBgpRoutes( - result=[ - compute.BgpRoute(), - compute.BgpRoute(), - ], + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") ), ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(compute.RoutersListBgpRoutes.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", - "router": "sample3", - } - - pager = client.list_bgp_routes(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, compute.BgpRoute) for i in results) - - pages = list(client.list_bgp_routes(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_list_route_policies_rest_use_cached_wrapped_rpc(): +def test_insert_unary_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: @@ -4354,41 +4226,38 @@ def test_list_route_policies_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_route_policies in client._transport._wrapped_methods - ) + assert client._transport.insert 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_route_policies] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.insert] = mock_rpc request = {} - client.list_route_policies(request) + client.insert_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_route_policies(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.insert_unary(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_route_policies_rest_required_fields( - request_type=compute.ListRoutePoliciesRoutersRequest, -): +def test_insert_unary_rest_required_fields(request_type=compute.InsertRouterRequest): transport_class = transports.RoutersRestTransport request_init = {} request_init["project"] = "" request_init["region"] = "" - request_init["router"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4399,28 +4268,19 @@ def test_list_route_policies_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_route_policies._get_unset_required_fields(jsonified_request) + ).insert._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["region"] = "region_value" - jsonified_request["router"] = "router_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_route_policies._get_unset_required_fields(jsonified_request) + ).insert._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", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4428,8 +4288,6 @@ def test_list_route_policies_rest_required_fields( assert jsonified_request["project"] == "project_value" assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" - assert "router" in jsonified_request - assert jsonified_request["router"] == "router_value" client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4438,7 +4296,7 @@ def test_list_route_policies_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RoutersListRoutePolicies() + return_value = compute.Operation() # 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 @@ -4450,56 +4308,49 @@ def test_list_route_policies_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersListRoutePolicies.pb(return_value) + return_value = compute.Operation.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_route_policies(request) + response = client.insert_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_route_policies_rest_unset_required_fields(): +def test_insert_unary_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_route_policies._get_unset_required_fields({}) + unset_fields = transport.insert._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "filter", - "maxResults", - "orderBy", - "pageToken", - "returnPartialSuccess", - ) - ) + set(("requestId",)) & set( ( "project", "region", - "router", + "routerResource", ) ) ) -def test_list_route_policies_rest_flattened(): +def test_insert_unary_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4508,20 +4359,18 @@ def test_list_route_policies_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RoutersListRoutePolicies() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method - sample_request = { - "project": "sample1", - "region": "sample2", - "router": "sample3", - } + sample_request = {"project": "sample1", "region": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", region="region_value", - router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") + ), ) mock_args.update(sample_request) @@ -4529,26 +4378,26 @@ def test_list_route_policies_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersListRoutePolicies.pb(return_value) + return_value = compute.Operation.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_route_policies(**mock_args) + client.insert_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/listRoutePolicies" + "%s/compute/v1/projects/{project}/regions/{region}/routers" % client.transport._host, args[1], ) -def test_list_route_policies_rest_flattened_error(transport: str = "rest"): +def test_insert_unary_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4557,83 +4406,17 @@ def test_list_route_policies_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_route_policies( - compute.ListRoutePoliciesRoutersRequest(), + client.insert_unary( + compute.InsertRouterRequest(), project="project_value", region="region_value", - router="router_value", - ) - - -def test_list_route_policies_rest_pager(transport: str = "rest"): - client = RoutersClient( - 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.RoutersListRoutePolicies( - result=[ - compute.RoutePolicy(), - compute.RoutePolicy(), - compute.RoutePolicy(), - ], - next_page_token="abc", - ), - compute.RoutersListRoutePolicies( - result=[], - next_page_token="def", - ), - compute.RoutersListRoutePolicies( - result=[ - compute.RoutePolicy(), - ], - next_page_token="ghi", - ), - compute.RoutersListRoutePolicies( - result=[ - compute.RoutePolicy(), - compute.RoutePolicy(), - ], + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") ), ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(compute.RoutersListRoutePolicies.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", - "router": "sample3", - } - pager = client.list_route_policies(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, compute.RoutePolicy) for i in results) - pages = list(client.list_route_policies(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -def test_patch_rest_use_cached_wrapped_rpc(): +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: @@ -4647,39 +4430,34 @@ def test_patch_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.patch in client._transport._wrapped_methods + 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.patch] = mock_rpc + client._transport._wrapped_methods[client._transport.list] = mock_rpc request = {} - client.patch(request) + client.list(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.patch(request) + 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_patch_rest_required_fields(request_type=compute.PatchRouterRequest): +def test_list_rest_required_fields(request_type=compute.ListRoutersRequest): transport_class = transports.RoutersRestTransport request_init = {} request_init["project"] = "" request_init["region"] = "" - request_init["router"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -4690,20 +4468,27 @@ def test_patch_rest_required_fields(request_type=compute.PatchRouterRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch._get_unset_required_fields(jsonified_request) + ).list._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["region"] = "region_value" - jsonified_request["router"] = "router_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch._get_unset_required_fields(jsonified_request) + ).list._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + 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 @@ -4711,8 +4496,6 @@ def test_patch_rest_required_fields(request_type=compute.PatchRouterRequest): assert jsonified_request["project"] == "project_value" assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" - assert "router" in jsonified_request - assert jsonified_request["router"] == "router_value" client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), @@ -4721,7 +4504,7 @@ def test_patch_rest_required_fields(request_type=compute.PatchRouterRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RouterList() # 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 @@ -4733,50 +4516,55 @@ def test_patch_rest_required_fields(request_type=compute.PatchRouterRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RouterList.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.patch(request) + response = client.list(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_patch_rest_unset_required_fields(): +def test_list_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.patch._get_unset_required_fields({}) + unset_fields = transport.list._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) & set( ( "project", "region", - "router", - "routerResource", ) ) ) -def test_patch_rest_flattened(): +def test_list_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -4785,23 +4573,15 @@ def test_patch_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RouterList() # get arguments that satisfy an http rule for this method - sample_request = { - "project": "sample1", - "region": "sample2", - "router": "sample3", - } + sample_request = {"project": "sample1", "region": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", region="region_value", - router="router_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), ) mock_args.update(sample_request) @@ -4809,26 +4589,26 @@ def test_patch_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RouterList.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.patch(**mock_args) + 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/v1/projects/{project}/regions/{region}/routers/{router}" + "%s/compute/v1/projects/{project}/regions/{region}/routers" % client.transport._host, args[1], ) -def test_patch_rest_flattened_error(transport: str = "rest"): +def test_list_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4837,58 +4617,116 @@ def test_patch_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.patch( - compute.PatchRouterRequest(), + client.list( + compute.ListRoutersRequest(), project="project_value", region="region_value", - router="router_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), - ) - - -def test_patch_unary_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 = RoutersClient( - 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.patch 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.patch] = mock_rpc - - request = {} - client.patch_unary(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.patch_unary(request) +def test_list_rest_pager(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # 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.RouterList( + items=[ + compute.Router(), + compute.Router(), + compute.Router(), + ], + next_page_token="abc", + ), + compute.RouterList( + items=[], + next_page_token="def", + ), + compute.RouterList( + items=[ + compute.Router(), + ], + next_page_token="ghi", + ), + compute.RouterList( + items=[ + compute.Router(), + compute.Router(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RouterList.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"} -def test_patch_unary_rest_required_fields(request_type=compute.PatchRouterRequest): + pager = client.list(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.Router) 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_list_bgp_routes_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 = RoutersClient( + 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_bgp_routes 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_bgp_routes] = mock_rpc + + request = {} + client.list_bgp_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_bgp_routes(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_bgp_routes_rest_required_fields( + request_type=compute.ListBgpRoutesRoutersRequest, +): transport_class = transports.RoutersRestTransport request_init = {} @@ -4905,7 +4743,7 @@ def test_patch_unary_rest_required_fields(request_type=compute.PatchRouterReques unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch._get_unset_required_fields(jsonified_request) + ).list_bgp_routes._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -4916,9 +4754,22 @@ def test_patch_unary_rest_required_fields(request_type=compute.PatchRouterReques unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch._get_unset_required_fields(jsonified_request) + ).list_bgp_routes._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "address_family", + "destination_prefix", + "filter", + "max_results", + "order_by", + "page_token", + "peer", + "policy_applied", + "return_partial_success", + "route_type", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -4936,7 +4787,7 @@ def test_patch_unary_rest_required_fields(request_type=compute.PatchRouterReques request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersListBgpRoutes() # 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 @@ -4948,50 +4799,61 @@ def test_patch_unary_rest_required_fields(request_type=compute.PatchRouterReques pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListBgpRoutes.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.patch_unary(request) + response = client.list_bgp_routes(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_patch_unary_rest_unset_required_fields(): +def test_list_bgp_routes_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.patch._get_unset_required_fields({}) + unset_fields = transport.list_bgp_routes._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "addressFamily", + "destinationPrefix", + "filter", + "maxResults", + "orderBy", + "pageToken", + "peer", + "policyApplied", + "returnPartialSuccess", + "routeType", + ) + ) & set( ( "project", "region", "router", - "routerResource", ) ) ) -def test_patch_unary_rest_flattened(): +def test_list_bgp_routes_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5000,7 +4862,7 @@ def test_patch_unary_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersListBgpRoutes() # get arguments that satisfy an http rule for this method sample_request = { @@ -5014,9 +4876,6 @@ def test_patch_unary_rest_flattened(): project="project_value", region="region_value", router="router_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), ) mock_args.update(sample_request) @@ -5024,26 +4883,26 @@ def test_patch_unary_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListBgpRoutes.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.patch_unary(**mock_args) + client.list_bgp_routes(**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/v1/projects/{project}/regions/{region}/routers/{router}" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/listBgpRoutes" % client.transport._host, args[1], ) -def test_patch_unary_rest_flattened_error(transport: str = "rest"): +def test_list_bgp_routes_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5052,18 +4911,83 @@ def test_patch_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.patch_unary( - compute.PatchRouterRequest(), + client.list_bgp_routes( + compute.ListBgpRoutesRoutersRequest(), project="project_value", region="region_value", router="router_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") + ) + + +def test_list_bgp_routes_rest_pager(transport: str = "rest"): + client = RoutersClient( + 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.RoutersListBgpRoutes( + result=[ + compute.BgpRoute(), + compute.BgpRoute(), + compute.BgpRoute(), + ], + next_page_token="abc", + ), + compute.RoutersListBgpRoutes( + result=[], + next_page_token="def", + ), + compute.RoutersListBgpRoutes( + result=[ + compute.BgpRoute(), + ], + next_page_token="ghi", + ), + compute.RoutersListBgpRoutes( + result=[ + compute.BgpRoute(), + compute.BgpRoute(), + ], ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RoutersListBgpRoutes.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", + "router": "sample3", + } + + pager = client.list_bgp_routes(request=sample_request) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") -def test_patch_route_policy_rest_use_cached_wrapped_rpc(): + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.BgpRoute) for i in results) + + pages = list(client.list_bgp_routes(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_named_sets_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: @@ -5077,38 +5001,30 @@ def test_patch_route_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.patch_route_policy in client._transport._wrapped_methods - ) + assert client._transport.list_named_sets 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.patch_route_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.list_named_sets] = mock_rpc request = {} - client.patch_route_policy(request) + client.list_named_sets(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.patch_route_policy(request) + client.list_named_sets(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_patch_route_policy_rest_required_fields( - request_type=compute.PatchRoutePolicyRouterRequest, +def test_list_named_sets_rest_required_fields( + request_type=compute.ListNamedSetsRoutersRequest, ): transport_class = transports.RoutersRestTransport @@ -5126,7 +5042,7 @@ def test_patch_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch_route_policy._get_unset_required_fields(jsonified_request) + ).list_named_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5137,15 +5053,23 @@ def test_patch_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch_route_policy._get_unset_required_fields(jsonified_request) + ).list_named_sets._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "project" in jsonified_request - assert jsonified_request["project"] == "project_value" - assert "region" in jsonified_request + 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 "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request assert jsonified_request["region"] == "region_value" assert "router" in jsonified_request assert jsonified_request["router"] == "router_value" @@ -5157,7 +5081,7 @@ def test_patch_route_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersListNamedSets() # 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 @@ -5169,50 +5093,56 @@ def test_patch_route_policy_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListNamedSets.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.patch_route_policy(request) + response = client.list_named_sets(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_patch_route_policy_rest_unset_required_fields(): +def test_list_named_sets_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.patch_route_policy._get_unset_required_fields({}) + unset_fields = transport.list_named_sets._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) & set( ( "project", "region", - "routePolicyResource", "router", ) ) ) -def test_patch_route_policy_rest_flattened(): +def test_list_named_sets_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5221,7 +5151,7 @@ def test_patch_route_policy_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersListNamedSets() # get arguments that satisfy an http rule for this method sample_request = { @@ -5235,7 +5165,6 @@ def test_patch_route_policy_rest_flattened(): project="project_value", region="region_value", router="router_value", - route_policy_resource=compute.RoutePolicy(description="description_value"), ) mock_args.update(sample_request) @@ -5243,26 +5172,26 @@ def test_patch_route_policy_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListNamedSets.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.patch_route_policy(**mock_args) + client.list_named_sets(**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/v1/projects/{project}/regions/{region}/routers/{router}/patchRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/listNamedSets" % client.transport._host, args[1], ) -def test_patch_route_policy_rest_flattened_error(transport: str = "rest"): +def test_list_named_sets_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5271,16 +5200,83 @@ def test_patch_route_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.patch_route_policy( - compute.PatchRoutePolicyRouterRequest(), + client.list_named_sets( + compute.ListNamedSetsRoutersRequest(), project="project_value", region="region_value", router="router_value", - route_policy_resource=compute.RoutePolicy(description="description_value"), ) -def test_patch_route_policy_unary_rest_use_cached_wrapped_rpc(): +def test_list_named_sets_rest_pager(transport: str = "rest"): + client = RoutersClient( + 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.RoutersListNamedSets( + result=[ + compute.NamedSet(), + compute.NamedSet(), + compute.NamedSet(), + ], + next_page_token="abc", + ), + compute.RoutersListNamedSets( + result=[], + next_page_token="def", + ), + compute.RoutersListNamedSets( + result=[ + compute.NamedSet(), + ], + next_page_token="ghi", + ), + compute.RoutersListNamedSets( + result=[ + compute.NamedSet(), + compute.NamedSet(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RoutersListNamedSets.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", + "router": "sample3", + } + + pager = client.list_named_sets(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.NamedSet) for i in results) + + pages = list(client.list_named_sets(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_route_policies_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: @@ -5295,7 +5291,7 @@ def test_patch_route_policy_unary_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.patch_route_policy in client._transport._wrapped_methods + client._transport.list_route_policies in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -5303,29 +5299,25 @@ def test_patch_route_policy_unary_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.patch_route_policy] = ( + client._transport._wrapped_methods[client._transport.list_route_policies] = ( mock_rpc ) request = {} - client.patch_route_policy_unary(request) + client.list_route_policies(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.patch_route_policy_unary(request) + client.list_route_policies(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_patch_route_policy_unary_rest_required_fields( - request_type=compute.PatchRoutePolicyRouterRequest, +def test_list_route_policies_rest_required_fields( + request_type=compute.ListRoutePoliciesRoutersRequest, ): transport_class = transports.RoutersRestTransport @@ -5343,7 +5335,7 @@ def test_patch_route_policy_unary_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch_route_policy._get_unset_required_fields(jsonified_request) + ).list_route_policies._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5354,9 +5346,17 @@ def test_patch_route_policy_unary_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).patch_route_policy._get_unset_required_fields(jsonified_request) + ).list_route_policies._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + 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 @@ -5374,7 +5374,7 @@ def test_patch_route_policy_unary_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersListRoutePolicies() # 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 @@ -5386,50 +5386,56 @@ def test_patch_route_policy_unary_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListRoutePolicies.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.patch_route_policy_unary(request) + response = client.list_route_policies(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_patch_route_policy_unary_rest_unset_required_fields(): +def test_list_route_policies_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.patch_route_policy._get_unset_required_fields({}) + unset_fields = transport.list_route_policies._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) + set( + ( + "filter", + "maxResults", + "orderBy", + "pageToken", + "returnPartialSuccess", + ) + ) & set( ( "project", "region", - "routePolicyResource", "router", ) ) ) -def test_patch_route_policy_unary_rest_flattened(): +def test_list_route_policies_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5438,7 +5444,7 @@ def test_patch_route_policy_unary_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation() + return_value = compute.RoutersListRoutePolicies() # get arguments that satisfy an http rule for this method sample_request = { @@ -5452,7 +5458,6 @@ def test_patch_route_policy_unary_rest_flattened(): project="project_value", region="region_value", router="router_value", - route_policy_resource=compute.RoutePolicy(description="description_value"), ) mock_args.update(sample_request) @@ -5460,26 +5465,26 @@ def test_patch_route_policy_unary_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListRoutePolicies.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.patch_route_policy_unary(**mock_args) + client.list_route_policies(**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/v1/projects/{project}/regions/{region}/routers/{router}/patchRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/listRoutePolicies" % client.transport._host, args[1], ) -def test_patch_route_policy_unary_rest_flattened_error(transport: str = "rest"): +def test_list_route_policies_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5488,16 +5493,83 @@ def test_patch_route_policy_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.patch_route_policy_unary( - compute.PatchRoutePolicyRouterRequest(), + client.list_route_policies( + compute.ListRoutePoliciesRoutersRequest(), project="project_value", region="region_value", router="router_value", - route_policy_resource=compute.RoutePolicy(description="description_value"), ) -def test_preview_rest_use_cached_wrapped_rpc(): +def test_list_route_policies_rest_pager(transport: str = "rest"): + client = RoutersClient( + 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.RoutersListRoutePolicies( + result=[ + compute.RoutePolicy(), + compute.RoutePolicy(), + compute.RoutePolicy(), + ], + next_page_token="abc", + ), + compute.RoutersListRoutePolicies( + result=[], + next_page_token="def", + ), + compute.RoutersListRoutePolicies( + result=[ + compute.RoutePolicy(), + ], + next_page_token="ghi", + ), + compute.RoutersListRoutePolicies( + result=[ + compute.RoutePolicy(), + compute.RoutePolicy(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(compute.RoutersListRoutePolicies.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", + "router": "sample3", + } + + pager = client.list_route_policies(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, compute.RoutePolicy) for i in results) + + pages = list(client.list_route_policies(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_patch_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: @@ -5511,29 +5583,33 @@ def test_preview_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.preview in client._transport._wrapped_methods + assert client._transport.patch 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.preview] = mock_rpc + client._transport._wrapped_methods[client._transport.patch] = mock_rpc request = {} - client.preview(request) + client.patch(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.preview(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.patch(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_preview_rest_required_fields(request_type=compute.PreviewRouterRequest): +def test_patch_rest_required_fields(request_type=compute.PatchRouterRequest): transport_class = transports.RoutersRestTransport request_init = {} @@ -5550,7 +5626,7 @@ def test_preview_rest_required_fields(request_type=compute.PreviewRouterRequest) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).preview._get_unset_required_fields(jsonified_request) + ).patch._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5561,7 +5637,9 @@ def test_preview_rest_required_fields(request_type=compute.PreviewRouterRequest) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).preview._get_unset_required_fields(jsonified_request) + ).patch._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -5579,7 +5657,7 @@ def test_preview_rest_required_fields(request_type=compute.PreviewRouterRequest) request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = compute.RoutersPreviewResponse() + return_value = compute.Operation() # 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 @@ -5591,7 +5669,7 @@ def test_preview_rest_required_fields(request_type=compute.PreviewRouterRequest) pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -5601,28 +5679,28 @@ def test_preview_rest_required_fields(request_type=compute.PreviewRouterRequest) response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersPreviewResponse.pb(return_value) + return_value = compute.Operation.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.preview(request) + response = client.patch(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_preview_rest_unset_required_fields(): +def test_patch_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.preview._get_unset_required_fields({}) + unset_fields = transport.patch._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) + set(("requestId",)) & set( ( "project", @@ -5634,7 +5712,7 @@ def test_preview_rest_unset_required_fields(): ) -def test_preview_rest_flattened(): +def test_patch_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5643,7 +5721,7 @@ def test_preview_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RoutersPreviewResponse() + return_value = compute.Operation() # get arguments that satisfy an http rule for this method sample_request = { @@ -5667,26 +5745,26 @@ def test_preview_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersPreviewResponse.pb(return_value) + return_value = compute.Operation.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.preview(**mock_args) + client.patch(**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/v1/projects/{project}/regions/{region}/routers/{router}/preview" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}" % client.transport._host, args[1], ) -def test_preview_rest_flattened_error(transport: str = "rest"): +def test_patch_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5695,8 +5773,8 @@ def test_preview_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.preview( - compute.PreviewRouterRequest(), + client.patch( + compute.PatchRouterRequest(), project="project_value", region="region_value", router="router_value", @@ -5706,7 +5784,7 @@ def test_preview_rest_flattened_error(transport: str = "rest"): ) -def test_update_rest_use_cached_wrapped_rpc(): +def test_patch_unary_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: @@ -5720,17 +5798,17 @@ def test_update_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update in client._transport._wrapped_methods + assert client._transport.patch in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update] = mock_rpc + client._transport._wrapped_methods[client._transport.patch] = mock_rpc request = {} - client.update(request) + client.patch_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5739,14 +5817,14 @@ def test_update_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update(request) + client.patch_unary(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_rest_required_fields(request_type=compute.UpdateRouterRequest): +def test_patch_unary_rest_required_fields(request_type=compute.PatchRouterRequest): transport_class = transports.RoutersRestTransport request_init = {} @@ -5763,7 +5841,7 @@ def test_update_rest_required_fields(request_type=compute.UpdateRouterRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update._get_unset_required_fields(jsonified_request) + ).patch._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5774,7 +5852,7 @@ def test_update_rest_required_fields(request_type=compute.UpdateRouterRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update._get_unset_required_fields(jsonified_request) + ).patch._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) @@ -5806,7 +5884,7 @@ def test_update_rest_required_fields(request_type=compute.UpdateRouterRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "put", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -5823,19 +5901,19 @@ def test_update_rest_required_fields(request_type=compute.UpdateRouterRequest): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update(request) + response = client.patch_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_rest_unset_required_fields(): +def test_patch_unary_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update._get_unset_required_fields({}) + unset_fields = transport.patch._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set( @@ -5849,7 +5927,7 @@ def test_update_rest_unset_required_fields(): ) -def test_update_rest_flattened(): +def test_patch_unary_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -5888,7 +5966,7 @@ def test_update_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update(**mock_args) + client.patch_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -5901,7 +5979,7 @@ def test_update_rest_flattened(): ) -def test_update_rest_flattened_error(transport: str = "rest"): +def test_patch_unary_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5910,8 +5988,8 @@ def test_update_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update( - compute.UpdateRouterRequest(), + client.patch_unary( + compute.PatchRouterRequest(), project="project_value", region="region_value", router="router_value", @@ -5921,7 +5999,7 @@ def test_update_rest_flattened_error(transport: str = "rest"): ) -def test_update_unary_rest_use_cached_wrapped_rpc(): +def test_patch_named_set_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: @@ -5935,17 +6013,17 @@ def test_update_unary_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update in client._transport._wrapped_methods + assert client._transport.patch_named_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update] = mock_rpc + client._transport._wrapped_methods[client._transport.patch_named_set] = mock_rpc request = {} - client.update_unary(request) + client.patch_named_set(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5954,14 +6032,16 @@ def test_update_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_unary(request) + client.patch_named_set(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_unary_rest_required_fields(request_type=compute.UpdateRouterRequest): +def test_patch_named_set_rest_required_fields( + request_type=compute.PatchNamedSetRouterRequest, +): transport_class = transports.RoutersRestTransport request_init = {} @@ -5978,7 +6058,7 @@ def test_update_unary_rest_required_fields(request_type=compute.UpdateRouterRequ unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update._get_unset_required_fields(jsonified_request) + ).patch_named_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -5989,7 +6069,7 @@ def test_update_unary_rest_required_fields(request_type=compute.UpdateRouterRequ unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update._get_unset_required_fields(jsonified_request) + ).patch_named_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) @@ -6021,7 +6101,7 @@ def test_update_unary_rest_required_fields(request_type=compute.UpdateRouterRequ pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "put", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -6038,33 +6118,33 @@ def test_update_unary_rest_required_fields(request_type=compute.UpdateRouterRequ req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_unary(request) + response = client.patch_named_set(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_unary_rest_unset_required_fields(): +def test_patch_named_set_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update._get_unset_required_fields({}) + unset_fields = transport.patch_named_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set( ( + "namedSetResource", "project", "region", "router", - "routerResource", ) ) ) -def test_update_unary_rest_flattened(): +def test_patch_named_set_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6087,9 +6167,7 @@ def test_update_unary_rest_flattened(): project="project_value", region="region_value", router="router_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), + named_set_resource=compute.NamedSet(description="description_value"), ) mock_args.update(sample_request) @@ -6103,20 +6181,20 @@ def test_update_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_unary(**mock_args) + client.patch_named_set(**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/v1/projects/{project}/regions/{region}/routers/{router}" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/patchNamedSet" % client.transport._host, args[1], ) -def test_update_unary_rest_flattened_error(transport: str = "rest"): +def test_patch_named_set_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6125,18 +6203,16 @@ def test_update_unary_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_unary( - compute.UpdateRouterRequest(), + client.patch_named_set( + compute.PatchNamedSetRouterRequest(), project="project_value", region="region_value", router="router_value", - router_resource=compute.Router( - bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") - ), + named_set_resource=compute.NamedSet(description="description_value"), ) -def test_update_route_policy_rest_use_cached_wrapped_rpc(): +def test_patch_named_set_unary_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: @@ -6150,21 +6226,17 @@ def test_update_route_policy_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_route_policy in client._transport._wrapped_methods - ) + assert client._transport.patch_named_set in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_route_policy] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.patch_named_set] = mock_rpc request = {} - client.update_route_policy(request) + client.patch_named_set_unary(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6173,15 +6245,15 @@ def test_update_route_policy_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_route_policy(request) + client.patch_named_set_unary(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_route_policy_rest_required_fields( - request_type=compute.UpdateRoutePolicyRouterRequest, +def test_patch_named_set_unary_rest_required_fields( + request_type=compute.PatchNamedSetRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -6199,7 +6271,7 @@ def test_update_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_route_policy._get_unset_required_fields(jsonified_request) + ).patch_named_set._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6210,7 +6282,7 @@ def test_update_route_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_route_policy._get_unset_required_fields(jsonified_request) + ).patch_named_set._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) @@ -6259,33 +6331,33 @@ def test_update_route_policy_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_route_policy(request) + response = client.patch_named_set_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_route_policy_rest_unset_required_fields(): +def test_patch_named_set_unary_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_route_policy._get_unset_required_fields({}) + unset_fields = transport.patch_named_set._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set( ( + "namedSetResource", "project", "region", - "routePolicyResource", "router", ) ) ) -def test_update_route_policy_rest_flattened(): +def test_patch_named_set_unary_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6308,7 +6380,7 @@ def test_update_route_policy_rest_flattened(): project="project_value", region="region_value", router="router_value", - route_policy_resource=compute.RoutePolicy(description="description_value"), + named_set_resource=compute.NamedSet(description="description_value"), ) mock_args.update(sample_request) @@ -6322,20 +6394,20 @@ def test_update_route_policy_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_route_policy(**mock_args) + client.patch_named_set_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/updateRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/patchNamedSet" % client.transport._host, args[1], ) -def test_update_route_policy_rest_flattened_error(transport: str = "rest"): +def test_patch_named_set_unary_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6344,16 +6416,16 @@ def test_update_route_policy_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_route_policy( - compute.UpdateRoutePolicyRouterRequest(), + client.patch_named_set_unary( + compute.PatchNamedSetRouterRequest(), project="project_value", region="region_value", router="router_value", - route_policy_resource=compute.RoutePolicy(description="description_value"), + named_set_resource=compute.NamedSet(description="description_value"), ) -def test_update_route_policy_unary_rest_use_cached_wrapped_rpc(): +def test_patch_route_policy_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: @@ -6368,7 +6440,7 @@ def test_update_route_policy_unary_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.update_route_policy in client._transport._wrapped_methods + client._transport.patch_route_policy in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -6376,12 +6448,12 @@ def test_update_route_policy_unary_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_route_policy] = ( + client._transport._wrapped_methods[client._transport.patch_route_policy] = ( mock_rpc ) request = {} - client.update_route_policy_unary(request) + client.patch_route_policy(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6390,15 +6462,15 @@ def test_update_route_policy_unary_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_route_policy_unary(request) + client.patch_route_policy(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_route_policy_unary_rest_required_fields( - request_type=compute.UpdateRoutePolicyRouterRequest, +def test_patch_route_policy_rest_required_fields( + request_type=compute.PatchRoutePolicyRouterRequest, ): transport_class = transports.RoutersRestTransport @@ -6416,7 +6488,7 @@ def test_update_route_policy_unary_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_route_policy._get_unset_required_fields(jsonified_request) + ).patch_route_policy._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -6427,7 +6499,7 @@ def test_update_route_policy_unary_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_route_policy._get_unset_required_fields(jsonified_request) + ).patch_route_policy._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) @@ -6476,19 +6548,19 @@ def test_update_route_policy_unary_rest_required_fields( req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.update_route_policy_unary(request) + response = client.patch_route_policy(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_update_route_policy_unary_rest_unset_required_fields(): +def test_patch_route_policy_rest_unset_required_fields(): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_route_policy._get_unset_required_fields({}) + unset_fields = transport.patch_route_policy._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set( @@ -6502,7 +6574,7 @@ def test_update_route_policy_unary_rest_unset_required_fields(): ) -def test_update_route_policy_unary_rest_flattened(): +def test_patch_route_policy_rest_flattened(): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -6539,20 +6611,20 @@ def test_update_route_policy_unary_rest_flattened(): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_route_policy_unary(**mock_args) + client.patch_route_policy(**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/v1/projects/{project}/regions/{region}/routers/{router}/updateRoutePolicy" + "%s/compute/v1/projects/{project}/regions/{region}/routers/{router}/patchRoutePolicy" % client.transport._host, args[1], ) -def test_update_route_policy_unary_rest_flattened_error(transport: str = "rest"): +def test_patch_route_policy_rest_flattened_error(transport: str = "rest"): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6561,8 +6633,8 @@ def test_update_route_policy_unary_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_route_policy_unary( - compute.UpdateRoutePolicyRouterRequest(), + client.patch_route_policy( + compute.PatchRoutePolicyRouterRequest(), project="project_value", region="region_value", router="router_value", @@ -6570,224 +6642,1944 @@ def test_update_route_policy_unary_rest_flattened_error(transport: str = "rest") ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RoutersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): +def test_patch_route_policy_unary_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 = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="rest", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.RoutersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutersClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide an api_key and a transport instance. - transport = transports.RoutersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = RoutersClient( - client_options=options, - transport=transport, + # Ensure method has been cached + assert ( + client._transport.patch_route_policy in client._transport._wrapped_methods ) - # 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 = RoutersClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() + # 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. ) - - # It is an error to provide scopes and a transport instance. - transport = transports.RoutersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = RoutersClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + client._transport._wrapped_methods[client._transport.patch_route_policy] = ( + mock_rpc ) + request = {} + client.patch_route_policy_unary(request) -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RoutersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = RoutersClient(transport=transport) - assert client.transport is transport - + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -@pytest.mark.parametrize( - "transport_class", - [ - transports.RoutersRestTransport, - ], -) -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() + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + client.patch_route_policy_unary(request) -def test_transport_kind_rest(): - transport = RoutersClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" + # 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_aggregated_list_rest_bad_request( - request_type=compute.AggregatedListRoutersRequest, +def test_patch_route_policy_unary_rest_required_fields( + request_type=compute.PatchRoutePolicyRouterRequest, ): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1"} + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" 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) + ) - # 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.aggregated_list(request) + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch_route_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).patch_route_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" -@pytest.mark.parametrize( - "request_type", - [ - compute.AggregatedListRoutersRequest, - dict, - ], -) -def test_aggregated_list_rest_call_success(request_type): client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - - # send a request that will satisfy transcoding - request_init = {"project": "sample1"} request = request_type(**request_init) + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.patch_route_policy_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_patch_route_policy_unary_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.patch_route_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "routePolicyResource", + "router", + ) + ) + ) + + +def test_patch_route_policy_unary_rest_flattened(): + client = RoutersClient( + 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.RouterAggregatedList( - id="id_value", - kind="kind_value", - next_page_token="next_page_token_value", - self_link="self_link_value", - unreachables=["unreachables_value"], + return_value = compute.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + route_policy_resource=compute.RoutePolicy(description="description_value"), ) + mock_args.update(sample_request) # Wrap the value into a proper Response obj - response_value = mock.Mock() + response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = compute.RouterAggregatedList.pb(return_value) + return_value = compute.Operation.pb(return_value) json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + 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.aggregated_list(request) - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.AggregatedListPager) - 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" - assert response.unreachables == ["unreachables_value"] + client.patch_route_policy_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/patchRoutePolicy" + % client.transport._host, + args[1], + ) -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_aggregated_list_rest_interceptors(null_interceptor): - transport = transports.RoutersRestTransport( +def test_patch_route_policy_unary_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + transport=transport, ) - client = RoutersClient(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.RoutersRestInterceptor, "post_aggregated_list" - ) as post, - mock.patch.object( - transports.RoutersRestInterceptor, "post_aggregated_list_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.RoutersRestInterceptor, "pre_aggregated_list" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = compute.AggregatedListRoutersRequest.pb( - compute.AggregatedListRoutersRequest() - ) - 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.RouterAggregatedList.to_json( - compute.RouterAggregatedList() + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.patch_route_policy_unary( + compute.PatchRoutePolicyRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + route_policy_resource=compute.RoutePolicy(description="description_value"), ) - req.return_value.content = return_value - request = compute.AggregatedListRoutersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = compute.RouterAggregatedList() - post_with_metadata.return_value = compute.RouterAggregatedList(), metadata - client.aggregated_list( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], +def test_preview_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # 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.preview 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.preview] = mock_rpc + + request = {} + client.preview(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.preview(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_preview_rest_required_fields(request_type=compute.PreviewRouterRequest): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).preview._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).preview._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.RoutersPreviewResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.RoutersPreviewResponse.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.preview(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_preview_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.preview._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "project", + "region", + "router", + "routerResource", + ) + ) + ) + + +def test_preview_rest_flattened(): + client = RoutersClient( + 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.RoutersPreviewResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_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.RoutersPreviewResponse.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.preview(**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/v1/projects/{project}/regions/{region}/routers/{router}/preview" + % client.transport._host, + args[1], + ) + + +def test_preview_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + 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.preview( + compute.PreviewRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") + ), + ) + + +def test_update_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update] = mock_rpc + + request = {} + client.update(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_rest_required_fields(request_type=compute.UpdateRouterRequest): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # 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": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.update(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "router", + "routerResource", + ) + ) + ) + + +def test_update_rest_flattened(): + client = RoutersClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_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.Operation.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.update(**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/v1/projects/{project}/regions/{region}/routers/{router}" + % client.transport._host, + args[1], + ) + + +def test_update_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update( + compute.UpdateRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") + ), + ) + + +def test_update_unary_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update] = mock_rpc + + request = {} + client.update_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_unary_rest_required_fields(request_type=compute.UpdateRouterRequest): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).update._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # 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": "put", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.update_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_unary_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "router", + "routerResource", + ) + ) + ) + + +def test_update_unary_rest_flattened(): + client = RoutersClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_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.Operation.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.update_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}" + % client.transport._host, + args[1], + ) + + +def test_update_unary_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_unary( + compute.UpdateRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + router_resource=compute.Router( + bgp=compute.RouterBgp(advertise_mode="advertise_mode_value") + ), + ) + + +def test_update_named_set_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_named_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_named_set] = ( + mock_rpc + ) + + request = {} + client.update_named_set(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_named_set(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_named_set_rest_required_fields( + request_type=compute.UpdateNamedSetRouterRequest, +): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).update_named_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_named_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.update_named_set(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_named_set_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_named_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "namedSetResource", + "project", + "region", + "router", + ) + ) + ) + + +def test_update_named_set_rest_flattened(): + client = RoutersClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + named_set_resource=compute.NamedSet(description="description_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.Operation.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.update_named_set(**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/v1/projects/{project}/regions/{region}/routers/{router}/updateNamedSet" + % client.transport._host, + args[1], + ) + + +def test_update_named_set_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_named_set( + compute.UpdateNamedSetRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + named_set_resource=compute.NamedSet(description="description_value"), + ) + + +def test_update_named_set_unary_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_named_set in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_named_set] = ( + mock_rpc + ) + + request = {} + client.update_named_set_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_named_set_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_named_set_unary_rest_required_fields( + request_type=compute.UpdateNamedSetRouterRequest, +): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).update_named_set._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_named_set._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.update_named_set_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_named_set_unary_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_named_set._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "namedSetResource", + "project", + "region", + "router", + ) + ) + ) + + +def test_update_named_set_unary_rest_flattened(): + client = RoutersClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + named_set_resource=compute.NamedSet(description="description_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.Operation.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.update_named_set_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/updateNamedSet" + % client.transport._host, + args[1], + ) + + +def test_update_named_set_unary_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_named_set_unary( + compute.UpdateNamedSetRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + named_set_resource=compute.NamedSet(description="description_value"), + ) + + +def test_update_route_policy_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_route_policy in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_route_policy] = ( + mock_rpc + ) + + request = {} + client.update_route_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_route_policy(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_route_policy_rest_required_fields( + request_type=compute.UpdateRoutePolicyRouterRequest, +): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).update_route_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_route_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.update_route_policy(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_route_policy_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_route_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "routePolicyResource", + "router", + ) + ) + ) + + +def test_update_route_policy_rest_flattened(): + client = RoutersClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + route_policy_resource=compute.RoutePolicy(description="description_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.Operation.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.update_route_policy(**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/v1/projects/{project}/regions/{region}/routers/{router}/updateRoutePolicy" + % client.transport._host, + args[1], + ) + + +def test_update_route_policy_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_route_policy( + compute.UpdateRoutePolicyRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + route_policy_resource=compute.RoutePolicy(description="description_value"), + ) + + +def test_update_route_policy_unary_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 = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.update_route_policy in client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_route_policy] = ( + mock_rpc + ) + + request = {} + client.update_route_policy_unary(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_route_policy_unary(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_route_policy_unary_rest_required_fields( + request_type=compute.UpdateRoutePolicyRouterRequest, +): + transport_class = transports.RoutersRestTransport + + request_init = {} + request_init["project"] = "" + request_init["region"] = "" + request_init["router"] = "" + 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() + ).update_route_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["project"] = "project_value" + jsonified_request["region"] = "region_value" + jsonified_request["router"] = "router_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_route_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "project" in jsonified_request + assert jsonified_request["project"] == "project_value" + assert "region" in jsonified_request + assert jsonified_request["region"] == "region_value" + assert "router" in jsonified_request + assert jsonified_request["router"] == "router_value" + + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = compute.Operation() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = compute.Operation.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.update_route_policy_unary(request) + + expected_params = [] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_route_policy_unary_rest_unset_required_fields(): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_route_policy._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("requestId",)) + & set( + ( + "project", + "region", + "routePolicyResource", + "router", + ) + ) + ) + + +def test_update_route_policy_unary_rest_flattened(): + client = RoutersClient( + 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.Operation() + + # get arguments that satisfy an http rule for this method + sample_request = { + "project": "sample1", + "region": "sample2", + "router": "sample3", + } + + # get truthy value for each flattened field + mock_args = dict( + project="project_value", + region="region_value", + router="router_value", + route_policy_resource=compute.RoutePolicy(description="description_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.Operation.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.update_route_policy_unary(**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/v1/projects/{project}/regions/{region}/routers/{router}/updateRoutePolicy" + % client.transport._host, + args[1], + ) + + +def test_update_route_policy_unary_rest_flattened_error(transport: str = "rest"): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_route_policy_unary( + compute.UpdateRoutePolicyRouterRequest(), + project="project_value", + region="region_value", + router="router_value", + route_policy_resource=compute.RoutePolicy(description="description_value"), + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutersClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = RoutersClient( + 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 = RoutersClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RoutersClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = RoutersClient(transport=transport) + assert client.transport is transport + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RoutersRestTransport, + ], +) +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 = RoutersClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_aggregated_list_rest_bad_request( + request_type=compute.AggregatedListRoutersRequest, +): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.aggregated_list(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.AggregatedListRoutersRequest, + dict, + ], +) +def test_aggregated_list_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = compute.RouterAggregatedList( + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_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.RouterAggregatedList.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.aggregated_list(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.AggregatedListPager) + 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" + assert response.unreachables == ["unreachables_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_aggregated_list_rest_interceptors(null_interceptor): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_aggregated_list" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_aggregated_list_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_aggregated_list" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.AggregatedListRoutersRequest.pb( + compute.AggregatedListRoutersRequest() + ) + 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.RouterAggregatedList.to_json( + compute.RouterAggregatedList() + ) + req.return_value.content = return_value + + request = compute.AggregatedListRoutersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RouterAggregatedList() + post_with_metadata.return_value = compute.RouterAggregatedList(), metadata + + client.aggregated_list( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() def test_delete_rest_bad_request(request_type=compute.DeleteRouterRequest): @@ -6811,17 +8603,787 @@ def test_delete_rest_bad_request(request_type=compute.DeleteRouterRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete(request) + client.delete(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRouterRequest, + dict, + ], +) +def test_delete_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_rest_interceptors(null_interceptor): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_delete") as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_delete_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RoutersRestInterceptor, "pre_delete") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRouterRequest.pb(compute.DeleteRouterRequest()) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteRouterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_named_set_rest_bad_request( + request_type=compute.DeleteNamedSetRouterRequest, +): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.delete_named_set(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteNamedSetRouterRequest, + dict, + ], +) +def test_delete_named_set_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete_named_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_named_set_rest_interceptors(null_interceptor): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_delete_named_set" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_delete_named_set_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_delete_named_set" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteNamedSetRouterRequest.pb( + compute.DeleteNamedSetRouterRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteNamedSetRouterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete_named_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_route_policy_rest_bad_request( + request_type=compute.DeleteRoutePolicyRouterRequest, +): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.delete_route_policy(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.DeleteRoutePolicyRouterRequest, + dict, + ], +) +def test_delete_route_policy_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.Operation.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.delete_route_policy(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_route_policy_rest_interceptors(null_interceptor): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_delete_route_policy" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_delete_route_policy_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_delete_route_policy" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.DeleteRoutePolicyRouterRequest.pb( + compute.DeleteRoutePolicyRouterRequest() + ) + 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.Operation.to_json(compute.Operation()) + req.return_value.content = return_value + + request = compute.DeleteRoutePolicyRouterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata + + client.delete_route_policy( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_rest_bad_request(request_type=compute.GetRouterRequest): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.get(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetRouterRequest, + dict, + ], +) +def test_get_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.Router( + creation_timestamp="creation_timestamp_value", + description="description_value", + encrypted_interconnect_router=True, + id=205, + kind="kind_value", + name="name_value", + ncc_gateway="ncc_gateway_value", + network="network_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.Router.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.Router) + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.encrypted_interconnect_router is True + assert response.id == 205 + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.ncc_gateway == "ncc_gateway_value" + assert response.network == "network_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.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_get") as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_get_with_metadata" + ) as post_with_metadata, + mock.patch.object(transports.RoutersRestInterceptor, "pre_get") as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetRouterRequest.pb(compute.GetRouterRequest()) + 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.Router.to_json(compute.Router()) + req.return_value.content = return_value + + request = compute.GetRouterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.Router() + post_with_metadata.return_value = compute.Router(), 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_get_named_set_rest_bad_request(request_type=compute.GetNamedSetRouterRequest): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.get_named_set(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.GetNamedSetRouterRequest, + dict, + ], +) +def test_get_named_set_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.RoutersGetNamedSetResponse( + etag="etag_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.RoutersGetNamedSetResponse.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_named_set(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, compute.RoutersGetNamedSetResponse) + assert response.etag == "etag_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_named_set_rest_interceptors(null_interceptor): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_get_named_set" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_get_named_set_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_get_named_set" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.GetNamedSetRouterRequest.pb( + compute.GetNamedSetRouterRequest() + ) + 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.RoutersGetNamedSetResponse.to_json( + compute.RoutersGetNamedSetResponse() + ) + req.return_value.content = return_value + + request = compute.GetNamedSetRouterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RoutersGetNamedSetResponse() + post_with_metadata.return_value = compute.RoutersGetNamedSetResponse(), metadata + + client.get_named_set( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_nat_ip_info_rest_bad_request( + request_type=compute.GetNatIpInfoRouterRequest, +): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.get_nat_ip_info(request) @pytest.mark.parametrize( "request_type", [ - compute.DeleteRouterRequest, + compute.GetNatIpInfoRouterRequest, dict, ], ) -def test_delete_rest_call_success(request_type): +def test_get_nat_ip_info_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6833,71 +9395,26 @@ def test_delete_rest_call_success(request_type): # 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.Operation( - client_operation_id="client_operation_id_value", - creation_timestamp="creation_timestamp_value", - description="description_value", - end_time="end_time_value", - http_error_message="http_error_message_value", - http_error_status_code=2374, - id=205, - insert_time="insert_time_value", - kind="kind_value", - name="name_value", - operation_group_id="operation_group_id_value", - operation_type="operation_type_value", - progress=885, - region="region_value", - self_link="self_link_value", - start_time="start_time_value", - status=compute.Operation.Status.DONE, - status_message="status_message_value", - target_id=947, - target_link="target_link_value", - user="user_value", - zone="zone_value", - ) + return_value = compute.NatIpInfoResponse() # 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.Operation.pb(return_value) + return_value = compute.NatIpInfoResponse.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.delete(request) + response = client.get_nat_ip_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, extended_operation.ExtendedOperation) - assert response.client_operation_id == "client_operation_id_value" - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.end_time == "end_time_value" - assert response.http_error_message == "http_error_message_value" - assert response.http_error_status_code == 2374 - assert response.id == 205 - assert response.insert_time == "insert_time_value" - assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.operation_group_id == "operation_group_id_value" - assert response.operation_type == "operation_type_value" - assert response.progress == 885 - assert response.region == "region_value" - assert response.self_link == "self_link_value" - assert response.start_time == "start_time_value" - assert response.status == compute.Operation.Status.DONE - assert response.status_message == "status_message_value" - assert response.target_id == 947 - assert response.target_link == "target_link_value" - assert response.user == "user_value" - assert response.zone == "zone_value" + assert isinstance(response, compute.NatIpInfoResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_rest_interceptors(null_interceptor): +def test_get_nat_ip_info_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -6907,16 +9424,22 @@ def test_delete_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_delete") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_delete_with_metadata" + transports.RoutersRestInterceptor, "post_get_nat_ip_info" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_get_nat_ip_info_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_delete") as pre, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_get_nat_ip_info" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.DeleteRouterRequest.pb(compute.DeleteRouterRequest()) + pb_message = compute.GetNatIpInfoRouterRequest.pb( + compute.GetNatIpInfoRouterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6927,19 +9450,19 @@ def test_delete_rest_interceptors(null_interceptor): 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.Operation.to_json(compute.Operation()) + return_value = compute.NatIpInfoResponse.to_json(compute.NatIpInfoResponse()) req.return_value.content = return_value - request = compute.DeleteRouterRequest() + request = compute.GetNatIpInfoRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Operation() - post_with_metadata.return_value = compute.Operation(), metadata + post.return_value = compute.NatIpInfoResponse() + post_with_metadata.return_value = compute.NatIpInfoResponse(), metadata - client.delete( + client.get_nat_ip_info( request, metadata=[ ("key", "val"), @@ -6952,8 +9475,8 @@ def test_delete_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_route_policy_rest_bad_request( - request_type=compute.DeleteRoutePolicyRouterRequest, +def test_get_nat_mapping_info_rest_bad_request( + request_type=compute.GetNatMappingInfoRoutersRequest, ): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -6975,17 +9498,17 @@ def test_delete_route_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_route_policy(request) + client.get_nat_mapping_info(request) @pytest.mark.parametrize( "request_type", [ - compute.DeleteRoutePolicyRouterRequest, + compute.GetNatMappingInfoRoutersRequest, dict, ], ) -def test_delete_route_policy_rest_call_success(request_type): +def test_get_nat_mapping_info_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -6997,29 +9520,11 @@ def test_delete_route_policy_rest_call_success(request_type): # 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.Operation( - client_operation_id="client_operation_id_value", - creation_timestamp="creation_timestamp_value", - description="description_value", - end_time="end_time_value", - http_error_message="http_error_message_value", - http_error_status_code=2374, - id=205, - insert_time="insert_time_value", + return_value = compute.VmEndpointNatMappingsList( + id="id_value", kind="kind_value", - name="name_value", - operation_group_id="operation_group_id_value", - operation_type="operation_type_value", - progress=885, - region="region_value", + next_page_token="next_page_token_value", self_link="self_link_value", - start_time="start_time_value", - status=compute.Operation.Status.DONE, - status_message="status_message_value", - target_id=947, - target_link="target_link_value", - user="user_value", - zone="zone_value", ) # Wrap the value into a proper Response obj @@ -7027,41 +9532,23 @@ def test_delete_route_policy_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.VmEndpointNatMappingsList.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.delete_route_policy(request) + response = client.get_nat_mapping_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, extended_operation.ExtendedOperation) - assert response.client_operation_id == "client_operation_id_value" - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.end_time == "end_time_value" - assert response.http_error_message == "http_error_message_value" - assert response.http_error_status_code == 2374 - assert response.id == 205 - assert response.insert_time == "insert_time_value" + assert isinstance(response, pagers.GetNatMappingInfoPager) + assert response.id == "id_value" assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.operation_group_id == "operation_group_id_value" - assert response.operation_type == "operation_type_value" - assert response.progress == 885 - assert response.region == "region_value" + assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" - assert response.start_time == "start_time_value" - assert response.status == compute.Operation.Status.DONE - assert response.status_message == "status_message_value" - assert response.target_id == 947 - assert response.target_link == "target_link_value" - assert response.user == "user_value" - assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_route_policy_rest_interceptors(null_interceptor): +def test_get_nat_mapping_info_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -7072,20 +9559,20 @@ def test_delete_route_policy_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.RoutersRestInterceptor, "post_delete_route_policy" + transports.RoutersRestInterceptor, "post_get_nat_mapping_info" ) as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_delete_route_policy_with_metadata" + transports.RoutersRestInterceptor, "post_get_nat_mapping_info_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.RoutersRestInterceptor, "pre_delete_route_policy" + transports.RoutersRestInterceptor, "pre_get_nat_mapping_info" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.DeleteRoutePolicyRouterRequest.pb( - compute.DeleteRoutePolicyRouterRequest() + pb_message = compute.GetNatMappingInfoRoutersRequest.pb( + compute.GetNatMappingInfoRoutersRequest() ) transcode.return_value = { "method": "post", @@ -7097,19 +9584,21 @@ def test_delete_route_policy_rest_interceptors(null_interceptor): 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.Operation.to_json(compute.Operation()) + return_value = compute.VmEndpointNatMappingsList.to_json( + compute.VmEndpointNatMappingsList() + ) req.return_value.content = return_value - request = compute.DeleteRoutePolicyRouterRequest() + request = compute.GetNatMappingInfoRoutersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Operation() - post_with_metadata.return_value = compute.Operation(), metadata + post.return_value = compute.VmEndpointNatMappingsList() + post_with_metadata.return_value = compute.VmEndpointNatMappingsList(), metadata - client.delete_route_policy( + client.get_nat_mapping_info( request, metadata=[ ("key", "val"), @@ -7122,7 +9611,9 @@ def test_delete_route_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_rest_bad_request(request_type=compute.GetRouterRequest): +def test_get_route_policy_rest_bad_request( + request_type=compute.GetRoutePolicyRouterRequest, +): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7143,17 +9634,17 @@ def test_get_rest_bad_request(request_type=compute.GetRouterRequest): 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) + client.get_route_policy(request) @pytest.mark.parametrize( "request_type", [ - compute.GetRouterRequest, + compute.GetRoutePolicyRouterRequest, dict, ], ) -def test_get_rest_call_success(request_type): +def test_get_route_policy_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7165,45 +9656,26 @@ def test_get_rest_call_success(request_type): # 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.Router( - creation_timestamp="creation_timestamp_value", - description="description_value", - encrypted_interconnect_router=True, - id=205, - kind="kind_value", - name="name_value", - network="network_value", - region="region_value", - self_link="self_link_value", - ) + return_value = compute.RoutersGetRoutePolicyResponse() # 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.Router.pb(return_value) + return_value = compute.RoutersGetRoutePolicyResponse.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) + response = client.get_route_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.Router) - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.encrypted_interconnect_router is True - assert response.id == 205 - assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.network == "network_value" - assert response.region == "region_value" - assert response.self_link == "self_link_value" + assert isinstance(response, compute.RoutersGetRoutePolicyResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_rest_interceptors(null_interceptor): +def test_get_route_policy_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -7213,16 +9685,22 @@ def test_get_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_get") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_get_with_metadata" + transports.RoutersRestInterceptor, "post_get_route_policy" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_get_route_policy_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_get") as pre, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_get_route_policy" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetRouterRequest.pb(compute.GetRouterRequest()) + pb_message = compute.GetRoutePolicyRouterRequest.pb( + compute.GetRoutePolicyRouterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7233,19 +9711,24 @@ def test_get_rest_interceptors(null_interceptor): 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.Router.to_json(compute.Router()) + return_value = compute.RoutersGetRoutePolicyResponse.to_json( + compute.RoutersGetRoutePolicyResponse() + ) req.return_value.content = return_value - request = compute.GetRouterRequest() + request = compute.GetRoutePolicyRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Router() - post_with_metadata.return_value = compute.Router(), metadata + post.return_value = compute.RoutersGetRoutePolicyResponse() + post_with_metadata.return_value = ( + compute.RoutersGetRoutePolicyResponse(), + metadata, + ) - client.get( + client.get_route_policy( request, metadata=[ ("key", "val"), @@ -7258,8 +9741,8 @@ def test_get_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_nat_ip_info_rest_bad_request( - request_type=compute.GetNatIpInfoRouterRequest, +def test_get_router_status_rest_bad_request( + request_type=compute.GetRouterStatusRouterRequest, ): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -7281,17 +9764,17 @@ def test_get_nat_ip_info_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_nat_ip_info(request) + client.get_router_status(request) @pytest.mark.parametrize( "request_type", [ - compute.GetNatIpInfoRouterRequest, + compute.GetRouterStatusRouterRequest, dict, ], ) -def test_get_nat_ip_info_rest_call_success(request_type): +def test_get_router_status_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -7303,26 +9786,29 @@ def test_get_nat_ip_info_rest_call_success(request_type): # 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.NatIpInfoResponse() + return_value = compute.RouterStatusResponse( + kind="kind_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.NatIpInfoResponse.pb(return_value) + return_value = compute.RouterStatusResponse.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_nat_ip_info(request) + response = client.get_router_status(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.NatIpInfoResponse) + assert isinstance(response, compute.RouterStatusResponse) + assert response.kind == "kind_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_nat_ip_info_rest_interceptors(null_interceptor): +def test_get_router_status_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -7333,20 +9819,20 @@ def test_get_nat_ip_info_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.RoutersRestInterceptor, "post_get_nat_ip_info" + transports.RoutersRestInterceptor, "post_get_router_status" ) as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_get_nat_ip_info_with_metadata" + transports.RoutersRestInterceptor, "post_get_router_status_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.RoutersRestInterceptor, "pre_get_nat_ip_info" + transports.RoutersRestInterceptor, "pre_get_router_status" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetNatIpInfoRouterRequest.pb( - compute.GetNatIpInfoRouterRequest() + pb_message = compute.GetRouterStatusRouterRequest.pb( + compute.GetRouterStatusRouterRequest() ) transcode.return_value = { "method": "post", @@ -7358,19 +9844,21 @@ def test_get_nat_ip_info_rest_interceptors(null_interceptor): 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.NatIpInfoResponse.to_json(compute.NatIpInfoResponse()) + return_value = compute.RouterStatusResponse.to_json( + compute.RouterStatusResponse() + ) req.return_value.content = return_value - request = compute.GetNatIpInfoRouterRequest() + request = compute.GetRouterStatusRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.NatIpInfoResponse() - post_with_metadata.return_value = compute.NatIpInfoResponse(), metadata + post.return_value = compute.RouterStatusResponse() + post_with_metadata.return_value = compute.RouterStatusResponse(), metadata - client.get_nat_ip_info( + client.get_router_status( request, metadata=[ ("key", "val"), @@ -7383,56 +9871,278 @@ def test_get_nat_ip_info_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_nat_mapping_info_rest_bad_request( - request_type=compute.GetNatMappingInfoRoutersRequest, -): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} - request = request_type(**request_init) +def test_insert_rest_bad_request(request_type=compute.InsertRouterRequest): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.insert(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.InsertRouterRequest, + dict, + ], +) +def test_insert_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2"} + request_init["router_resource"] = { + "bgp": { + "advertise_mode": "advertise_mode_value", + "advertised_groups": [ + "advertised_groups_value1", + "advertised_groups_value2", + ], + "advertised_ip_ranges": [ + {"description": "description_value", "range_": "range__value"} + ], + "asn": 322, + "identifier_range": "identifier_range_value", + "keepalive_interval": 1914, + }, + "bgp_peers": [ + { + "advertise_mode": "advertise_mode_value", + "advertised_groups": [ + "advertised_groups_value1", + "advertised_groups_value2", + ], + "advertised_ip_ranges": {}, + "advertised_route_priority": 2714, + "bfd": { + "min_receive_interval": 2122, + "min_transmit_interval": 2265, + "multiplier": 1095, + "session_initialization_mode": "session_initialization_mode_value", + }, + "custom_learned_ip_ranges": [{"range_": "range__value"}], + "custom_learned_route_priority": 3140, + "enable": "enable_value", + "enable_ipv4": True, + "enable_ipv6": True, + "export_policies": ["export_policies_value1", "export_policies_value2"], + "import_policies": ["import_policies_value1", "import_policies_value2"], + "interface_name": "interface_name_value", + "ip_address": "ip_address_value", + "ipv4_nexthop_address": "ipv4_nexthop_address_value", + "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "management_type": "management_type_value", + "md5_authentication_key_name": "md5_authentication_key_name_value", + "name": "name_value", + "peer_asn": 845, + "peer_ip_address": "peer_ip_address_value", + "peer_ipv4_nexthop_address": "peer_ipv4_nexthop_address_value", + "peer_ipv6_nexthop_address": "peer_ipv6_nexthop_address_value", + "router_appliance_instance": "router_appliance_instance_value", + } + ], + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "encrypted_interconnect_router": True, + "id": 205, + "interfaces": [ + { + "ip_range": "ip_range_value", + "ip_version": "ip_version_value", + "linked_interconnect_attachment": "linked_interconnect_attachment_value", + "linked_vpn_tunnel": "linked_vpn_tunnel_value", + "management_type": "management_type_value", + "name": "name_value", + "private_ip_address": "private_ip_address_value", + "redundant_interface": "redundant_interface_value", + "subnetwork": "subnetwork_value", + } + ], + "kind": "kind_value", + "md5_authentication_keys": [{"key": "key_value", "name": "name_value"}], + "name": "name_value", + "nats": [ + { + "auto_network_tier": "auto_network_tier_value", + "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, + "enable_dynamic_port_allocation": True, + "enable_endpoint_independent_mapping": True, + "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], + "icmp_idle_timeout_sec": 2214, + "log_config": {"enable": True, "filter": "filter_value"}, + "max_ports_per_vm": 1733, + "min_ports_per_vm": 1731, + "name": "name_value", + "nat64_subnetworks": [{"name": "name_value"}], + "nat_ip_allocate_option": "nat_ip_allocate_option_value", + "nat_ips": ["nat_ips_value1", "nat_ips_value2"], + "rules": [ + { + "action": { + "source_nat_active_ips": [ + "source_nat_active_ips_value1", + "source_nat_active_ips_value2", + ], + "source_nat_active_ranges": [ + "source_nat_active_ranges_value1", + "source_nat_active_ranges_value2", + ], + "source_nat_drain_ips": [ + "source_nat_drain_ips_value1", + "source_nat_drain_ips_value2", + ], + "source_nat_drain_ranges": [ + "source_nat_drain_ranges_value1", + "source_nat_drain_ranges_value2", + ], + }, + "description": "description_value", + "match": "match_value", + "rule_number": 1184, + } + ], + "source_subnetwork_ip_ranges_to_nat": "source_subnetwork_ip_ranges_to_nat_value", + "source_subnetwork_ip_ranges_to_nat64": "source_subnetwork_ip_ranges_to_nat64_value", + "subnetworks": [ + { + "name": "name_value", + "secondary_ip_range_names": [ + "secondary_ip_range_names_value1", + "secondary_ip_range_names_value2", + ], + "source_ip_ranges_to_nat": [ + "source_ip_ranges_to_nat_value1", + "source_ip_ranges_to_nat_value2", + ], + } + ], + "tcp_established_idle_timeout_sec": 3371, + "tcp_time_wait_timeout_sec": 2665, + "tcp_transitory_idle_timeout_sec": 3330, + "type_": "type__value", + "udp_idle_timeout_sec": 2118, + } + ], + "ncc_gateway": "ncc_gateway_value", + "network": "network_value", + "params": {"resource_manager_tags": {}}, + "region": "region_value", + "self_link": "self_link_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.InsertRouterRequest.meta.fields["router_resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] - # 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_nat_mapping_info(request) + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["router_resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - compute.GetNatMappingInfoRoutersRequest, - dict, - ], -) -def test_get_nat_mapping_info_rest_call_success(request_type): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["router_resource"][field])): + del request_init["router_resource"][field][i][subfield] + else: + del request_init["router_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.VmEndpointNatMappingsList( - id="id_value", + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", kind="kind_value", - next_page_token="next_page_token_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", ) # Wrap the value into a proper Response obj @@ -7440,150 +10150,41 @@ def test_get_nat_mapping_info_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.VmEndpointNatMappingsList.pb(return_value) + return_value = compute.Operation.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_nat_mapping_info(request) + response = client.insert(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.GetNatMappingInfoPager) - assert response.id == "id_value" + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" - assert response.next_page_token == "next_page_token_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_nat_mapping_info_rest_interceptors(null_interceptor): - transport = transports.RoutersRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), - ) - client = RoutersClient(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.RoutersRestInterceptor, "post_get_nat_mapping_info" - ) as post, - mock.patch.object( - transports.RoutersRestInterceptor, "post_get_nat_mapping_info_with_metadata" - ) as post_with_metadata, - mock.patch.object( - transports.RoutersRestInterceptor, "pre_get_nat_mapping_info" - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = compute.GetNatMappingInfoRoutersRequest.pb( - compute.GetNatMappingInfoRoutersRequest() - ) - 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.VmEndpointNatMappingsList.to_json( - compute.VmEndpointNatMappingsList() - ) - req.return_value.content = return_value - - request = compute.GetNatMappingInfoRoutersRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = compute.VmEndpointNatMappingsList() - post_with_metadata.return_value = compute.VmEndpointNatMappingsList(), metadata - - client.get_nat_mapping_info( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) - - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() - - -def test_get_route_policy_rest_bad_request( - request_type=compute.GetRoutePolicyRouterRequest, -): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "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.get_route_policy(request) - - -@pytest.mark.parametrize( - "request_type", - [ - compute.GetRoutePolicyRouterRequest, - dict, - ], -) -def test_get_route_policy_rest_call_success(request_type): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "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.RoutersGetRoutePolicyResponse() - - # 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.RoutersGetRoutePolicyResponse.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_route_policy(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, compute.RoutersGetRoutePolicyResponse) - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_route_policy_rest_interceptors(null_interceptor): +def test_insert_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -7593,22 +10194,16 @@ def test_get_route_policy_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RoutersRestInterceptor, "post_insert") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_get_route_policy" - ) as post, - mock.patch.object( - transports.RoutersRestInterceptor, "post_get_route_policy_with_metadata" + transports.RoutersRestInterceptor, "post_insert_with_metadata" ) as post_with_metadata, - mock.patch.object( - transports.RoutersRestInterceptor, "pre_get_route_policy" - ) as pre, + mock.patch.object(transports.RoutersRestInterceptor, "pre_insert") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetRoutePolicyRouterRequest.pb( - compute.GetRoutePolicyRouterRequest() - ) + pb_message = compute.InsertRouterRequest.pb(compute.InsertRouterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7619,24 +10214,19 @@ def test_get_route_policy_rest_interceptors(null_interceptor): 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.RoutersGetRoutePolicyResponse.to_json( - compute.RoutersGetRoutePolicyResponse() - ) + return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.GetRoutePolicyRouterRequest() + request = compute.InsertRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.RoutersGetRoutePolicyResponse() - post_with_metadata.return_value = ( - compute.RoutersGetRoutePolicyResponse(), - metadata, - ) + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata - client.get_route_policy( + client.insert( request, metadata=[ ("key", "val"), @@ -7649,14 +10239,12 @@ def test_get_route_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_router_status_rest_bad_request( - request_type=compute.GetRouterStatusRouterRequest, -): +def test_list_rest_bad_request(request_type=compute.ListRoutersRequest): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + request_init = {"project": "sample1", "region": "sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7672,30 +10260,33 @@ def test_get_router_status_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_router_status(request) + client.list(request) @pytest.mark.parametrize( "request_type", [ - compute.GetRouterStatusRouterRequest, + compute.ListRoutersRequest, dict, ], ) -def test_get_router_status_rest_call_success(request_type): +def test_list_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + request_init = {"project": "sample1", "region": "sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RouterStatusResponse( + return_value = compute.RouterList( + 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 @@ -7703,20 +10294,23 @@ def test_get_router_status_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RouterStatusResponse.pb(return_value) + return_value = compute.RouterList.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_router_status(request) + response = client.list(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.RouterStatusResponse) + 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_get_router_status_rest_interceptors(null_interceptor): +def test_list_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -7726,22 +10320,16 @@ def test_get_router_status_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RoutersRestInterceptor, "post_list") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_get_router_status" - ) as post, - mock.patch.object( - transports.RoutersRestInterceptor, "post_get_router_status_with_metadata" + transports.RoutersRestInterceptor, "post_list_with_metadata" ) as post_with_metadata, - mock.patch.object( - transports.RoutersRestInterceptor, "pre_get_router_status" - ) as pre, + mock.patch.object(transports.RoutersRestInterceptor, "pre_list") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.GetRouterStatusRouterRequest.pb( - compute.GetRouterStatusRouterRequest() - ) + pb_message = compute.ListRoutersRequest.pb(compute.ListRoutersRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -7752,21 +10340,19 @@ def test_get_router_status_rest_interceptors(null_interceptor): 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.RouterStatusResponse.to_json( - compute.RouterStatusResponse() - ) + return_value = compute.RouterList.to_json(compute.RouterList()) req.return_value.content = return_value - request = compute.GetRouterStatusRouterRequest() + request = compute.ListRoutersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.RouterStatusResponse() - post_with_metadata.return_value = compute.RouterStatusResponse(), metadata + post.return_value = compute.RouterList() + post_with_metadata.return_value = compute.RouterList(), metadata - client.get_router_status( + client.list( request, metadata=[ ("key", "val"), @@ -7779,12 +10365,14 @@ def test_get_router_status_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_insert_rest_bad_request(request_type=compute.InsertRouterRequest): +def test_list_bgp_routes_rest_bad_request( + request_type=compute.ListBgpRoutesRoutersRequest, +): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2"} + request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -7796,259 +10384,179 @@ def test_insert_rest_bad_request(request_type=compute.InsertRouterRequest): 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.insert(request) - - -@pytest.mark.parametrize( - "request_type", - [ - compute.InsertRouterRequest, - dict, - ], -) -def test_insert_rest_call_success(request_type): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2"} - request_init["router_resource"] = { - "bgp": { - "advertise_mode": "advertise_mode_value", - "advertised_groups": [ - "advertised_groups_value1", - "advertised_groups_value2", - ], - "advertised_ip_ranges": [ - {"description": "description_value", "range_": "range__value"} - ], - "asn": 322, - "identifier_range": "identifier_range_value", - "keepalive_interval": 1914, - }, - "bgp_peers": [ - { - "advertise_mode": "advertise_mode_value", - "advertised_groups": [ - "advertised_groups_value1", - "advertised_groups_value2", - ], - "advertised_ip_ranges": {}, - "advertised_route_priority": 2714, - "bfd": { - "min_receive_interval": 2122, - "min_transmit_interval": 2265, - "multiplier": 1095, - "session_initialization_mode": "session_initialization_mode_value", - }, - "custom_learned_ip_ranges": [{"range_": "range__value"}], - "custom_learned_route_priority": 3140, - "enable": "enable_value", - "enable_ipv4": True, - "enable_ipv6": True, - "export_policies": ["export_policies_value1", "export_policies_value2"], - "import_policies": ["import_policies_value1", "import_policies_value2"], - "interface_name": "interface_name_value", - "ip_address": "ip_address_value", - "ipv4_nexthop_address": "ipv4_nexthop_address_value", - "ipv6_nexthop_address": "ipv6_nexthop_address_value", - "management_type": "management_type_value", - "md5_authentication_key_name": "md5_authentication_key_name_value", - "name": "name_value", - "peer_asn": 845, - "peer_ip_address": "peer_ip_address_value", - "peer_ipv4_nexthop_address": "peer_ipv4_nexthop_address_value", - "peer_ipv6_nexthop_address": "peer_ipv6_nexthop_address_value", - "router_appliance_instance": "router_appliance_instance_value", - } - ], - "creation_timestamp": "creation_timestamp_value", - "description": "description_value", - "encrypted_interconnect_router": True, - "id": 205, - "interfaces": [ - { - "ip_range": "ip_range_value", - "ip_version": "ip_version_value", - "linked_interconnect_attachment": "linked_interconnect_attachment_value", - "linked_vpn_tunnel": "linked_vpn_tunnel_value", - "management_type": "management_type_value", - "name": "name_value", - "private_ip_address": "private_ip_address_value", - "redundant_interface": "redundant_interface_value", - "subnetwork": "subnetwork_value", - } - ], - "kind": "kind_value", - "md5_authentication_keys": [{"key": "key_value", "name": "name_value"}], - "name": "name_value", - "nats": [ - { - "auto_network_tier": "auto_network_tier_value", - "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], - "enable_dynamic_port_allocation": True, - "enable_endpoint_independent_mapping": True, - "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], - "icmp_idle_timeout_sec": 2214, - "log_config": {"enable": True, "filter": "filter_value"}, - "max_ports_per_vm": 1733, - "min_ports_per_vm": 1731, - "name": "name_value", - "nat64_subnetworks": [{"name": "name_value"}], - "nat_ip_allocate_option": "nat_ip_allocate_option_value", - "nat_ips": ["nat_ips_value1", "nat_ips_value2"], - "rules": [ - { - "action": { - "source_nat_active_ips": [ - "source_nat_active_ips_value1", - "source_nat_active_ips_value2", - ], - "source_nat_active_ranges": [ - "source_nat_active_ranges_value1", - "source_nat_active_ranges_value2", - ], - "source_nat_drain_ips": [ - "source_nat_drain_ips_value1", - "source_nat_drain_ips_value2", - ], - "source_nat_drain_ranges": [ - "source_nat_drain_ranges_value1", - "source_nat_drain_ranges_value2", - ], - }, - "description": "description_value", - "match": "match_value", - "rule_number": 1184, - } - ], - "source_subnetwork_ip_ranges_to_nat": "source_subnetwork_ip_ranges_to_nat_value", - "source_subnetwork_ip_ranges_to_nat64": "source_subnetwork_ip_ranges_to_nat64_value", - "subnetworks": [ - { - "name": "name_value", - "secondary_ip_range_names": [ - "secondary_ip_range_names_value1", - "secondary_ip_range_names_value2", - ], - "source_ip_ranges_to_nat": [ - "source_ip_ranges_to_nat_value1", - "source_ip_ranges_to_nat_value2", - ], - } - ], - "tcp_established_idle_timeout_sec": 3371, - "tcp_time_wait_timeout_sec": 2665, - "tcp_transitory_idle_timeout_sec": 3330, - "type_": "type__value", - "udp_idle_timeout_sec": 2118, - } - ], - "network": "network_value", - "params": {"resource_manager_tags": {}}, - "region": "region_value", - "self_link": "self_link_value", - } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + 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_bgp_routes(request) - # Determine if the message type is proto-plus or protobuf - test_field = compute.InsertRouterRequest.meta.fields["router_resource"] - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] +@pytest.mark.parametrize( + "request_type", + [ + compute.ListBgpRoutesRoutersRequest, + dict, + ], +) +def test_list_bgp_routes_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + request = request_type(**request_init) - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields + # 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.RoutersListBgpRoutes( + etag="etag_value", + id="id_value", + kind="kind_value", + next_page_token="next_page_token_value", + self_link="self_link_value", + unreachables=["unreachables_value"], + ) - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 - subfields_not_in_runtime = [] + # Convert return value to protobuf type + return_value = compute.RoutersListBgpRoutes.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_bgp_routes(request) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["router_resource"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBgpRoutesPager) + assert response.etag == "etag_value" + 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" + assert response.unreachables == ["unreachables_value"] - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["router_resource"][field])): - del request_init["router_resource"][field][i][subfield] - else: - del request_init["router_resource"][field][subfield] +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_bgp_routes_rest_interceptors(null_interceptor): + transport = transports.RoutersRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), + ) + client = RoutersClient(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.RoutersRestInterceptor, "post_list_bgp_routes" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_list_bgp_routes_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_list_bgp_routes" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = compute.ListBgpRoutesRoutersRequest.pb( + compute.ListBgpRoutesRoutersRequest() + ) + 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.RoutersListBgpRoutes.to_json( + compute.RoutersListBgpRoutes() + ) + req.return_value.content = return_value + + request = compute.ListBgpRoutesRoutersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = compute.RoutersListBgpRoutes() + post_with_metadata.return_value = compute.RoutersListBgpRoutes(), metadata + + client.list_bgp_routes( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_named_sets_rest_bad_request( + request_type=compute.ListNamedSetsRoutersRequest, +): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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_named_sets(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.ListNamedSetsRoutersRequest, + dict, + ], +) +def test_list_named_sets_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "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.Operation( - client_operation_id="client_operation_id_value", - creation_timestamp="creation_timestamp_value", - description="description_value", - end_time="end_time_value", - http_error_message="http_error_message_value", - http_error_status_code=2374, - id=205, - insert_time="insert_time_value", + return_value = compute.RoutersListNamedSets( + etag="etag_value", + id="id_value", kind="kind_value", - name="name_value", - operation_group_id="operation_group_id_value", - operation_type="operation_type_value", - progress=885, - region="region_value", + next_page_token="next_page_token_value", self_link="self_link_value", - start_time="start_time_value", - status=compute.Operation.Status.DONE, - status_message="status_message_value", - target_id=947, - target_link="target_link_value", - user="user_value", - zone="zone_value", + unreachables=["unreachables_value"], ) # Wrap the value into a proper Response obj @@ -8056,41 +10564,25 @@ def get_message_fields(field): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.Operation.pb(return_value) + return_value = compute.RoutersListNamedSets.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.insert(request) + response = client.list_named_sets(request) # Establish that the response is the type that we expect. - assert isinstance(response, extended_operation.ExtendedOperation) - assert response.client_operation_id == "client_operation_id_value" - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.end_time == "end_time_value" - assert response.http_error_message == "http_error_message_value" - assert response.http_error_status_code == 2374 - assert response.id == 205 - assert response.insert_time == "insert_time_value" + assert isinstance(response, pagers.ListNamedSetsPager) + assert response.etag == "etag_value" + assert response.id == "id_value" assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.operation_group_id == "operation_group_id_value" - assert response.operation_type == "operation_type_value" - assert response.progress == 885 - assert response.region == "region_value" + assert response.next_page_token == "next_page_token_value" assert response.self_link == "self_link_value" - assert response.start_time == "start_time_value" - assert response.status == compute.Operation.Status.DONE - assert response.status_message == "status_message_value" - assert response.target_id == 947 - assert response.target_link == "target_link_value" - assert response.user == "user_value" - assert response.zone == "zone_value" + assert response.unreachables == ["unreachables_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_insert_rest_interceptors(null_interceptor): +def test_list_named_sets_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -8100,16 +10592,22 @@ def test_insert_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_insert") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_insert_with_metadata" + transports.RoutersRestInterceptor, "post_list_named_sets" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_list_named_sets_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_insert") as pre, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_list_named_sets" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.InsertRouterRequest.pb(compute.InsertRouterRequest()) + pb_message = compute.ListNamedSetsRoutersRequest.pb( + compute.ListNamedSetsRoutersRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8120,19 +10618,21 @@ def test_insert_rest_interceptors(null_interceptor): 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.Operation.to_json(compute.Operation()) + return_value = compute.RoutersListNamedSets.to_json( + compute.RoutersListNamedSets() + ) req.return_value.content = return_value - request = compute.InsertRouterRequest() + request = compute.ListNamedSetsRoutersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Operation() - post_with_metadata.return_value = compute.Operation(), metadata + post.return_value = compute.RoutersListNamedSets() + post_with_metadata.return_value = compute.RoutersListNamedSets(), metadata - client.insert( + client.list_named_sets( request, metadata=[ ("key", "val"), @@ -8145,12 +10645,14 @@ def test_insert_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_rest_bad_request(request_type=compute.ListRoutersRequest): +def test_list_route_policies_rest_bad_request( + request_type=compute.ListRoutePoliciesRoutersRequest, +): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2"} + request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8166,33 +10668,35 @@ def test_list_rest_bad_request(request_type=compute.ListRoutersRequest): 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) + client.list_route_policies(request) @pytest.mark.parametrize( "request_type", [ - compute.ListRoutersRequest, + compute.ListRoutePoliciesRoutersRequest, dict, ], ) -def test_list_rest_call_success(request_type): +def test_list_route_policies_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2"} + request_init = {"project": "sample1", "region": "sample2", "router": "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.RouterList( + return_value = compute.RoutersListRoutePolicies( + etag="etag_value", id="id_value", kind="kind_value", next_page_token="next_page_token_value", self_link="self_link_value", + unreachables=["unreachables_value"], ) # Wrap the value into a proper Response obj @@ -8200,23 +10704,25 @@ def test_list_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RouterList.pb(return_value) + return_value = compute.RoutersListRoutePolicies.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) + response = client.list_route_policies(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListPager) + assert isinstance(response, pagers.ListRoutePoliciesPager) + assert response.etag == "etag_value" 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" + assert response.unreachables == ["unreachables_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_rest_interceptors(null_interceptor): +def test_list_route_policies_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -8226,16 +10732,22 @@ def test_list_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_list") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_list_with_metadata" + transports.RoutersRestInterceptor, "post_list_route_policies" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_list_route_policies_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_list") as pre, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_list_route_policies" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.ListRoutersRequest.pb(compute.ListRoutersRequest()) + pb_message = compute.ListRoutePoliciesRoutersRequest.pb( + compute.ListRoutePoliciesRoutersRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8246,19 +10758,21 @@ def test_list_rest_interceptors(null_interceptor): 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.RouterList.to_json(compute.RouterList()) + return_value = compute.RoutersListRoutePolicies.to_json( + compute.RoutersListRoutePolicies() + ) req.return_value.content = return_value - request = compute.ListRoutersRequest() + request = compute.ListRoutePoliciesRoutersRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.RouterList() - post_with_metadata.return_value = compute.RouterList(), metadata + post.return_value = compute.RoutersListRoutePolicies() + post_with_metadata.return_value = compute.RoutersListRoutePolicies(), metadata - client.list( + client.list_route_policies( request, metadata=[ ("key", "val"), @@ -8271,9 +10785,7 @@ def test_list_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_bgp_routes_rest_bad_request( - request_type=compute.ListBgpRoutesRoutersRequest, -): +def test_patch_rest_bad_request(request_type=compute.PatchRouterRequest): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8294,35 +10806,257 @@ def test_list_bgp_routes_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_bgp_routes(request) + client.patch(request) + + +@pytest.mark.parametrize( + "request_type", + [ + compute.PatchRouterRequest, + dict, + ], +) +def test_patch_rest_call_success(request_type): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + request_init["router_resource"] = { + "bgp": { + "advertise_mode": "advertise_mode_value", + "advertised_groups": [ + "advertised_groups_value1", + "advertised_groups_value2", + ], + "advertised_ip_ranges": [ + {"description": "description_value", "range_": "range__value"} + ], + "asn": 322, + "identifier_range": "identifier_range_value", + "keepalive_interval": 1914, + }, + "bgp_peers": [ + { + "advertise_mode": "advertise_mode_value", + "advertised_groups": [ + "advertised_groups_value1", + "advertised_groups_value2", + ], + "advertised_ip_ranges": {}, + "advertised_route_priority": 2714, + "bfd": { + "min_receive_interval": 2122, + "min_transmit_interval": 2265, + "multiplier": 1095, + "session_initialization_mode": "session_initialization_mode_value", + }, + "custom_learned_ip_ranges": [{"range_": "range__value"}], + "custom_learned_route_priority": 3140, + "enable": "enable_value", + "enable_ipv4": True, + "enable_ipv6": True, + "export_policies": ["export_policies_value1", "export_policies_value2"], + "import_policies": ["import_policies_value1", "import_policies_value2"], + "interface_name": "interface_name_value", + "ip_address": "ip_address_value", + "ipv4_nexthop_address": "ipv4_nexthop_address_value", + "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "management_type": "management_type_value", + "md5_authentication_key_name": "md5_authentication_key_name_value", + "name": "name_value", + "peer_asn": 845, + "peer_ip_address": "peer_ip_address_value", + "peer_ipv4_nexthop_address": "peer_ipv4_nexthop_address_value", + "peer_ipv6_nexthop_address": "peer_ipv6_nexthop_address_value", + "router_appliance_instance": "router_appliance_instance_value", + } + ], + "creation_timestamp": "creation_timestamp_value", + "description": "description_value", + "encrypted_interconnect_router": True, + "id": 205, + "interfaces": [ + { + "ip_range": "ip_range_value", + "ip_version": "ip_version_value", + "linked_interconnect_attachment": "linked_interconnect_attachment_value", + "linked_vpn_tunnel": "linked_vpn_tunnel_value", + "management_type": "management_type_value", + "name": "name_value", + "private_ip_address": "private_ip_address_value", + "redundant_interface": "redundant_interface_value", + "subnetwork": "subnetwork_value", + } + ], + "kind": "kind_value", + "md5_authentication_keys": [{"key": "key_value", "name": "name_value"}], + "name": "name_value", + "nats": [ + { + "auto_network_tier": "auto_network_tier_value", + "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, + "enable_dynamic_port_allocation": True, + "enable_endpoint_independent_mapping": True, + "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], + "icmp_idle_timeout_sec": 2214, + "log_config": {"enable": True, "filter": "filter_value"}, + "max_ports_per_vm": 1733, + "min_ports_per_vm": 1731, + "name": "name_value", + "nat64_subnetworks": [{"name": "name_value"}], + "nat_ip_allocate_option": "nat_ip_allocate_option_value", + "nat_ips": ["nat_ips_value1", "nat_ips_value2"], + "rules": [ + { + "action": { + "source_nat_active_ips": [ + "source_nat_active_ips_value1", + "source_nat_active_ips_value2", + ], + "source_nat_active_ranges": [ + "source_nat_active_ranges_value1", + "source_nat_active_ranges_value2", + ], + "source_nat_drain_ips": [ + "source_nat_drain_ips_value1", + "source_nat_drain_ips_value2", + ], + "source_nat_drain_ranges": [ + "source_nat_drain_ranges_value1", + "source_nat_drain_ranges_value2", + ], + }, + "description": "description_value", + "match": "match_value", + "rule_number": 1184, + } + ], + "source_subnetwork_ip_ranges_to_nat": "source_subnetwork_ip_ranges_to_nat_value", + "source_subnetwork_ip_ranges_to_nat64": "source_subnetwork_ip_ranges_to_nat64_value", + "subnetworks": [ + { + "name": "name_value", + "secondary_ip_range_names": [ + "secondary_ip_range_names_value1", + "secondary_ip_range_names_value2", + ], + "source_ip_ranges_to_nat": [ + "source_ip_ranges_to_nat_value1", + "source_ip_ranges_to_nat_value2", + ], + } + ], + "tcp_established_idle_timeout_sec": 3371, + "tcp_time_wait_timeout_sec": 2665, + "tcp_transitory_idle_timeout_sec": 3330, + "type_": "type__value", + "udp_idle_timeout_sec": 2118, + } + ], + "ncc_gateway": "ncc_gateway_value", + "network": "network_value", + "params": {"resource_manager_tags": {}}, + "region": "region_value", + "self_link": "self_link_value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.PatchRouterRequest.meta.fields["router_resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["router_resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value -@pytest.mark.parametrize( - "request_type", - [ - compute.ListBgpRoutesRoutersRequest, - dict, - ], -) -def test_list_bgp_routes_rest_call_success(request_type): - client = RoutersClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) - # send a request that will satisfy transcoding - request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["router_resource"][field])): + del request_init["router_resource"][field][i][subfield] + else: + del request_init["router_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RoutersListBgpRoutes( - etag="etag_value", - id="id_value", + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", kind="kind_value", - next_page_token="next_page_token_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", self_link="self_link_value", - unreachables=["unreachables_value"], + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", ) # Wrap the value into a proper Response obj @@ -8330,25 +11064,41 @@ def test_list_bgp_routes_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersListBgpRoutes.pb(return_value) + return_value = compute.Operation.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_bgp_routes(request) + response = client.patch(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBgpRoutesPager) - assert response.etag == "etag_value" - assert response.id == "id_value" + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" - assert response.next_page_token == "next_page_token_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" assert response.self_link == "self_link_value" - assert response.unreachables == ["unreachables_value"] + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_bgp_routes_rest_interceptors(null_interceptor): +def test_patch_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -8358,22 +11108,16 @@ def test_list_bgp_routes_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RoutersRestInterceptor, "post_patch") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_list_bgp_routes" - ) as post, - mock.patch.object( - transports.RoutersRestInterceptor, "post_list_bgp_routes_with_metadata" + transports.RoutersRestInterceptor, "post_patch_with_metadata" ) as post_with_metadata, - mock.patch.object( - transports.RoutersRestInterceptor, "pre_list_bgp_routes" - ) as pre, + mock.patch.object(transports.RoutersRestInterceptor, "pre_patch") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.ListBgpRoutesRoutersRequest.pb( - compute.ListBgpRoutesRoutersRequest() - ) + pb_message = compute.PatchRouterRequest.pb(compute.PatchRouterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8384,21 +11128,19 @@ def test_list_bgp_routes_rest_interceptors(null_interceptor): 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.RoutersListBgpRoutes.to_json( - compute.RoutersListBgpRoutes() - ) + return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.ListBgpRoutesRoutersRequest() + request = compute.PatchRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.RoutersListBgpRoutes() - post_with_metadata.return_value = compute.RoutersListBgpRoutes(), metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata - client.list_bgp_routes( + client.patch( request, metadata=[ ("key", "val"), @@ -8411,8 +11153,8 @@ def test_list_bgp_routes_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_list_route_policies_rest_bad_request( - request_type=compute.ListRoutePoliciesRoutersRequest, +def test_patch_named_set_rest_bad_request( + request_type=compute.PatchNamedSetRouterRequest, ): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -8434,35 +11176,132 @@ def test_list_route_policies_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_route_policies(request) + client.patch_named_set(request) @pytest.mark.parametrize( "request_type", [ - compute.ListRoutePoliciesRoutersRequest, + compute.PatchNamedSetRouterRequest, dict, ], ) -def test_list_route_policies_rest_call_success(request_type): +def test_patch_named_set_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} + request_init["named_set_resource"] = { + "description": "description_value", + "elements": [ + { + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", + } + ], + "fingerprint": "fingerprint_value", + "name": "name_value", + "type_": "type__value", + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = compute.PatchNamedSetRouterRequest.meta.fields["named_set_resource"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["named_set_resource"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["named_set_resource"][field])): + del request_init["named_set_resource"][field][i][subfield] + else: + del request_init["named_set_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.RoutersListRoutePolicies( - etag="etag_value", - id="id_value", + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", kind="kind_value", - next_page_token="next_page_token_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", self_link="self_link_value", - unreachables=["unreachables_value"], + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_value", ) # Wrap the value into a proper Response obj @@ -8470,25 +11309,41 @@ def test_list_route_policies_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = compute.RoutersListRoutePolicies.pb(return_value) + return_value = compute.Operation.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_route_policies(request) + response = client.patch_named_set(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListRoutePoliciesPager) - assert response.etag == "etag_value" - assert response.id == "id_value" + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" - assert response.next_page_token == "next_page_token_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" assert response.self_link == "self_link_value" - assert response.unreachables == ["unreachables_value"] + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_route_policies_rest_interceptors(null_interceptor): +def test_patch_named_set_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -8499,20 +11354,20 @@ def test_list_route_policies_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.RoutersRestInterceptor, "post_list_route_policies" + transports.RoutersRestInterceptor, "post_patch_named_set" ) as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_list_route_policies_with_metadata" + transports.RoutersRestInterceptor, "post_patch_named_set_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.RoutersRestInterceptor, "pre_list_route_policies" + transports.RoutersRestInterceptor, "pre_patch_named_set" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.ListRoutePoliciesRoutersRequest.pb( - compute.ListRoutePoliciesRoutersRequest() + pb_message = compute.PatchNamedSetRouterRequest.pb( + compute.PatchNamedSetRouterRequest() ) transcode.return_value = { "method": "post", @@ -8524,21 +11379,19 @@ def test_list_route_policies_rest_interceptors(null_interceptor): 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.RoutersListRoutePolicies.to_json( - compute.RoutersListRoutePolicies() - ) + return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.ListRoutePoliciesRoutersRequest() + request = compute.PatchNamedSetRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.RoutersListRoutePolicies() - post_with_metadata.return_value = compute.RoutersListRoutePolicies(), metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata - client.list_route_policies( + client.patch_named_set( request, metadata=[ ("key", "val"), @@ -8551,7 +11404,9 @@ def test_list_route_policies_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_patch_rest_bad_request(request_type=compute.PatchRouterRequest): +def test_patch_route_policy_rest_bad_request( + request_type=compute.PatchRoutePolicyRouterRequest, +): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8572,166 +11427,51 @@ def test_patch_rest_bad_request(request_type=compute.PatchRouterRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.patch(request) + client.patch_route_policy(request) @pytest.mark.parametrize( "request_type", [ - compute.PatchRouterRequest, + compute.PatchRoutePolicyRouterRequest, dict, ], ) -def test_patch_rest_call_success(request_type): +def test_patch_route_policy_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} - request_init["router_resource"] = { - "bgp": { - "advertise_mode": "advertise_mode_value", - "advertised_groups": [ - "advertised_groups_value1", - "advertised_groups_value2", - ], - "advertised_ip_ranges": [ - {"description": "description_value", "range_": "range__value"} - ], - "asn": 322, - "identifier_range": "identifier_range_value", - "keepalive_interval": 1914, - }, - "bgp_peers": [ - { - "advertise_mode": "advertise_mode_value", - "advertised_groups": [ - "advertised_groups_value1", - "advertised_groups_value2", - ], - "advertised_ip_ranges": {}, - "advertised_route_priority": 2714, - "bfd": { - "min_receive_interval": 2122, - "min_transmit_interval": 2265, - "multiplier": 1095, - "session_initialization_mode": "session_initialization_mode_value", - }, - "custom_learned_ip_ranges": [{"range_": "range__value"}], - "custom_learned_route_priority": 3140, - "enable": "enable_value", - "enable_ipv4": True, - "enable_ipv6": True, - "export_policies": ["export_policies_value1", "export_policies_value2"], - "import_policies": ["import_policies_value1", "import_policies_value2"], - "interface_name": "interface_name_value", - "ip_address": "ip_address_value", - "ipv4_nexthop_address": "ipv4_nexthop_address_value", - "ipv6_nexthop_address": "ipv6_nexthop_address_value", - "management_type": "management_type_value", - "md5_authentication_key_name": "md5_authentication_key_name_value", - "name": "name_value", - "peer_asn": 845, - "peer_ip_address": "peer_ip_address_value", - "peer_ipv4_nexthop_address": "peer_ipv4_nexthop_address_value", - "peer_ipv6_nexthop_address": "peer_ipv6_nexthop_address_value", - "router_appliance_instance": "router_appliance_instance_value", - } - ], - "creation_timestamp": "creation_timestamp_value", + request_init["route_policy_resource"] = { "description": "description_value", - "encrypted_interconnect_router": True, - "id": 205, - "interfaces": [ - { - "ip_range": "ip_range_value", - "ip_version": "ip_version_value", - "linked_interconnect_attachment": "linked_interconnect_attachment_value", - "linked_vpn_tunnel": "linked_vpn_tunnel_value", - "management_type": "management_type_value", - "name": "name_value", - "private_ip_address": "private_ip_address_value", - "redundant_interface": "redundant_interface_value", - "subnetwork": "subnetwork_value", - } - ], - "kind": "kind_value", - "md5_authentication_keys": [{"key": "key_value", "name": "name_value"}], + "fingerprint": "fingerprint_value", "name": "name_value", - "nats": [ + "terms": [ { - "auto_network_tier": "auto_network_tier_value", - "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], - "enable_dynamic_port_allocation": True, - "enable_endpoint_independent_mapping": True, - "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], - "icmp_idle_timeout_sec": 2214, - "log_config": {"enable": True, "filter": "filter_value"}, - "max_ports_per_vm": 1733, - "min_ports_per_vm": 1731, - "name": "name_value", - "nat64_subnetworks": [{"name": "name_value"}], - "nat_ip_allocate_option": "nat_ip_allocate_option_value", - "nat_ips": ["nat_ips_value1", "nat_ips_value2"], - "rules": [ + "actions": [ { - "action": { - "source_nat_active_ips": [ - "source_nat_active_ips_value1", - "source_nat_active_ips_value2", - ], - "source_nat_active_ranges": [ - "source_nat_active_ranges_value1", - "source_nat_active_ranges_value2", - ], - "source_nat_drain_ips": [ - "source_nat_drain_ips_value1", - "source_nat_drain_ips_value2", - ], - "source_nat_drain_ranges": [ - "source_nat_drain_ranges_value1", - "source_nat_drain_ranges_value2", - ], - }, "description": "description_value", - "match": "match_value", - "rule_number": 1184, - } - ], - "source_subnetwork_ip_ranges_to_nat": "source_subnetwork_ip_ranges_to_nat_value", - "source_subnetwork_ip_ranges_to_nat64": "source_subnetwork_ip_ranges_to_nat64_value", - "subnetworks": [ - { - "name": "name_value", - "secondary_ip_range_names": [ - "secondary_ip_range_names_value1", - "secondary_ip_range_names_value2", - ], - "source_ip_ranges_to_nat": [ - "source_ip_ranges_to_nat_value1", - "source_ip_ranges_to_nat_value2", - ], + "expression": "expression_value", + "location": "location_value", + "title": "title_value", } ], - "tcp_established_idle_timeout_sec": 3371, - "tcp_time_wait_timeout_sec": 2665, - "tcp_transitory_idle_timeout_sec": 3330, - "type_": "type__value", - "udp_idle_timeout_sec": 2118, + "match": {}, + "priority": 898, } ], - "network": "network_value", - "params": {"resource_manager_tags": {}}, - "region": "region_value", - "self_link": "self_link_value", + "type_": "type__value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = compute.PatchRouterRequest.meta.fields["router_resource"] + test_field = compute.PatchRoutePolicyRouterRequest.meta.fields[ + "route_policy_resource" + ] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -8759,7 +11499,9 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["router_resource"].items(): # pragma: NO COVER + for field, value in request_init[ + "route_policy_resource" + ].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -8789,10 +11531,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["router_resource"][field])): - del request_init["router_resource"][field][i][subfield] + for i in range(0, len(request_init["route_policy_resource"][field])): + del request_init["route_policy_resource"][field][i][subfield] else: - del request_init["router_resource"][field][subfield] + del request_init["route_policy_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -8833,7 +11575,7 @@ def get_message_fields(field): 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.patch(request) + response = client.patch_route_policy(request) # Establish that the response is the type that we expect. assert isinstance(response, extended_operation.ExtendedOperation) @@ -8862,7 +11604,7 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_patch_rest_interceptors(null_interceptor): +def test_patch_route_policy_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -8872,16 +11614,22 @@ def test_patch_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_patch") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_patch_with_metadata" + transports.RoutersRestInterceptor, "post_patch_route_policy" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_patch_route_policy_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_patch") as pre, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_patch_route_policy" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.PatchRouterRequest.pb(compute.PatchRouterRequest()) + pb_message = compute.PatchRoutePolicyRouterRequest.pb( + compute.PatchRoutePolicyRouterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8895,7 +11643,7 @@ def test_patch_rest_interceptors(null_interceptor): return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.PatchRouterRequest() + request = compute.PatchRoutePolicyRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -8904,7 +11652,7 @@ def test_patch_rest_interceptors(null_interceptor): post.return_value = compute.Operation() post_with_metadata.return_value = compute.Operation(), metadata - client.patch( + client.patch_route_policy( request, metadata=[ ("key", "val"), @@ -8917,9 +11665,7 @@ def test_patch_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_patch_route_policy_rest_bad_request( - request_type=compute.PatchRoutePolicyRouterRequest, -): +def test_preview_rest_bad_request(request_type=compute.PreviewRouterRequest): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -8940,51 +11686,168 @@ def test_patch_route_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.patch_route_policy(request) + client.preview(request) @pytest.mark.parametrize( "request_type", [ - compute.PatchRoutePolicyRouterRequest, + compute.PreviewRouterRequest, dict, ], ) -def test_patch_route_policy_rest_call_success(request_type): +def test_preview_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} - request_init["route_policy_resource"] = { + request_init["router_resource"] = { + "bgp": { + "advertise_mode": "advertise_mode_value", + "advertised_groups": [ + "advertised_groups_value1", + "advertised_groups_value2", + ], + "advertised_ip_ranges": [ + {"description": "description_value", "range_": "range__value"} + ], + "asn": 322, + "identifier_range": "identifier_range_value", + "keepalive_interval": 1914, + }, + "bgp_peers": [ + { + "advertise_mode": "advertise_mode_value", + "advertised_groups": [ + "advertised_groups_value1", + "advertised_groups_value2", + ], + "advertised_ip_ranges": {}, + "advertised_route_priority": 2714, + "bfd": { + "min_receive_interval": 2122, + "min_transmit_interval": 2265, + "multiplier": 1095, + "session_initialization_mode": "session_initialization_mode_value", + }, + "custom_learned_ip_ranges": [{"range_": "range__value"}], + "custom_learned_route_priority": 3140, + "enable": "enable_value", + "enable_ipv4": True, + "enable_ipv6": True, + "export_policies": ["export_policies_value1", "export_policies_value2"], + "import_policies": ["import_policies_value1", "import_policies_value2"], + "interface_name": "interface_name_value", + "ip_address": "ip_address_value", + "ipv4_nexthop_address": "ipv4_nexthop_address_value", + "ipv6_nexthop_address": "ipv6_nexthop_address_value", + "management_type": "management_type_value", + "md5_authentication_key_name": "md5_authentication_key_name_value", + "name": "name_value", + "peer_asn": 845, + "peer_ip_address": "peer_ip_address_value", + "peer_ipv4_nexthop_address": "peer_ipv4_nexthop_address_value", + "peer_ipv6_nexthop_address": "peer_ipv6_nexthop_address_value", + "router_appliance_instance": "router_appliance_instance_value", + } + ], + "creation_timestamp": "creation_timestamp_value", "description": "description_value", - "fingerprint": "fingerprint_value", + "encrypted_interconnect_router": True, + "id": 205, + "interfaces": [ + { + "ip_range": "ip_range_value", + "ip_version": "ip_version_value", + "linked_interconnect_attachment": "linked_interconnect_attachment_value", + "linked_vpn_tunnel": "linked_vpn_tunnel_value", + "management_type": "management_type_value", + "name": "name_value", + "private_ip_address": "private_ip_address_value", + "redundant_interface": "redundant_interface_value", + "subnetwork": "subnetwork_value", + } + ], + "kind": "kind_value", + "md5_authentication_keys": [{"key": "key_value", "name": "name_value"}], "name": "name_value", - "terms": [ + "nats": [ { - "actions": [ + "auto_network_tier": "auto_network_tier_value", + "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, + "enable_dynamic_port_allocation": True, + "enable_endpoint_independent_mapping": True, + "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], + "icmp_idle_timeout_sec": 2214, + "log_config": {"enable": True, "filter": "filter_value"}, + "max_ports_per_vm": 1733, + "min_ports_per_vm": 1731, + "name": "name_value", + "nat64_subnetworks": [{"name": "name_value"}], + "nat_ip_allocate_option": "nat_ip_allocate_option_value", + "nat_ips": ["nat_ips_value1", "nat_ips_value2"], + "rules": [ { + "action": { + "source_nat_active_ips": [ + "source_nat_active_ips_value1", + "source_nat_active_ips_value2", + ], + "source_nat_active_ranges": [ + "source_nat_active_ranges_value1", + "source_nat_active_ranges_value2", + ], + "source_nat_drain_ips": [ + "source_nat_drain_ips_value1", + "source_nat_drain_ips_value2", + ], + "source_nat_drain_ranges": [ + "source_nat_drain_ranges_value1", + "source_nat_drain_ranges_value2", + ], + }, "description": "description_value", - "expression": "expression_value", - "location": "location_value", - "title": "title_value", + "match": "match_value", + "rule_number": 1184, } ], - "match": {}, - "priority": 898, + "source_subnetwork_ip_ranges_to_nat": "source_subnetwork_ip_ranges_to_nat_value", + "source_subnetwork_ip_ranges_to_nat64": "source_subnetwork_ip_ranges_to_nat64_value", + "subnetworks": [ + { + "name": "name_value", + "secondary_ip_range_names": [ + "secondary_ip_range_names_value1", + "secondary_ip_range_names_value2", + ], + "source_ip_ranges_to_nat": [ + "source_ip_ranges_to_nat_value1", + "source_ip_ranges_to_nat_value2", + ], + } + ], + "tcp_established_idle_timeout_sec": 3371, + "tcp_time_wait_timeout_sec": 2665, + "tcp_transitory_idle_timeout_sec": 3330, + "type_": "type__value", + "udp_idle_timeout_sec": 2118, } ], - "type_": "type__value", + "ncc_gateway": "ncc_gateway_value", + "network": "network_value", + "params": {"resource_manager_tags": {}}, + "region": "region_value", + "self_link": "self_link_value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = compute.PatchRoutePolicyRouterRequest.meta.fields[ - "route_policy_resource" - ] + test_field = compute.PreviewRouterRequest.meta.fields["router_resource"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -9012,9 +11875,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init[ - "route_policy_resource" - ].items(): # pragma: NO COVER + for field, value in request_init["router_resource"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -9044,80 +11905,35 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["route_policy_resource"][field])): - del request_init["route_policy_resource"][field][i][subfield] + for i in range(0, len(request_init["router_resource"][field])): + del request_init["router_resource"][field][i][subfield] else: - del request_init["route_policy_resource"][field][subfield] + del request_init["router_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = compute.Operation( - client_operation_id="client_operation_id_value", - creation_timestamp="creation_timestamp_value", - description="description_value", - end_time="end_time_value", - http_error_message="http_error_message_value", - http_error_status_code=2374, - id=205, - insert_time="insert_time_value", - kind="kind_value", - name="name_value", - operation_group_id="operation_group_id_value", - operation_type="operation_type_value", - progress=885, - region="region_value", - self_link="self_link_value", - start_time="start_time_value", - status=compute.Operation.Status.DONE, - status_message="status_message_value", - target_id=947, - target_link="target_link_value", - user="user_value", - zone="zone_value", - ) + return_value = compute.RoutersPreviewResponse() # 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.Operation.pb(return_value) + return_value = compute.RoutersPreviewResponse.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.patch_route_policy(request) + response = client.preview(request) # Establish that the response is the type that we expect. - assert isinstance(response, extended_operation.ExtendedOperation) - assert response.client_operation_id == "client_operation_id_value" - assert response.creation_timestamp == "creation_timestamp_value" - assert response.description == "description_value" - assert response.end_time == "end_time_value" - assert response.http_error_message == "http_error_message_value" - assert response.http_error_status_code == 2374 - assert response.id == 205 - assert response.insert_time == "insert_time_value" - assert response.kind == "kind_value" - assert response.name == "name_value" - assert response.operation_group_id == "operation_group_id_value" - assert response.operation_type == "operation_type_value" - assert response.progress == 885 - assert response.region == "region_value" - assert response.self_link == "self_link_value" - assert response.start_time == "start_time_value" - assert response.status == compute.Operation.Status.DONE - assert response.status_message == "status_message_value" - assert response.target_id == 947 - assert response.target_link == "target_link_value" - assert response.user == "user_value" - assert response.zone == "zone_value" + assert isinstance(response, compute.RoutersPreviewResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_patch_route_policy_rest_interceptors(null_interceptor): +def test_preview_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -9127,22 +11943,16 @@ def test_patch_route_policy_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(transports.RoutersRestInterceptor, "post_preview") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_patch_route_policy" - ) as post, - mock.patch.object( - transports.RoutersRestInterceptor, "post_patch_route_policy_with_metadata" + transports.RoutersRestInterceptor, "post_preview_with_metadata" ) as post_with_metadata, - mock.patch.object( - transports.RoutersRestInterceptor, "pre_patch_route_policy" - ) as pre, + mock.patch.object(transports.RoutersRestInterceptor, "pre_preview") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.PatchRoutePolicyRouterRequest.pb( - compute.PatchRoutePolicyRouterRequest() - ) + pb_message = compute.PreviewRouterRequest.pb(compute.PreviewRouterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9153,19 +11963,21 @@ def test_patch_route_policy_rest_interceptors(null_interceptor): 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.Operation.to_json(compute.Operation()) + return_value = compute.RoutersPreviewResponse.to_json( + compute.RoutersPreviewResponse() + ) req.return_value.content = return_value - request = compute.PatchRoutePolicyRouterRequest() + request = compute.PreviewRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.Operation() - post_with_metadata.return_value = compute.Operation(), metadata + post.return_value = compute.RoutersPreviewResponse() + post_with_metadata.return_value = compute.RoutersPreviewResponse(), metadata - client.patch_route_policy( + client.preview( request, metadata=[ ("key", "val"), @@ -9178,7 +11990,7 @@ def test_patch_route_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_preview_rest_bad_request(request_type=compute.PreviewRouterRequest): +def test_update_rest_bad_request(request_type=compute.UpdateRouterRequest): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9199,17 +12011,17 @@ def test_preview_rest_bad_request(request_type=compute.PreviewRouterRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.preview(request) + client.update(request) @pytest.mark.parametrize( "request_type", [ - compute.PreviewRouterRequest, + compute.UpdateRouterRequest, dict, ], ) -def test_preview_rest_call_success(request_type): +def test_update_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9290,6 +12102,7 @@ def test_preview_rest_call_success(request_type): { "auto_network_tier": "auto_network_tier_value", "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], + "effective_tcp_time_wait_timeout_sec": 3705, "enable_dynamic_port_allocation": True, "enable_endpoint_independent_mapping": True, "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], @@ -9348,6 +12161,7 @@ def test_preview_rest_call_success(request_type): "udp_idle_timeout_sec": 2118, } ], + "ncc_gateway": "ncc_gateway_value", "network": "network_value", "params": {"resource_manager_tags": {}}, "region": "region_value", @@ -9358,7 +12172,7 @@ def test_preview_rest_call_success(request_type): # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = compute.PreviewRouterRequest.meta.fields["router_resource"] + test_field = compute.UpdateRouterRequest.meta.fields["router_resource"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -9425,26 +12239,71 @@ def get_message_fields(field): # 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.RoutersPreviewResponse() + return_value = compute.Operation( + client_operation_id="client_operation_id_value", + creation_timestamp="creation_timestamp_value", + description="description_value", + end_time="end_time_value", + http_error_message="http_error_message_value", + http_error_status_code=2374, + id=205, + insert_time="insert_time_value", + kind="kind_value", + name="name_value", + operation_group_id="operation_group_id_value", + operation_type="operation_type_value", + progress=885, + region="region_value", + self_link="self_link_value", + start_time="start_time_value", + status=compute.Operation.Status.DONE, + status_message="status_message_value", + target_id=947, + target_link="target_link_value", + user="user_value", + zone="zone_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.RoutersPreviewResponse.pb(return_value) + return_value = compute.Operation.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.preview(request) + response = client.update(request) # Establish that the response is the type that we expect. - assert isinstance(response, compute.RoutersPreviewResponse) + assert isinstance(response, extended_operation.ExtendedOperation) + assert response.client_operation_id == "client_operation_id_value" + assert response.creation_timestamp == "creation_timestamp_value" + assert response.description == "description_value" + assert response.end_time == "end_time_value" + assert response.http_error_message == "http_error_message_value" + assert response.http_error_status_code == 2374 + assert response.id == 205 + assert response.insert_time == "insert_time_value" + assert response.kind == "kind_value" + assert response.name == "name_value" + assert response.operation_group_id == "operation_group_id_value" + assert response.operation_type == "operation_type_value" + assert response.progress == 885 + assert response.region == "region_value" + assert response.self_link == "self_link_value" + assert response.start_time == "start_time_value" + assert response.status == compute.Operation.Status.DONE + assert response.status_message == "status_message_value" + assert response.target_id == 947 + assert response.target_link == "target_link_value" + assert response.user == "user_value" + assert response.zone == "zone_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_preview_rest_interceptors(null_interceptor): +def test_update_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -9454,16 +12313,16 @@ def test_preview_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_preview") as post, + mock.patch.object(transports.RoutersRestInterceptor, "post_update") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_preview_with_metadata" + transports.RoutersRestInterceptor, "post_update_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_preview") as pre, + mock.patch.object(transports.RoutersRestInterceptor, "pre_update") as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.PreviewRouterRequest.pb(compute.PreviewRouterRequest()) + pb_message = compute.UpdateRouterRequest.pb(compute.UpdateRouterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9474,21 +12333,19 @@ def test_preview_rest_interceptors(null_interceptor): 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.RoutersPreviewResponse.to_json( - compute.RoutersPreviewResponse() - ) + return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.PreviewRouterRequest() + request = compute.UpdateRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = compute.RoutersPreviewResponse() - post_with_metadata.return_value = compute.RoutersPreviewResponse(), metadata + post.return_value = compute.Operation() + post_with_metadata.return_value = compute.Operation(), metadata - client.preview( + client.update( request, metadata=[ ("key", "val"), @@ -9501,7 +12358,9 @@ def test_preview_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_rest_bad_request(request_type=compute.UpdateRouterRequest): +def test_update_named_set_rest_bad_request( + request_type=compute.UpdateNamedSetRouterRequest, +): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9522,166 +12381,43 @@ def test_update_rest_bad_request(request_type=compute.UpdateRouterRequest): response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update(request) + client.update_named_set(request) @pytest.mark.parametrize( "request_type", [ - compute.UpdateRouterRequest, + compute.UpdateNamedSetRouterRequest, dict, ], ) -def test_update_rest_call_success(request_type): +def test_update_named_set_rest_call_success(request_type): client = RoutersClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "region": "sample2", "router": "sample3"} - request_init["router_resource"] = { - "bgp": { - "advertise_mode": "advertise_mode_value", - "advertised_groups": [ - "advertised_groups_value1", - "advertised_groups_value2", - ], - "advertised_ip_ranges": [ - {"description": "description_value", "range_": "range__value"} - ], - "asn": 322, - "identifier_range": "identifier_range_value", - "keepalive_interval": 1914, - }, - "bgp_peers": [ - { - "advertise_mode": "advertise_mode_value", - "advertised_groups": [ - "advertised_groups_value1", - "advertised_groups_value2", - ], - "advertised_ip_ranges": {}, - "advertised_route_priority": 2714, - "bfd": { - "min_receive_interval": 2122, - "min_transmit_interval": 2265, - "multiplier": 1095, - "session_initialization_mode": "session_initialization_mode_value", - }, - "custom_learned_ip_ranges": [{"range_": "range__value"}], - "custom_learned_route_priority": 3140, - "enable": "enable_value", - "enable_ipv4": True, - "enable_ipv6": True, - "export_policies": ["export_policies_value1", "export_policies_value2"], - "import_policies": ["import_policies_value1", "import_policies_value2"], - "interface_name": "interface_name_value", - "ip_address": "ip_address_value", - "ipv4_nexthop_address": "ipv4_nexthop_address_value", - "ipv6_nexthop_address": "ipv6_nexthop_address_value", - "management_type": "management_type_value", - "md5_authentication_key_name": "md5_authentication_key_name_value", - "name": "name_value", - "peer_asn": 845, - "peer_ip_address": "peer_ip_address_value", - "peer_ipv4_nexthop_address": "peer_ipv4_nexthop_address_value", - "peer_ipv6_nexthop_address": "peer_ipv6_nexthop_address_value", - "router_appliance_instance": "router_appliance_instance_value", - } - ], - "creation_timestamp": "creation_timestamp_value", + request_init["named_set_resource"] = { "description": "description_value", - "encrypted_interconnect_router": True, - "id": 205, - "interfaces": [ + "elements": [ { - "ip_range": "ip_range_value", - "ip_version": "ip_version_value", - "linked_interconnect_attachment": "linked_interconnect_attachment_value", - "linked_vpn_tunnel": "linked_vpn_tunnel_value", - "management_type": "management_type_value", - "name": "name_value", - "private_ip_address": "private_ip_address_value", - "redundant_interface": "redundant_interface_value", - "subnetwork": "subnetwork_value", + "description": "description_value", + "expression": "expression_value", + "location": "location_value", + "title": "title_value", } ], - "kind": "kind_value", - "md5_authentication_keys": [{"key": "key_value", "name": "name_value"}], + "fingerprint": "fingerprint_value", "name": "name_value", - "nats": [ - { - "auto_network_tier": "auto_network_tier_value", - "drain_nat_ips": ["drain_nat_ips_value1", "drain_nat_ips_value2"], - "enable_dynamic_port_allocation": True, - "enable_endpoint_independent_mapping": True, - "endpoint_types": ["endpoint_types_value1", "endpoint_types_value2"], - "icmp_idle_timeout_sec": 2214, - "log_config": {"enable": True, "filter": "filter_value"}, - "max_ports_per_vm": 1733, - "min_ports_per_vm": 1731, - "name": "name_value", - "nat64_subnetworks": [{"name": "name_value"}], - "nat_ip_allocate_option": "nat_ip_allocate_option_value", - "nat_ips": ["nat_ips_value1", "nat_ips_value2"], - "rules": [ - { - "action": { - "source_nat_active_ips": [ - "source_nat_active_ips_value1", - "source_nat_active_ips_value2", - ], - "source_nat_active_ranges": [ - "source_nat_active_ranges_value1", - "source_nat_active_ranges_value2", - ], - "source_nat_drain_ips": [ - "source_nat_drain_ips_value1", - "source_nat_drain_ips_value2", - ], - "source_nat_drain_ranges": [ - "source_nat_drain_ranges_value1", - "source_nat_drain_ranges_value2", - ], - }, - "description": "description_value", - "match": "match_value", - "rule_number": 1184, - } - ], - "source_subnetwork_ip_ranges_to_nat": "source_subnetwork_ip_ranges_to_nat_value", - "source_subnetwork_ip_ranges_to_nat64": "source_subnetwork_ip_ranges_to_nat64_value", - "subnetworks": [ - { - "name": "name_value", - "secondary_ip_range_names": [ - "secondary_ip_range_names_value1", - "secondary_ip_range_names_value2", - ], - "source_ip_ranges_to_nat": [ - "source_ip_ranges_to_nat_value1", - "source_ip_ranges_to_nat_value2", - ], - } - ], - "tcp_established_idle_timeout_sec": 3371, - "tcp_time_wait_timeout_sec": 2665, - "tcp_transitory_idle_timeout_sec": 3330, - "type_": "type__value", - "udp_idle_timeout_sec": 2118, - } - ], - "network": "network_value", - "params": {"resource_manager_tags": {}}, - "region": "region_value", - "self_link": "self_link_value", + "type_": "type__value", } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency # See https://github.com/googleapis/gapic-generator-python/issues/1748 # Determine if the message type is proto-plus or protobuf - test_field = compute.UpdateRouterRequest.meta.fields["router_resource"] + test_field = compute.UpdateNamedSetRouterRequest.meta.fields["named_set_resource"] def get_message_fields(field): # Given a field which is a message (composite type), return a list with @@ -9709,7 +12445,7 @@ def get_message_fields(field): # For each item in the sample request, create a list of sub fields which are not present at runtime # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["router_resource"].items(): # pragma: NO COVER + for field, value in request_init["named_set_resource"].items(): # pragma: NO COVER result = None is_repeated = False # For repeated fields @@ -9739,10 +12475,10 @@ def get_message_fields(field): subfield = subfield_to_delete.get("subfield") if subfield: if field_repeated: - for i in range(0, len(request_init["router_resource"][field])): - del request_init["router_resource"][field][i][subfield] + for i in range(0, len(request_init["named_set_resource"][field])): + del request_init["named_set_resource"][field][i][subfield] else: - del request_init["router_resource"][field][subfield] + del request_init["named_set_resource"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9783,7 +12519,7 @@ def get_message_fields(field): 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.update(request) + response = client.update_named_set(request) # Establish that the response is the type that we expect. assert isinstance(response, extended_operation.ExtendedOperation) @@ -9812,7 +12548,7 @@ def get_message_fields(field): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_rest_interceptors(null_interceptor): +def test_update_named_set_rest_interceptors(null_interceptor): transport = transports.RoutersRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None if null_interceptor else transports.RoutersRestInterceptor(), @@ -9822,16 +12558,22 @@ def test_update_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(transports.RoutersRestInterceptor, "post_update") as post, mock.patch.object( - transports.RoutersRestInterceptor, "post_update_with_metadata" + transports.RoutersRestInterceptor, "post_update_named_set" + ) as post, + mock.patch.object( + transports.RoutersRestInterceptor, "post_update_named_set_with_metadata" ) as post_with_metadata, - mock.patch.object(transports.RoutersRestInterceptor, "pre_update") as pre, + mock.patch.object( + transports.RoutersRestInterceptor, "pre_update_named_set" + ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = compute.UpdateRouterRequest.pb(compute.UpdateRouterRequest()) + pb_message = compute.UpdateNamedSetRouterRequest.pb( + compute.UpdateNamedSetRouterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9845,7 +12587,7 @@ def test_update_rest_interceptors(null_interceptor): return_value = compute.Operation.to_json(compute.Operation()) req.return_value.content = return_value - request = compute.UpdateRouterRequest() + request = compute.UpdateNamedSetRouterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9854,7 +12596,7 @@ def test_update_rest_interceptors(null_interceptor): post.return_value = compute.Operation() post_with_metadata.return_value = compute.Operation(), metadata - client.update( + client.update_named_set( request, metadata=[ ("key", "val"), @@ -10173,6 +12915,25 @@ def test_delete_unary_empty_call_rest(): 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_delete_named_set_unary_empty_call_rest(): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_named_set), "__call__") as call: + client.delete_named_set_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.DeleteNamedSetRouterRequest() + 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_delete_route_policy_unary_empty_call_rest(): @@ -10213,6 +12974,25 @@ def test_get_empty_call_rest(): 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_get_named_set_empty_call_rest(): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_named_set), "__call__") as call: + client.get_named_set(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.GetNamedSetRouterRequest() + 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_get_nat_ip_info_empty_call_rest(): @@ -10350,6 +13130,25 @@ def test_list_bgp_routes_empty_call_rest(): 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_named_sets_empty_call_rest(): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_named_sets), "__call__") as call: + client.list_named_sets(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.ListNamedSetsRoutersRequest() + 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_route_policies_empty_call_rest(): @@ -10390,6 +13189,25 @@ def test_patch_unary_empty_call_rest(): 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_patch_named_set_unary_empty_call_rest(): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.patch_named_set), "__call__") as call: + client.patch_named_set_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.PatchNamedSetRouterRequest() + 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_patch_route_policy_unary_empty_call_rest(): @@ -10449,6 +13267,25 @@ def test_update_unary_empty_call_rest(): 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_update_named_set_unary_empty_call_rest(): + client = RoutersClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_named_set), "__call__") as call: + client.update_named_set_unary(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = compute.UpdateNamedSetRouterRequest() + 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_update_route_policy_unary_empty_call_rest(): @@ -10494,8 +13331,10 @@ def test_routers_base_transport(): methods = ( "aggregated_list", "delete", + "delete_named_set", "delete_route_policy", "get", + "get_named_set", "get_nat_ip_info", "get_nat_mapping_info", "get_route_policy", @@ -10503,11 +13342,14 @@ def test_routers_base_transport(): "insert", "list", "list_bgp_routes", + "list_named_sets", "list_route_policies", "patch", + "patch_named_set", "patch_route_policy", "preview", "update", + "update_named_set", "update_route_policy", ) for method in methods: @@ -10658,12 +13500,18 @@ def test_routers_client_transport_session_collision(transport_name): session1 = client1.transport.delete._session session2 = client2.transport.delete._session assert session1 != session2 + session1 = client1.transport.delete_named_set._session + session2 = client2.transport.delete_named_set._session + assert session1 != session2 session1 = client1.transport.delete_route_policy._session session2 = client2.transport.delete_route_policy._session assert session1 != session2 session1 = client1.transport.get._session session2 = client2.transport.get._session assert session1 != session2 + session1 = client1.transport.get_named_set._session + session2 = client2.transport.get_named_set._session + assert session1 != session2 session1 = client1.transport.get_nat_ip_info._session session2 = client2.transport.get_nat_ip_info._session assert session1 != session2 @@ -10685,12 +13533,18 @@ def test_routers_client_transport_session_collision(transport_name): session1 = client1.transport.list_bgp_routes._session session2 = client2.transport.list_bgp_routes._session assert session1 != session2 + session1 = client1.transport.list_named_sets._session + session2 = client2.transport.list_named_sets._session + assert session1 != session2 session1 = client1.transport.list_route_policies._session session2 = client2.transport.list_route_policies._session assert session1 != session2 session1 = client1.transport.patch._session session2 = client2.transport.patch._session assert session1 != session2 + session1 = client1.transport.patch_named_set._session + session2 = client2.transport.patch_named_set._session + assert session1 != session2 session1 = client1.transport.patch_route_policy._session session2 = client2.transport.patch_route_policy._session assert session1 != session2 @@ -10700,6 +13554,9 @@ def test_routers_client_transport_session_collision(transport_name): session1 = client1.transport.update._session session2 = client2.transport.update._session assert session1 != session2 + session1 = client1.transport.update_named_set._session + session2 = client2.transport.update_named_set._session + assert session1 != session2 session1 = client1.transport.update_route_policy._session session2 = client2.transport.update_route_policy._session assert session1 != session2 diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py index af7f9b060cdb..d21e71ca823b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_security_policies.py @@ -6355,7 +6355,11 @@ def test_insert_rest_call_success(request_type): } ], "creation_timestamp": "creation_timestamp_value", - "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "ddos_protection_config": { + "ddos_adaptive_protection": "ddos_adaptive_protection_value", + "ddos_impacted_baseline_threshold": 0.33580000000000004, + "ddos_protection": "ddos_protection_value", + }, "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, @@ -7055,7 +7059,11 @@ def test_patch_rest_call_success(request_type): } ], "creation_timestamp": "creation_timestamp_value", - "ddos_protection_config": {"ddos_protection": "ddos_protection_value"}, + "ddos_protection_config": { + "ddos_adaptive_protection": "ddos_adaptive_protection_value", + "ddos_impacted_baseline_threshold": 0.33580000000000004, + "ddos_protection": "ddos_protection_value", + }, "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py index 6adc0665da45..1eaefbe09d7b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_service_attachments.py @@ -4339,6 +4339,7 @@ def test_get_rest_call_success(request_type): id=205, kind="kind_value", name="name_value", + nat_ips_per_endpoint=2132, nat_subnets=["nat_subnets_value"], producer_forwarding_rule="producer_forwarding_rule_value", propagated_connection_limit=2868, @@ -4372,6 +4373,7 @@ def test_get_rest_call_success(request_type): assert response.id == 205 assert response.kind == "kind_value" assert response.name == "name_value" + assert response.nat_ips_per_endpoint == 2132 assert response.nat_subnets == ["nat_subnets_value"] assert response.producer_forwarding_rule == "producer_forwarding_rule_value" assert response.propagated_connection_limit == 2868 @@ -4652,6 +4654,7 @@ def test_insert_rest_call_success(request_type): "kind": "kind_value", "metadata": {}, "name": "name_value", + "nat_ips_per_endpoint": 2132, "nat_subnets": ["nat_subnets_value1", "nat_subnets_value2"], "producer_forwarding_rule": "producer_forwarding_rule_value", "propagated_connection_limit": 2868, @@ -5082,6 +5085,7 @@ def test_patch_rest_call_success(request_type): "kind": "kind_value", "metadata": {}, "name": "name_value", + "nat_ips_per_endpoint": 2132, "nat_subnets": ["nat_subnets_value1", "nat_subnets_value2"], "producer_forwarding_rule": "producer_forwarding_rule_value", "propagated_connection_limit": 2868, diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py index 6c0d6698b4e8..9af73b7fc30b 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_subnetworks.py @@ -5999,6 +5999,8 @@ def test_insert_rest_call_success(request_type): "secondary_ip_ranges": [ { "ip_cidr_range": "ip_cidr_range_value", + "ip_collection": "ip_collection_value", + "ip_version": "ip_version_value", "range_name": "range_name_value", "reserved_internal_range": "reserved_internal_range_value", } @@ -6571,6 +6573,8 @@ def test_patch_rest_call_success(request_type): "secondary_ip_ranges": [ { "ip_cidr_range": "ip_cidr_range_value", + "ip_collection": "ip_collection_value", + "ip_version": "ip_version_value", "range_name": "range_name_value", "reserved_internal_range": "reserved_internal_range_value", } diff --git a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py index bb0aa3099880..219626e2c844 100644 --- a/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py +++ b/packages/google-cloud-compute/tests/unit/gapic/compute_v1/test_target_tcp_proxies.py @@ -4186,6 +4186,7 @@ def test_get_rest_call_success(request_type): description="description_value", id=205, kind="kind_value", + load_balancing_scheme="load_balancing_scheme_value", name="name_value", proxy_bind=True, proxy_header="proxy_header_value", @@ -4212,6 +4213,7 @@ def test_get_rest_call_success(request_type): assert response.description == "description_value" assert response.id == 205 assert response.kind == "kind_value" + assert response.load_balancing_scheme == "load_balancing_scheme_value" assert response.name == "name_value" assert response.proxy_bind is True assert response.proxy_header == "proxy_header_value" @@ -4325,6 +4327,7 @@ def test_insert_rest_call_success(request_type): "description": "description_value", "id": 205, "kind": "kind_value", + "load_balancing_scheme": "load_balancing_scheme_value", "name": "name_value", "proxy_bind": True, "proxy_header": "proxy_header_value", diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/__init__.py index 677d45994ed6..4947cf6c48a6 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/__init__.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/__init__.py @@ -369,6 +369,8 @@ GetSipTrunkRequest, ListSipTrunksRequest, ListSipTrunksResponse, + ProbeDetails, + SipHostname, SipTrunk, UpdateSipTrunkRequest, ) @@ -726,6 +728,7 @@ def _get_version(dependency_name): "ParticipantsClient", "PhoneNumber", "PhoneNumbersClient", + "ProbeDetails", "QueryInput", "QueryParameters", "QueryResult", @@ -750,6 +753,7 @@ def _get_version(dependency_name): "SetSuggestionFeatureConfigOperationMetadata", "SetSuggestionFeatureConfigRequest", "SipConfig", + "SipHostname", "SipTrunk", "SipTrunksClient", "SmartReplyAnswer", diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/async_client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/async_client.py index b580e149e123..2eafd0e37eee 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/async_client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/async_client.py @@ -324,6 +324,7 @@ async def sample_create_sip_trunk(): # Initialize request argument(s) sip_trunk = dialogflow_v2beta1.SipTrunk() sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.CreateSipTrunkRequest( parent="parent_value", @@ -789,6 +790,7 @@ async def sample_update_sip_trunk(): # Initialize request argument(s) sip_trunk = dialogflow_v2beta1.SipTrunk() sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.UpdateSipTrunkRequest( sip_trunk=sip_trunk, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/client.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/client.py index 43f0c2b07a79..7c9d1206b6f4 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/client.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/services/sip_trunks/client.py @@ -761,6 +761,7 @@ def sample_create_sip_trunk(): # Initialize request argument(s) sip_trunk = dialogflow_v2beta1.SipTrunk() sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.CreateSipTrunkRequest( parent="parent_value", @@ -1214,6 +1215,7 @@ def sample_update_sip_trunk(): # Initialize request argument(s) sip_trunk = dialogflow_v2beta1.SipTrunk() sip_trunk.expected_hostname = ['expected_hostname_value1', 'expected_hostname_value2'] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.UpdateSipTrunkRequest( sip_trunk=sip_trunk, diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/__init__.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/__init__.py index 2ac08d2586ab..6e2809bbb066 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/__init__.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/__init__.py @@ -342,6 +342,8 @@ GetSipTrunkRequest, ListSipTrunksRequest, ListSipTrunksResponse, + ProbeDetails, + SipHostname, SipTrunk, UpdateSipTrunkRequest, ) @@ -657,6 +659,8 @@ "GetSipTrunkRequest", "ListSipTrunksRequest", "ListSipTrunksResponse", + "ProbeDetails", + "SipHostname", "SipTrunk", "UpdateSipTrunkRequest", "CreateToolRequest", diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/participant.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/participant.py index f390755708ef..c19db07c9f5e 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/participant.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/participant.py @@ -3785,55 +3785,8 @@ class TurnInput(proto.Message): virtual_agent_parameters (google.protobuf.struct_pb2.Struct): Optional. Parameters to be passed to the virtual agent. - tool_responses (google.cloud.dialogflow_v2beta1.types.BidiStreamingAnalyzeContentRequest.TurnInput.ToolResponses): - Optional. The tool responses from the client. """ - class ToolResponse(proto.Message): - r"""The execution result of a specific tool from the client. - - Attributes: - id (str): - Required. The matching ID of the tool call - the response is for. - tool (str): - Required. The identifier of the tool that got - executed. - response (google.protobuf.struct_pb2.Struct): - Optional. The tool execution result in JSON - object format. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - tool: str = proto.Field( - proto.STRING, - number=2, - ) - response: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - class ToolResponses(proto.Message): - r"""The tool responses from the client. - - Attributes: - tool_responses (MutableSequence[google.cloud.dialogflow_v2beta1.types.BidiStreamingAnalyzeContentRequest.TurnInput.ToolResponse]): - Optional. The list of tool responses. - """ - - tool_responses: MutableSequence[ - "BidiStreamingAnalyzeContentRequest.TurnInput.ToolResponse" - ] = proto.RepeatedField( - proto.MESSAGE, - number=1, - message="BidiStreamingAnalyzeContentRequest.TurnInput.ToolResponse", - ) - text: str = proto.Field( proto.STRING, number=1, @@ -3854,13 +3807,6 @@ class ToolResponses(proto.Message): number=4, message=struct_pb2.Struct, ) - tool_responses: "BidiStreamingAnalyzeContentRequest.TurnInput.ToolResponses" = ( - proto.Field( - proto.MESSAGE, - number=5, - message="BidiStreamingAnalyzeContentRequest.TurnInput.ToolResponses", - ) - ) class Input(proto.Message): r"""Input for the conversation. @@ -3950,10 +3896,6 @@ class BidiStreamingAnalyzeContentResponse(proto.Message): turn_complete (google.cloud.dialogflow_v2beta1.types.BidiStreamingAnalyzeContentResponse.TurnComplete): Indicate that the turn is complete. - This field is a member of `oneof`_ ``response``. - tool_calls (google.cloud.dialogflow_v2beta1.types.BidiStreamingAnalyzeContentResponse.ToolCalls): - The tool calls from the server. - This field is a member of `oneof`_ ``response``. """ @@ -3963,49 +3905,6 @@ class BargeInSignal(proto.Message): class TurnComplete(proto.Message): r"""Indicate that the turn is complete.""" - class ToolCall(proto.Message): - r"""Request for the client to execute the specified tool. - - Attributes: - id (str): - The unique identifier of the tool call. - tool (str): - The identifier of the tool to execute. - args (google.protobuf.struct_pb2.Struct): - The input parameters and values for the tool - in JSON object format. - """ - - id: str = proto.Field( - proto.STRING, - number=1, - ) - tool: str = proto.Field( - proto.STRING, - number=2, - ) - args: struct_pb2.Struct = proto.Field( - proto.MESSAGE, - number=3, - message=struct_pb2.Struct, - ) - - class ToolCalls(proto.Message): - r"""The tool calls from the server. - - Attributes: - tool_calls (MutableSequence[google.cloud.dialogflow_v2beta1.types.BidiStreamingAnalyzeContentResponse.ToolCall]): - The list of tool calls. - """ - - tool_calls: MutableSequence["BidiStreamingAnalyzeContentResponse.ToolCall"] = ( - proto.RepeatedField( - proto.MESSAGE, - number=1, - message="BidiStreamingAnalyzeContentResponse.ToolCall", - ) - ) - recognition_result: session.StreamingRecognitionResult = proto.Field( proto.MESSAGE, number=1, @@ -4030,12 +3929,6 @@ class ToolCalls(proto.Message): oneof="response", message=TurnComplete, ) - tool_calls: ToolCalls = proto.Field( - proto.MESSAGE, - number=5, - oneof="response", - message=ToolCalls, - ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/sip_trunk.py b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/sip_trunk.py index f4769ac9a461..495cc291190f 100644 --- a/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/sip_trunk.py +++ b/packages/google-cloud-dialogflow/google/cloud/dialogflow_v2beta1/types/sip_trunk.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore import proto # type: ignore @@ -32,6 +33,8 @@ "UpdateSipTrunkRequest", "SipTrunk", "Connection", + "SipHostname", + "ProbeDetails", }, ) @@ -192,8 +195,26 @@ class SipTrunk(proto.Message): display_name (str): Optional. Human readable alias for this trunk. + peer_hostnames (MutableSequence[google.cloud.dialogflow_v2beta1.types.SipHostname]): + Required. Peer hostnames of the SIP trunk. + google_root_cert_file (google.cloud.dialogflow_v2beta1.types.SipTrunk.GoogleRootCertFile): + Optional. The root certificate file to use + for this SIP trunk. """ + class GoogleRootCertFile(proto.Enum): + r"""The type of Google root certificate file used for mTLS. + + Values: + CERT_FILE_UNSPECIFIED (0): + Unspecified root certificate file. + EXTERNAL_PRIVATE_CA (5): + Use external private CA. + """ + + CERT_FILE_UNSPECIFIED = 0 + EXTERNAL_PRIVATE_CA = 5 + name: str = proto.Field( proto.STRING, number=1, @@ -211,6 +232,16 @@ class SipTrunk(proto.Message): proto.STRING, number=4, ) + peer_hostnames: MutableSequence["SipHostname"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="SipHostname", + ) + google_root_cert_file: GoogleRootCertFile = proto.Field( + proto.ENUM, + number=9, + enum=GoogleRootCertFile, + ) class Connection(proto.Message): @@ -349,4 +380,194 @@ class ErrorDetails(proto.Message): ) +class SipHostname(proto.Message): + r"""Represents a peer hostname for SIP Trunk. + + Attributes: + peer_hostname (str): + Required. Peer hostname name. + enabled_sip_ping (bool): + Output only. Peer hostname enabled for SIP + ping. + ping_interval (google.protobuf.duration_pb2.Duration): + Output only. How often the sip ping should + occur. + peer_socket_address (str): + Output only. The peer_socket address of the partner SBC + pinged. + probe_details (google.cloud.dialogflow_v2beta1.types.ProbeDetails): + Output only. The details from the options + probe. + connection_state (google.cloud.dialogflow_v2beta1.types.SipHostname.ConnectionState): + Output only. State of the connection. + error_details (google.cloud.dialogflow_v2beta1.types.SipHostname.HostnameErrorDetails): + Output only. The error details for the + connection. Only populated when authentication + errors occur. + """ + + class ConnectionState(proto.Enum): + r"""The state of SBC hostname connection. + + Values: + CONNECTION_STATE_UNSPECIFIED (0): + SBC hostname connection state is Not + specified. + CONNECTED (1): + SBC hostname connection is connected. + DISCONNECTED (2): + SBC hostname connection is disconnected. + AUTHENTICATION_FAILED (3): + SBC hostname connection has authentication + error. + KEEPALIVE (4): + SBC hostname connection is keepalive. + """ + + CONNECTION_STATE_UNSPECIFIED = 0 + CONNECTED = 1 + DISCONNECTED = 2 + AUTHENTICATION_FAILED = 3 + KEEPALIVE = 4 + + class HostnameCertificateState(proto.Enum): + r"""The state of Sip Trunk certificate authentication. + + Values: + HOSTNAME_CERTIFICATE_STATE_UNSPECIFIED (0): + Certificate state is not specified. + VALID (1): + Certificate is valid. + INVALID (2): + Catch all for any error not specified. + EXPIRED (3): + Certificate leaf node has expired. + HOSTNAME_NOT_FOUND (4): + There is no hostname defined to authenticate + in SipTrunkingServer. + UNAUTHENTICATED (5): + No path found from the leaf certificate to + any root. + TRUST_STORE_NOT_FOUND (6): + Trust store does not exist. + HOSTNAME_INVALID_FORMAT (7): + Hostname has invalid format. + QUOTA_EXCEEDED (8): + Certificate has exhausted its quota. + """ + + HOSTNAME_CERTIFICATE_STATE_UNSPECIFIED = 0 + VALID = 1 + INVALID = 2 + EXPIRED = 3 + HOSTNAME_NOT_FOUND = 4 + UNAUTHENTICATED = 5 + TRUST_STORE_NOT_FOUND = 6 + HOSTNAME_INVALID_FORMAT = 7 + QUOTA_EXCEEDED = 8 + + class HostnameErrorDetails(proto.Message): + r"""The error details of Sip Trunk hostnameconnection + authentication. + + Attributes: + certificate_state (google.cloud.dialogflow_v2beta1.types.SipHostname.HostnameCertificateState): + Output only. The status of the certificate + authentication. + error_message (str): + Output only. The error message provided from + SIP trunking auth service + """ + + certificate_state: "SipHostname.HostnameCertificateState" = proto.Field( + proto.ENUM, + number=1, + enum="SipHostname.HostnameCertificateState", + ) + error_message: str = proto.Field( + proto.STRING, + number=2, + ) + + peer_hostname: str = proto.Field( + proto.STRING, + number=1, + ) + enabled_sip_ping: bool = proto.Field( + proto.BOOL, + number=2, + ) + ping_interval: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + peer_socket_address: str = proto.Field( + proto.STRING, + number=4, + ) + probe_details: "ProbeDetails" = proto.Field( + proto.MESSAGE, + number=5, + message="ProbeDetails", + ) + connection_state: ConnectionState = proto.Field( + proto.ENUM, + number=6, + enum=ConnectionState, + ) + error_details: HostnameErrorDetails = proto.Field( + proto.MESSAGE, + number=7, + message=HostnameErrorDetails, + ) + + +class ProbeDetails(proto.Message): + r"""The probe details of Sip Trunk peer hostname. + + Attributes: + options_latency (google.protobuf.duration_pb2.Duration): + Output only. Duration between OPTIONS send + and OPTIONS 200 received. + probe_status (google.cloud.dialogflow_v2beta1.types.ProbeDetails.ProbeStatus): + Output only. Result of the probe. + init_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. When the options probe was + started. + """ + + class ProbeStatus(proto.Enum): + r"""The status of InitiateSipOptionsPing to peer hostname. + + Values: + PROBE_STATUS_UNSPECIFIED (0): + Peer hostname ping state is not specified. + PROBE_STATUS_SUCCESS (1): + Peer hostname ping succeeded. + PROBE_STATUS_FAILED (2): + Peer hostname ping failed. + """ + + PROBE_STATUS_UNSPECIFIED = 0 + PROBE_STATUS_SUCCESS = 1 + PROBE_STATUS_FAILED = 2 + + options_latency: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=1, + message=duration_pb2.Duration, + ) + probe_status: ProbeStatus = proto.Field( + proto.ENUM, + number=2, + enum=ProbeStatus, + ) + init_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_async.py index 1a9f3c5bf8f6..89b10511344c 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_async.py +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_async.py @@ -44,6 +44,7 @@ async def sample_create_sip_trunk(): "expected_hostname_value1", "expected_hostname_value2", ] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.CreateSipTrunkRequest( parent="parent_value", diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_sync.py index 59bdaf2c3640..7a4f92ab65e7 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_sync.py +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_create_sip_trunk_sync.py @@ -44,6 +44,7 @@ def sample_create_sip_trunk(): "expected_hostname_value1", "expected_hostname_value2", ] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.CreateSipTrunkRequest( parent="parent_value", diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_async.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_async.py index 5855a223a447..90d0621ec2f5 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_async.py +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_async.py @@ -44,6 +44,7 @@ async def sample_update_sip_trunk(): "expected_hostname_value1", "expected_hostname_value2", ] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.UpdateSipTrunkRequest( sip_trunk=sip_trunk, diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_sync.py b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_sync.py index a65f920dbd62..88fd85e99dc2 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_sync.py +++ b/packages/google-cloud-dialogflow/samples/generated_samples/dialogflow_v2beta1_generated_sip_trunks_update_sip_trunk_sync.py @@ -44,6 +44,7 @@ def sample_update_sip_trunk(): "expected_hostname_value1", "expected_hostname_value2", ] + sip_trunk.peer_hostnames.peer_hostname = "peer_hostname_value" request = dialogflow_v2beta1.UpdateSipTrunkRequest( sip_trunk=sip_trunk, diff --git a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json index 647d7e817b2f..94843ff63847 100644 --- a/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json +++ b/packages/google-cloud-dialogflow/samples/generated_samples/snippet_metadata_google.cloud.dialogflow.v2beta1.json @@ -17811,12 +17811,12 @@ "regionTag": "dialogflow_v2beta1_generated_SipTrunks_CreateSipTrunk_async", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -17826,18 +17826,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], @@ -17895,12 +17895,12 @@ "regionTag": "dialogflow_v2beta1_generated_SipTrunks_CreateSipTrunk_sync", "segments": [ { - "end": 55, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 56, "start": 27, "type": "SHORT" }, @@ -17910,18 +17910,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 49, + "end": 50, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 52, - "start": 50, + "end": 53, + "start": 51, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], @@ -18457,12 +18457,12 @@ "regionTag": "dialogflow_v2beta1_generated_SipTrunks_UpdateSipTrunk_async", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -18472,18 +18472,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], @@ -18541,12 +18541,12 @@ "regionTag": "dialogflow_v2beta1_generated_SipTrunks_UpdateSipTrunk_sync", "segments": [ { - "end": 54, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 54, + "end": 55, "start": 27, "type": "SHORT" }, @@ -18556,18 +18556,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 48, + "end": 49, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 51, - "start": 49, + "end": 52, + "start": 50, "type": "REQUEST_EXECUTION" }, { - "end": 55, - "start": 52, + "end": 56, + "start": 53, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_sip_trunks.py b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_sip_trunks.py index 31a626f00894..c3a13d3c32e9 100644 --- a/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_sip_trunks.py +++ b/packages/google-cloud-dialogflow/tests/unit/gapic/dialogflow_v2beta1/test_sip_trunks.py @@ -39,6 +39,7 @@ HAS_GOOGLE_AUTH_AIO = False import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore from google.api_core import ( @@ -1311,6 +1312,7 @@ def test_create_sip_trunk(request_type, transport: str = "grpc"): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) response = client.create_sip_trunk(request) @@ -1325,6 +1327,10 @@ def test_create_sip_trunk(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) def test_create_sip_trunk_non_empty_request_with_auto_populated_field(): @@ -1461,6 +1467,7 @@ async def test_create_sip_trunk_async(request_type, transport: str = "grpc_async name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) ) response = await client.create_sip_trunk(request) @@ -1476,6 +1483,10 @@ async def test_create_sip_trunk_async(request_type, transport: str = "grpc_async assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) def test_create_sip_trunk_field_headers(): @@ -2490,6 +2501,7 @@ def test_get_sip_trunk(request_type, transport: str = "grpc"): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) response = client.get_sip_trunk(request) @@ -2504,6 +2516,10 @@ def test_get_sip_trunk(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) def test_get_sip_trunk_non_empty_request_with_auto_populated_field(): @@ -2638,6 +2654,7 @@ async def test_get_sip_trunk_async(request_type, transport: str = "grpc_asyncio" name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) ) response = await client.get_sip_trunk(request) @@ -2653,6 +2670,10 @@ async def test_get_sip_trunk_async(request_type, transport: str = "grpc_asyncio" assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) def test_get_sip_trunk_field_headers(): @@ -2818,6 +2839,7 @@ def test_update_sip_trunk(request_type, transport: str = "grpc"): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) response = client.update_sip_trunk(request) @@ -2832,6 +2854,10 @@ def test_update_sip_trunk(request_type, transport: str = "grpc"): assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) def test_update_sip_trunk_non_empty_request_with_auto_populated_field(): @@ -2964,6 +2990,7 @@ async def test_update_sip_trunk_async(request_type, transport: str = "grpc_async name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) ) response = await client.update_sip_trunk(request) @@ -2979,6 +3006,10 @@ async def test_update_sip_trunk_async(request_type, transport: str = "grpc_async assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) def test_update_sip_trunk_field_headers(): @@ -4358,6 +4389,7 @@ async def test_create_sip_trunk_empty_call_grpc_asyncio(): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) ) await client.create_sip_trunk(request=None) @@ -4434,6 +4466,7 @@ async def test_get_sip_trunk_empty_call_grpc_asyncio(): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) ) await client.get_sip_trunk(request=None) @@ -4462,6 +4495,7 @@ async def test_update_sip_trunk_empty_call_grpc_asyncio(): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) ) await client.update_sip_trunk(request=None) @@ -4535,6 +4569,25 @@ def test_create_sip_trunk_rest_call_success(request_type): } ], "display_name": "display_name_value", + "peer_hostnames": [ + { + "peer_hostname": "peer_hostname_value", + "enabled_sip_ping": True, + "ping_interval": {"seconds": 751, "nanos": 543}, + "peer_socket_address": "peer_socket_address_value", + "probe_details": { + "options_latency": {}, + "probe_status": 1, + "init_time": {}, + }, + "connection_state": 1, + "error_details": { + "certificate_state": 1, + "error_message": "error_message_value", + }, + } + ], + "google_root_cert_file": 5, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -4612,6 +4665,7 @@ def get_message_fields(field): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) # Wrap the value into a proper Response obj @@ -4631,6 +4685,10 @@ def get_message_fields(field): assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -4976,6 +5034,7 @@ def test_get_sip_trunk_rest_call_success(request_type): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) # Wrap the value into a proper Response obj @@ -4995,6 +5054,10 @@ def test_get_sip_trunk_rest_call_success(request_type): assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -5116,6 +5179,25 @@ def test_update_sip_trunk_rest_call_success(request_type): } ], "display_name": "display_name_value", + "peer_hostnames": [ + { + "peer_hostname": "peer_hostname_value", + "enabled_sip_ping": True, + "ping_interval": {"seconds": 751, "nanos": 543}, + "peer_socket_address": "peer_socket_address_value", + "probe_details": { + "options_latency": {}, + "probe_status": 1, + "init_time": {}, + }, + "connection_state": 1, + "error_details": { + "certificate_state": 1, + "error_message": "error_message_value", + }, + } + ], + "google_root_cert_file": 5, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -5193,6 +5275,7 @@ def get_message_fields(field): name="name_value", expected_hostname=["expected_hostname_value"], display_name="display_name_value", + google_root_cert_file=gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA, ) # Wrap the value into a proper Response obj @@ -5212,6 +5295,10 @@ def get_message_fields(field): assert response.name == "name_value" assert response.expected_hostname == ["expected_hostname_value"] assert response.display_name == "display_name_value" + assert ( + response.google_root_cert_file + == gcd_sip_trunk.SipTrunk.GoogleRootCertFile.EXTERNAL_PRIVATE_CA + ) @pytest.mark.parametrize("null_interceptor", [True, False]) diff --git a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py index a3d462ad5dbe..2c7c5187db75 100644 --- a/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py +++ b/packages/google-cloud-discoveryengine/google/cloud/discoveryengine_v1/types/search_service.py @@ -448,6 +448,16 @@ class SearchRequest(proto.Message): ``relevance_filter_spec`` instead. This feature is not supported for healthcare search. + relevance_filter_spec (google.cloud.discoveryengine_v1.types.SearchRequest.RelevanceFilterSpec): + Optional. The granular relevance filtering specification. + + If not specified, the global ``relevance_threshold`` will be + used for all sub-searches. If specified, this overrides the + global ``relevance_threshold`` to use thresholds on a per + sub-search basis. + + This feature is currently supported only for custom and site + search. relevance_score_spec (google.cloud.discoveryengine_v1.types.SearchRequest.RelevanceScoreSpec): Optional. The specification for returning the relevance score. @@ -1759,6 +1769,65 @@ class RelevanceScoreSpec(proto.Message): number=1, ) + class RelevanceFilterSpec(proto.Message): + r"""Relevance filtering specification. + + Attributes: + keyword_search_threshold (google.cloud.discoveryengine_v1.types.SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec): + Optional. Relevance filtering threshold + specification for keyword search. + semantic_search_threshold (google.cloud.discoveryengine_v1.types.SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec): + Optional. Relevance filtering threshold + specification for semantic search. + """ + + class RelevanceThresholdSpec(proto.Message): + r"""Specification for relevance filtering on a specific + sub-search. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + relevance_threshold (google.cloud.discoveryengine_v1.types.SearchRequest.RelevanceThreshold): + Pre-defined relevance threshold for the + sub-search. + + This field is a member of `oneof`_ ``relevance_threshold_spec``. + semantic_relevance_threshold (float): + Custom relevance threshold for the sub-search. The value + must be in [0.0, 1.0]. + + This field is a member of `oneof`_ ``relevance_threshold_spec``. + """ + + relevance_threshold: "SearchRequest.RelevanceThreshold" = proto.Field( + proto.ENUM, + number=1, + oneof="relevance_threshold_spec", + enum="SearchRequest.RelevanceThreshold", + ) + semantic_relevance_threshold: float = proto.Field( + proto.FLOAT, + number=2, + oneof="relevance_threshold_spec", + ) + + keyword_search_threshold: "SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec" = proto.Field( + proto.MESSAGE, + number=1, + message="SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec", + ) + semantic_search_threshold: "SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec" = proto.Field( + proto.MESSAGE, + number=2, + message="SearchRequest.RelevanceFilterSpec.RelevanceThresholdSpec", + ) + serving_config: str = proto.Field( proto.STRING, number=1, @@ -1911,6 +1980,11 @@ class RelevanceScoreSpec(proto.Message): number=44, enum=RelevanceThreshold, ) + relevance_filter_spec: RelevanceFilterSpec = proto.Field( + proto.MESSAGE, + number=86, + message=RelevanceFilterSpec, + ) relevance_score_spec: RelevanceScoreSpec = proto.Field( proto.MESSAGE, number=52, diff --git a/packages/google-cloud-kms/google/cloud/kms/__init__.py b/packages/google-cloud-kms/google/cloud/kms/__init__.py index 2748e366cabc..a09ae2ab9e3b 100644 --- a/packages/google-cloud-kms/google/cloud/kms/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms/__init__.py @@ -123,6 +123,8 @@ Digest, EncryptRequest, EncryptResponse, + ExportTrustedKeyWrappedCryptoKeyVersionRequest, + ExportTrustedKeyWrappedCryptoKeyVersionResponse, GenerateRandomBytesRequest, GenerateRandomBytesResponse, GetCryptoKeyRequest, @@ -132,6 +134,7 @@ GetPublicKeyRequest, GetRetiredResourceRequest, ImportCryptoKeyVersionRequest, + ImportTrustedKeyWrappedCryptoKeyVersionRequest, ListCryptoKeysRequest, ListCryptoKeysResponse, ListCryptoKeyVersionsRequest, @@ -244,6 +247,8 @@ "Digest", "EncryptRequest", "EncryptResponse", + "ExportTrustedKeyWrappedCryptoKeyVersionRequest", + "ExportTrustedKeyWrappedCryptoKeyVersionResponse", "GenerateRandomBytesRequest", "GenerateRandomBytesResponse", "GetCryptoKeyRequest", @@ -253,6 +258,7 @@ "GetPublicKeyRequest", "GetRetiredResourceRequest", "ImportCryptoKeyVersionRequest", + "ImportTrustedKeyWrappedCryptoKeyVersionRequest", "ListCryptoKeysRequest", "ListCryptoKeysResponse", "ListCryptoKeyVersionsRequest", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py index 0ba3f15c2366..4b811b37101d 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/__init__.py @@ -118,6 +118,8 @@ Digest, EncryptRequest, EncryptResponse, + ExportTrustedKeyWrappedCryptoKeyVersionRequest, + ExportTrustedKeyWrappedCryptoKeyVersionResponse, GenerateRandomBytesRequest, GenerateRandomBytesResponse, GetCryptoKeyRequest, @@ -127,6 +129,7 @@ GetPublicKeyRequest, GetRetiredResourceRequest, ImportCryptoKeyVersionRequest, + ImportTrustedKeyWrappedCryptoKeyVersionRequest, ListCryptoKeysRequest, ListCryptoKeysResponse, ListCryptoKeyVersionsRequest, @@ -288,6 +291,8 @@ def _get_version(dependency_name): "ExecuteSingleTenantHsmInstanceProposalMetadata", "ExecuteSingleTenantHsmInstanceProposalRequest", "ExecuteSingleTenantHsmInstanceProposalResponse", + "ExportTrustedKeyWrappedCryptoKeyVersionRequest", + "ExportTrustedKeyWrappedCryptoKeyVersionResponse", "ExternalProtectionLevelOptions", "GenerateRandomBytesRequest", "GenerateRandomBytesResponse", @@ -306,6 +311,7 @@ def _get_version(dependency_name): "HsmManagementClient", "ImportCryptoKeyVersionRequest", "ImportJob", + "ImportTrustedKeyWrappedCryptoKeyVersionRequest", "KeyAccessJustificationsPolicy", "KeyHandle", "KeyManagementServiceClient", @@ -355,4 +361,3 @@ def _get_version(dependency_name): "VerifyConnectivityRequest", "VerifyConnectivityResponse", ) -# Trigger CI check diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json index df16c1e4c878..a22209cefb9f 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json +++ b/packages/google-cloud-kms/google/cloud/kms_v1/gapic_metadata.json @@ -476,6 +476,11 @@ "encrypt" ] }, + "ExportTrustedKeyWrappedCryptoKeyVersion": { + "methods": [ + "export_trusted_key_wrapped_crypto_key_version" + ] + }, "GenerateRandomBytes": { "methods": [ "generate_random_bytes" @@ -516,6 +521,11 @@ "import_crypto_key_version" ] }, + "ImportTrustedKeyWrappedCryptoKeyVersion": { + "methods": [ + "import_trusted_key_wrapped_crypto_key_version" + ] + }, "ListCryptoKeyVersions": { "methods": [ "list_crypto_key_versions" @@ -646,6 +656,11 @@ "encrypt" ] }, + "ExportTrustedKeyWrappedCryptoKeyVersion": { + "methods": [ + "export_trusted_key_wrapped_crypto_key_version" + ] + }, "GenerateRandomBytes": { "methods": [ "generate_random_bytes" @@ -686,6 +701,11 @@ "import_crypto_key_version" ] }, + "ImportTrustedKeyWrappedCryptoKeyVersion": { + "methods": [ + "import_trusted_key_wrapped_crypto_key_version" + ] + }, "ListCryptoKeyVersions": { "methods": [ "list_crypto_key_versions" @@ -816,6 +836,11 @@ "encrypt" ] }, + "ExportTrustedKeyWrappedCryptoKeyVersion": { + "methods": [ + "export_trusted_key_wrapped_crypto_key_version" + ] + }, "GenerateRandomBytes": { "methods": [ "generate_random_bytes" @@ -856,6 +881,11 @@ "import_crypto_key_version" ] }, + "ImportTrustedKeyWrappedCryptoKeyVersion": { + "methods": [ + "import_trusted_key_wrapped_crypto_key_version" + ] + }, "ListCryptoKeyVersions": { "methods": [ "list_crypto_key_versions" diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py index 4812bbed46c5..bdc4a7f5cb11 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/async_client.py @@ -2490,7 +2490,7 @@ async def sample_import_crypto_key_version(): request = kms_v1.ImportCryptoKeyVersionRequest( rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', parent="parent_value", - algorithm="PQ_SIGN_ML_DSA_87_EXTERNAL_MU", + algorithm="AES_256_KWP", import_job="import_job_value", ) @@ -2562,6 +2562,226 @@ async def sample_import_crypto_key_version(): # Done; return the response. return response + async def import_trusted_key_wrapped_crypto_key_version( + self, + request: Optional[ + Union[service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.CryptoKeyVersion: + r"""Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + will have trusted_wrapping_enabled set to true. + + .. 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 kms_v1 + + async def sample_import_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ImportTrustedKeyWrappedCryptoKeyVersionRequest( + parent="parent_value", + importing_key="importing_key_value", + wrapped_key=b'wrapped_key_blob', + algorithm="AES_256_KWP", + ) + + # Make the request + response = await client.import_trusted_key_wrapped_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ImportTrustedKeyWrappedCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, service.ImportTrustedKeyWrappedCryptoKeyVersionRequest + ): + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.import_trusted_key_wrapped_crypto_key_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def export_trusted_key_wrapped_crypto_key_version( + self, + request: Optional[ + Union[service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + r"""Exports a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must have trusted_wrapping_enabled set to true. The + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] of the + [wrapping_key] must have the + [AES_WRAPPING][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.AES_WRAPPING] + purpose. The [wrapping_key] must have the + [AES_256_KWP][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.AES_256_KWP] + algorithm. + + .. 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 kms_v1 + + async def sample_export_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ExportTrustedKeyWrappedCryptoKeyVersionRequest( + name="name_value", + wrapping_key="wrapping_key_value", + ) + + # Make the request + response = await client.export_trusted_key_wrapped_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionRequest, dict]]): + The request object. Request message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + Response message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, service.ExportTrustedKeyWrappedCryptoKeyVersionRequest + ): + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.export_trusted_key_wrapped_crypto_key_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def create_import_job( self, request: Optional[Union[service.CreateImportJobRequest, dict]] = None, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py index aff969e7a712..2f87e34ca423 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/client.py @@ -2977,7 +2977,7 @@ def sample_import_crypto_key_version(): request = kms_v1.ImportCryptoKeyVersionRequest( rsa_aes_wrapped_key=b'rsa_aes_wrapped_key_blob', parent="parent_value", - algorithm="PQ_SIGN_ML_DSA_87_EXTERNAL_MU", + algorithm="AES_256_KWP", import_job="import_job_value", ) @@ -3049,6 +3049,226 @@ def sample_import_crypto_key_version(): # Done; return the response. return response + def import_trusted_key_wrapped_crypto_key_version( + self, + request: Optional[ + Union[service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.CryptoKeyVersion: + r"""Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + will have trusted_wrapping_enabled set to true. + + .. 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 kms_v1 + + def sample_import_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ImportTrustedKeyWrappedCryptoKeyVersionRequest( + parent="parent_value", + importing_key="importing_key_value", + wrapped_key=b'wrapped_key_blob', + algorithm="AES_256_KWP", + ) + + # Make the request + response = client.import_trusted_key_wrapped_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ImportTrustedKeyWrappedCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion]. + 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.kms_v1.types.CryptoKeyVersion: + A [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] represents an + individual cryptographic key, and the associated key + material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key + material represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used + to encrypt, decrypt, or sign data when an authorized + user or application invokes Cloud KMS. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, service.ImportTrustedKeyWrappedCryptoKeyVersionRequest + ): + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.import_trusted_key_wrapped_crypto_key_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def export_trusted_key_wrapped_crypto_key_version( + self, + request: Optional[ + Union[service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, dict] + ] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + r"""Exports a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must have trusted_wrapping_enabled set to true. The + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] of the + [wrapping_key] must have the + [AES_WRAPPING][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.AES_WRAPPING] + purpose. The [wrapping_key] must have the + [AES_256_KWP][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.AES_256_KWP] + algorithm. + + .. 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 kms_v1 + + def sample_export_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ExportTrustedKeyWrappedCryptoKeyVersionRequest( + name="name_value", + wrapping_key="wrapping_key_value", + ) + + # Make the request + response = client.export_trusted_key_wrapped_crypto_key_version(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionRequest, dict]): + The request object. Request message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + 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.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + Response message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance( + request, service.ExportTrustedKeyWrappedCryptoKeyVersionRequest + ): + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.export_trusted_key_wrapped_crypto_key_version + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def create_import_job( self, request: Optional[Union[service.CreateImportJobRequest, dict]] = None, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py index 9cc920eb8e96..33532892c458 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/base.py @@ -386,6 +386,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.import_trusted_key_wrapped_crypto_key_version: gapic_v1.method.wrap_method( + self.import_trusted_key_wrapped_crypto_key_version, + default_timeout=None, + client_info=client_info, + ), + self.export_trusted_key_wrapped_crypto_key_version: gapic_v1.method.wrap_method( + self.export_trusted_key_wrapped_crypto_key_version, + default_timeout=None, + client_info=client_info, + ), self.create_import_job: gapic_v1.method.wrap_method( self.create_import_job, default_retry=retries.Retry( @@ -805,6 +815,27 @@ def import_crypto_key_version( ]: raise NotImplementedError() + @property + def import_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ImportTrustedKeyWrappedCryptoKeyVersionRequest], + Union[resources.CryptoKeyVersion, Awaitable[resources.CryptoKeyVersion]], + ]: + raise NotImplementedError() + + @property + def export_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ExportTrustedKeyWrappedCryptoKeyVersionRequest], + Union[ + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse, + Awaitable[service.ExportTrustedKeyWrappedCryptoKeyVersionResponse], + ], + ]: + raise NotImplementedError() + @property def create_import_job( self, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py index d5139a3be9a7..c07000ae4742 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc.py @@ -861,6 +861,94 @@ def import_crypto_key_version( ) return self._stubs["import_crypto_key_version"] + @property + def import_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ImportTrustedKeyWrappedCryptoKeyVersionRequest], + resources.CryptoKeyVersion, + ]: + r"""Return a callable for the import trusted key wrapped + crypto key version method over gRPC. + + Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + will have trusted_wrapping_enabled set to true. + + Returns: + Callable[[~.ImportTrustedKeyWrappedCryptoKeyVersionRequest], + ~.CryptoKeyVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_trusted_key_wrapped_crypto_key_version" not in self._stubs: + self._stubs["import_trusted_key_wrapped_crypto_key_version"] = ( + self._logged_channel.unary_unary( + "/google.cloud.kms.v1.KeyManagementService/ImportTrustedKeyWrappedCryptoKeyVersion", + request_serializer=service.ImportTrustedKeyWrappedCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + ) + return self._stubs["import_trusted_key_wrapped_crypto_key_version"] + + @property + def export_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ExportTrustedKeyWrappedCryptoKeyVersionRequest], + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse, + ]: + r"""Return a callable for the export trusted key wrapped + crypto key version method over gRPC. + + Exports a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must have trusted_wrapping_enabled set to true. The + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] of the + [wrapping_key] must have the + [AES_WRAPPING][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.AES_WRAPPING] + purpose. The [wrapping_key] must have the + [AES_256_KWP][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.AES_256_KWP] + algorithm. + + Returns: + Callable[[~.ExportTrustedKeyWrappedCryptoKeyVersionRequest], + ~.ExportTrustedKeyWrappedCryptoKeyVersionResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_trusted_key_wrapped_crypto_key_version" not in self._stubs: + self._stubs["export_trusted_key_wrapped_crypto_key_version"] = ( + self._logged_channel.unary_unary( + "/google.cloud.kms.v1.KeyManagementService/ExportTrustedKeyWrappedCryptoKeyVersion", + request_serializer=service.ExportTrustedKeyWrappedCryptoKeyVersionRequest.serialize, + response_deserializer=service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.deserialize, + ) + ) + return self._stubs["export_trusted_key_wrapped_crypto_key_version"] + @property def create_import_job( self, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py index 98fc2864f25e..ce8e83c2b40d 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/grpc_asyncio.py @@ -891,6 +891,94 @@ def import_crypto_key_version( ) return self._stubs["import_crypto_key_version"] + @property + def import_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ImportTrustedKeyWrappedCryptoKeyVersionRequest], + Awaitable[resources.CryptoKeyVersion], + ]: + r"""Return a callable for the import trusted key wrapped + crypto key version method over gRPC. + + Import wrapped key material into a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + All requests must specify a + [CryptoKey][google.cloud.kms.v1.CryptoKey]. If a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] is + additionally specified in the request, key material will be + reimported into that version. Otherwise, a new version will be + created, and will be assigned the next sequential id within the + [CryptoKey][google.cloud.kms.v1.CryptoKey]. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + will have trusted_wrapping_enabled set to true. + + Returns: + Callable[[~.ImportTrustedKeyWrappedCryptoKeyVersionRequest], + Awaitable[~.CryptoKeyVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "import_trusted_key_wrapped_crypto_key_version" not in self._stubs: + self._stubs["import_trusted_key_wrapped_crypto_key_version"] = ( + self._logged_channel.unary_unary( + "/google.cloud.kms.v1.KeyManagementService/ImportTrustedKeyWrappedCryptoKeyVersion", + request_serializer=service.ImportTrustedKeyWrappedCryptoKeyVersionRequest.serialize, + response_deserializer=resources.CryptoKeyVersion.deserialize, + ) + ) + return self._stubs["import_trusted_key_wrapped_crypto_key_version"] + + @property + def export_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ExportTrustedKeyWrappedCryptoKeyVersionRequest], + Awaitable[service.ExportTrustedKeyWrappedCryptoKeyVersionResponse], + ]: + r"""Return a callable for the export trusted key wrapped + crypto key version method over gRPC. + + Exports a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] with a + trusted key. + + The [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must have trusted_wrapping_enabled set to true. The + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] of the + [wrapping_key] must have the + [AES_WRAPPING][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.AES_WRAPPING] + purpose. The [wrapping_key] must have the + [AES_256_KWP][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm.AES_256_KWP] + algorithm. + + Returns: + Callable[[~.ExportTrustedKeyWrappedCryptoKeyVersionRequest], + Awaitable[~.ExportTrustedKeyWrappedCryptoKeyVersionResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_trusted_key_wrapped_crypto_key_version" not in self._stubs: + self._stubs["export_trusted_key_wrapped_crypto_key_version"] = ( + self._logged_channel.unary_unary( + "/google.cloud.kms.v1.KeyManagementService/ExportTrustedKeyWrappedCryptoKeyVersion", + request_serializer=service.ExportTrustedKeyWrappedCryptoKeyVersionRequest.serialize, + response_deserializer=service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.deserialize, + ) + ) + return self._stubs["export_trusted_key_wrapped_crypto_key_version"] + @property def create_import_job( self, @@ -1667,6 +1755,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.import_trusted_key_wrapped_crypto_key_version: self._wrap_method( + self.import_trusted_key_wrapped_crypto_key_version, + default_timeout=None, + client_info=client_info, + ), + self.export_trusted_key_wrapped_crypto_key_version: self._wrap_method( + self.export_trusted_key_wrapped_crypto_key_version, + default_timeout=None, + client_info=client_info, + ), self.create_import_job: self._wrap_method( self.create_import_job, default_retry=retries.AsyncRetry( diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py index 4249d25d6eb9..0082b362ecba 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest.py @@ -174,6 +174,14 @@ def post_encrypt(self, response): logging.log(f"Received response: {response}") return response + def pre_export_trusted_key_wrapped_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_trusted_key_wrapped_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + def pre_generate_random_bytes(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -238,6 +246,14 @@ def post_import_crypto_key_version(self, response): logging.log(f"Received response: {response}") return response + def pre_import_trusted_key_wrapped_crypto_key_version(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_import_trusted_key_wrapped_crypto_key_version(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_crypto_keys(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -908,6 +924,58 @@ def post_encrypt_with_metadata( """ return response, metadata + def pre_export_trusted_key_wrapped_crypto_key_version( + self, + request: service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for export_trusted_key_wrapped_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_export_trusted_key_wrapped_crypto_key_version( + self, response: service.ExportTrustedKeyWrappedCryptoKeyVersionResponse + ) -> service.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + """Post-rpc interceptor for export_trusted_key_wrapped_crypto_key_version + + DEPRECATED. Please use the `post_export_trusted_key_wrapped_crypto_key_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. This `post_export_trusted_key_wrapped_crypto_key_version` interceptor runs + before the `post_export_trusted_key_wrapped_crypto_key_version_with_metadata` interceptor. + """ + return response + + def post_export_trusted_key_wrapped_crypto_key_version_with_metadata( + self, + response: service.ExportTrustedKeyWrappedCryptoKeyVersionResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for export_trusted_key_wrapped_crypto_key_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the KeyManagementService server but before it is returned to user code. + + We recommend only using this `post_export_trusted_key_wrapped_crypto_key_version_with_metadata` + interceptor in new development instead of the `post_export_trusted_key_wrapped_crypto_key_version` interceptor. + When both interceptors are used, this `post_export_trusted_key_wrapped_crypto_key_version_with_metadata` interceptor runs after the + `post_export_trusted_key_wrapped_crypto_key_version` interceptor. The (possibly modified) response returned by + `post_export_trusted_key_wrapped_crypto_key_version` will be passed to + `post_export_trusted_key_wrapped_crypto_key_version_with_metadata`. + """ + return response, metadata + def pre_generate_random_bytes( self, request: service.GenerateRandomBytesRequest, @@ -1278,6 +1346,55 @@ def post_import_crypto_key_version_with_metadata( """ return response, metadata + def pre_import_trusted_key_wrapped_crypto_key_version( + self, + request: service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for import_trusted_key_wrapped_crypto_key_version + + Override in a subclass to manipulate the request or metadata + before they are sent to the KeyManagementService server. + """ + return request, metadata + + def post_import_trusted_key_wrapped_crypto_key_version( + self, response: resources.CryptoKeyVersion + ) -> resources.CryptoKeyVersion: + """Post-rpc interceptor for import_trusted_key_wrapped_crypto_key_version + + DEPRECATED. Please use the `post_import_trusted_key_wrapped_crypto_key_version_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the KeyManagementService server but before + it is returned to user code. This `post_import_trusted_key_wrapped_crypto_key_version` interceptor runs + before the `post_import_trusted_key_wrapped_crypto_key_version_with_metadata` interceptor. + """ + return response + + def post_import_trusted_key_wrapped_crypto_key_version_with_metadata( + self, + response: resources.CryptoKeyVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.CryptoKeyVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for import_trusted_key_wrapped_crypto_key_version + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the KeyManagementService server but before it is returned to user code. + + We recommend only using this `post_import_trusted_key_wrapped_crypto_key_version_with_metadata` + interceptor in new development instead of the `post_import_trusted_key_wrapped_crypto_key_version` interceptor. + When both interceptors are used, this `post_import_trusted_key_wrapped_crypto_key_version_with_metadata` interceptor runs after the + `post_import_trusted_key_wrapped_crypto_key_version` interceptor. The (possibly modified) response returned by + `post_import_trusted_key_wrapped_crypto_key_version` will be passed to + `post_import_trusted_key_wrapped_crypto_key_version_with_metadata`. + """ + return response, metadata + def pre_list_crypto_keys( self, request: service.ListCryptoKeysRequest, @@ -4092,6 +4209,167 @@ def __call__( ) return resp + class _ExportTrustedKeyWrappedCryptoKeyVersion( + _BaseKeyManagementServiceRestTransport._BaseExportTrustedKeyWrappedCryptoKeyVersion, + KeyManagementServiceRestStub, + ): + def __hash__(self): + return hash( + "KeyManagementServiceRestTransport.ExportTrustedKeyWrappedCryptoKeyVersion" + ) + + @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: service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> service.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + r"""Call the export trusted key + wrapped crypto key version method over HTTP. + + Args: + request (~.service.ExportTrustedKeyWrappedCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + 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: + ~.service.ExportTrustedKeyWrappedCryptoKeyVersionResponse: + Response message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseExportTrustedKeyWrappedCryptoKeyVersion._get_http_options() + + request, metadata = ( + self._interceptor.pre_export_trusted_key_wrapped_crypto_key_version( + request, metadata + ) + ) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseExportTrustedKeyWrappedCryptoKeyVersion._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseExportTrustedKeyWrappedCryptoKeyVersion._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.kms_v1.KeyManagementServiceClient.ExportTrustedKeyWrappedCryptoKeyVersion", + extra={ + "serviceName": "google.cloud.kms.v1.KeyManagementService", + "rpcName": "ExportTrustedKeyWrappedCryptoKeyVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = KeyManagementServiceRestTransport._ExportTrustedKeyWrappedCryptoKeyVersion._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 = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() + pb_resp = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_trusted_key_wrapped_crypto_key_version( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_export_trusted_key_wrapped_crypto_key_version_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.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.kms_v1.KeyManagementServiceClient.export_trusted_key_wrapped_crypto_key_version", + extra={ + "serviceName": "google.cloud.kms.v1.KeyManagementService", + "rpcName": "ExportTrustedKeyWrappedCryptoKeyVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _GenerateRandomBytes( _BaseKeyManagementServiceRestTransport._BaseGenerateRandomBytes, KeyManagementServiceRestStub, @@ -5372,6 +5650,182 @@ def __call__( ) return resp + class _ImportTrustedKeyWrappedCryptoKeyVersion( + _BaseKeyManagementServiceRestTransport._BaseImportTrustedKeyWrappedCryptoKeyVersion, + KeyManagementServiceRestStub, + ): + def __hash__(self): + return hash( + "KeyManagementServiceRestTransport.ImportTrustedKeyWrappedCryptoKeyVersion" + ) + + @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), + data=body, + ) + return response + + def __call__( + self, + request: service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.CryptoKeyVersion: + r"""Call the import trusted key + wrapped crypto key version method over HTTP. + + Args: + request (~.service.ImportTrustedKeyWrappedCryptoKeyVersionRequest): + The request object. Request message for + [KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion]. + 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: + ~.resources.CryptoKeyVersion: + A + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + represents an individual cryptographic key, and the + associated key material. + + An + [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] + version can be used for cryptographic operations. + + For security reasons, the raw cryptographic key material + represented by a + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + can never be viewed or exported. It can only be used to + encrypt, decrypt, or sign data when an authorized user + or application invokes Cloud KMS. + + """ + + http_options = _BaseKeyManagementServiceRestTransport._BaseImportTrustedKeyWrappedCryptoKeyVersion._get_http_options() + + request, metadata = ( + self._interceptor.pre_import_trusted_key_wrapped_crypto_key_version( + request, metadata + ) + ) + transcoded_request = _BaseKeyManagementServiceRestTransport._BaseImportTrustedKeyWrappedCryptoKeyVersion._get_transcoded_request( + http_options, request + ) + + body = _BaseKeyManagementServiceRestTransport._BaseImportTrustedKeyWrappedCryptoKeyVersion._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseKeyManagementServiceRestTransport._BaseImportTrustedKeyWrappedCryptoKeyVersion._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.kms_v1.KeyManagementServiceClient.ImportTrustedKeyWrappedCryptoKeyVersion", + extra={ + "serviceName": "google.cloud.kms.v1.KeyManagementService", + "rpcName": "ImportTrustedKeyWrappedCryptoKeyVersion", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = KeyManagementServiceRestTransport._ImportTrustedKeyWrappedCryptoKeyVersion._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.CryptoKeyVersion() + pb_resp = resources.CryptoKeyVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_import_trusted_key_wrapped_crypto_key_version( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_import_trusted_key_wrapped_crypto_key_version_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.CryptoKeyVersion.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.kms_v1.KeyManagementServiceClient.import_trusted_key_wrapped_crypto_key_version", + extra={ + "serviceName": "google.cloud.kms.v1.KeyManagementService", + "rpcName": "ImportTrustedKeyWrappedCryptoKeyVersion", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _ListCryptoKeys( _BaseKeyManagementServiceRestTransport._BaseListCryptoKeys, KeyManagementServiceRestStub, @@ -7492,6 +7946,19 @@ def encrypt(self) -> Callable[[service.EncryptRequest], service.EncryptResponse] # In C++ this would require a dynamic_cast return self._Encrypt(self._session, self._host, self._interceptor) # type: ignore + @property + def export_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ExportTrustedKeyWrappedCryptoKeyVersionRequest], + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse, + ]: + # 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._ExportTrustedKeyWrappedCryptoKeyVersion( + self._session, self._host, self._interceptor + ) # type: ignore + @property def generate_random_bytes( self, @@ -7558,6 +8025,19 @@ def import_crypto_key_version( self._session, self._host, self._interceptor ) # type: ignore + @property + def import_trusted_key_wrapped_crypto_key_version( + self, + ) -> Callable[ + [service.ImportTrustedKeyWrappedCryptoKeyVersionRequest], + resources.CryptoKeyVersion, + ]: + # 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._ImportTrustedKeyWrappedCryptoKeyVersion( + self._session, self._host, self._interceptor + ) # type: ignore + @property def list_crypto_keys( self, diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py index c0062c431267..e38c1aa4dce4 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/services/key_management_service/transports/rest_base.py @@ -763,6 +763,57 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseExportTrustedKeyWrappedCryptoKeyVersion: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = { + "wrappingKey": "", + } + + @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": "/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}:exportTrustedKeyWrappedCryptoKeyVersion", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest.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=True, + ) + ) + query_params.update( + _BaseKeyManagementServiceRestTransport._BaseExportTrustedKeyWrappedCryptoKeyVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseGenerateRandomBytes: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1144,6 +1195,65 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseImportTrustedKeyWrappedCryptoKeyVersion: + 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": "post", + "uri": "/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions:importTrustedKeyWrappedCryptoKeyVersion", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest.pb( + request + ) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseKeyManagementServiceRestTransport._BaseImportTrustedKeyWrappedCryptoKeyVersion._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListCryptoKeys: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py index bdb971e19116..79649cf0fb11 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/__init__.py @@ -100,6 +100,8 @@ Digest, EncryptRequest, EncryptResponse, + ExportTrustedKeyWrappedCryptoKeyVersionRequest, + ExportTrustedKeyWrappedCryptoKeyVersionResponse, GenerateRandomBytesRequest, GenerateRandomBytesResponse, GetCryptoKeyRequest, @@ -109,6 +111,7 @@ GetPublicKeyRequest, GetRetiredResourceRequest, ImportCryptoKeyVersionRequest, + ImportTrustedKeyWrappedCryptoKeyVersionRequest, ListCryptoKeysRequest, ListCryptoKeysResponse, ListCryptoKeyVersionsRequest, @@ -211,6 +214,8 @@ "Digest", "EncryptRequest", "EncryptResponse", + "ExportTrustedKeyWrappedCryptoKeyVersionRequest", + "ExportTrustedKeyWrappedCryptoKeyVersionResponse", "GenerateRandomBytesRequest", "GenerateRandomBytesResponse", "GetCryptoKeyRequest", @@ -220,6 +225,7 @@ "GetPublicKeyRequest", "GetRetiredResourceRequest", "ImportCryptoKeyVersionRequest", + "ImportTrustedKeyWrappedCryptoKeyVersionRequest", "ListCryptoKeysRequest", "ListCryptoKeysResponse", "ListCryptoKeyVersionsRequest", diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py index e498bc8dca02..d922014832a4 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/hsm_management.py @@ -99,8 +99,7 @@ class SingleTenantHsmInstance(proto.Message): enabled for the [SingleTenantHsmInstance][google.cloud.kms.v1.SingleTenantHsmInstance]. This can only be set at creation time. Key portability - features are disabled by default and not yet available in - GA. + features are disabled by default. """ class State(proto.Enum): @@ -391,6 +390,13 @@ class SingleTenantHsmInstanceProposal(proto.Message): [ACTIVE][google.cloud.kms.v1.SingleTenantHsmInstance.State.ACTIVE] state to perform this operation. + This field is a member of `oneof`_ ``operation``. + upgrade_key_trust (google.cloud.kms_v1.types.SingleTenantHsmInstanceProposal.UpgradeKeyTrust): + Promotes a key with the AES_WRAPPING purpose to a trusted + wrapping key. The key must be in the + [ACTIVE][CryptoKeyVersion.CryptoKeyVersionState.ACTIVE] + state to perform this operation. + This field is a member of `oneof`_ ``operation``. """ @@ -657,6 +663,33 @@ class RefreshSingleTenantHsmInstance(proto.Message): """ + class UpgradeKeyTrust(proto.Message): + r"""Promotes a key with the AES_WRAPPING purpose to a trusted wrapping + key. The key must be in the + [ACTIVE][CryptoKeyVersion.CryptoKeyVersionState.ACTIVE] state to + perform this operation. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + promote. + two_factor_public_key_pem (str): + Required. The public key associated with the + 2FA key that will sign the login nonce for this + operation. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + two_factor_public_key_pem: str = proto.Field( + proto.STRING, + number=2, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -751,6 +784,12 @@ class RefreshSingleTenantHsmInstance(proto.Message): oneof="operation", message=RefreshSingleTenantHsmInstance, ) + upgrade_key_trust: UpgradeKeyTrust = proto.Field( + proto.MESSAGE, + number=18, + oneof="operation", + message=UpgradeKeyTrust, + ) class Challenge(proto.Message): diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py index 66a514691b0b..baeb205f6d98 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/resources.py @@ -382,6 +382,9 @@ class CryptoKeyPurpose(proto.Enum): [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey] and [Decapsulate][google.cloud.kms.v1.KeyManagementService.Decapsulate]. + AES_WRAPPING (11): + [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this + purpose may be used for AES key """ CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0 @@ -391,6 +394,7 @@ class CryptoKeyPurpose(proto.Enum): RAW_ENCRYPT_DECRYPT = 7 MAC = 9 KEY_ENCAPSULATION = 10 + AES_WRAPPING = 11 name: str = proto.Field( proto.STRING, @@ -679,6 +683,23 @@ class CryptoKeyVersion(proto.Message): Output only. Whether or not this key version is eligible for reimport, by being specified as a target in [ImportCryptoKeyVersionRequest.crypto_key_version][google.cloud.kms.v1.ImportCryptoKeyVersionRequest.crypto_key_version]. + trusted_wrapping_enabled (bool): + Immutable. Field indicating that the key may be wrapped by a + trusted key. This field can be set for all key purposes + except + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT], + and is only valid for keys with protection level + [HSM_SINGLE_TENANT][google.cloud.kms.v1.ProtectionLevel.HSM_SINGLE_TENANT]. + This field can only be set at creation or import time via + [CreateCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.CreateCryptoKeyVersion], + or + [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion]. + hsm_trusted (bool): + Output only. Field indicating that the key wrapping key is + trusted. This field is only valid for key purpose + [AES_256_WRAPPING][CryptoKey.CryptoKeyPurpose.AES_256_WRAPPING], + and protection level + [HSM_SINGLE_TENANT][google.cloud.kms.v1.ProtectionLevel.HSM_SINGLE_TENANT]. """ class CryptoKeyVersionAlgorithm(proto.Enum): @@ -865,6 +886,9 @@ class CryptoKeyVersionAlgorithm(proto.Enum): Signature Algorithm, at security level 5. Randomized version supporting externally-computed message representatives. + AES_256_KWP (73): + AES key wrap with zero padding algorithm (RFC 5649). Can + only be used by keys with purpose AES_WRAPPING. """ CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0 @@ -914,6 +938,7 @@ class CryptoKeyVersionAlgorithm(proto.Enum): PQ_SIGN_ML_DSA_44_EXTERNAL_MU = 70 PQ_SIGN_ML_DSA_65_EXTERNAL_MU = 67 PQ_SIGN_ML_DSA_87_EXTERNAL_MU = 71 + AES_256_KWP = 73 class CryptoKeyVersionState(proto.Enum): r"""The state of a @@ -1094,6 +1119,14 @@ class CryptoKeyVersionView(proto.Enum): proto.BOOL, number=18, ) + trusted_wrapping_enabled: bool = proto.Field( + proto.BOOL, + number=21, + ) + hsm_trusted: bool = proto.Field( + proto.BOOL, + number=23, + ) class ChecksummedData(proto.Message): diff --git a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py index 3c513b8ca9c9..80d6cc8fad49 100644 --- a/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py +++ b/packages/google-cloud-kms/google/cloud/kms_v1/types/service.py @@ -48,6 +48,9 @@ "DeleteCryptoKeyRequest", "DeleteCryptoKeyVersionRequest", "ImportCryptoKeyVersionRequest", + "ImportTrustedKeyWrappedCryptoKeyVersionRequest", + "ExportTrustedKeyWrappedCryptoKeyVersionRequest", + "ExportTrustedKeyWrappedCryptoKeyVersionResponse", "CreateImportJobRequest", "UpdateCryptoKeyRequest", "UpdateCryptoKeyVersionRequest", @@ -744,6 +747,18 @@ class CreateCryptoKeyRequest(proto.Message): [ImportCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportCryptoKeyVersion] before you can use this [CryptoKey][google.cloud.kms.v1.CryptoKey]. + trusted_wrapping_enabled (bool): + Optional. Whether trusted wrapping will be enabled on the + first + [CryptoKeyVersions][google.cloud.kms.v1.CryptoKeyVersion] + created for this [CryptoKey][google.cloud.kms.v1.CryptoKey]. + This field is only supported for keys with + [CryptoKeyVersionTemplate.protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [HSM_SINGLE_TENANT][google.cloud.kms.v1.ProtectionLevel.HSM_SINGLE_TENANT]. + This field is supported for all + [CryptoKeyPurposes][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose] + except + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. """ parent: str = proto.Field( @@ -763,6 +778,10 @@ class CreateCryptoKeyRequest(proto.Message): proto.BOOL, number=5, ) + trusted_wrapping_enabled: bool = proto.Field( + proto.BOOL, + number=6, + ) class CreateCryptoKeyVersionRequest(proto.Message): @@ -936,6 +955,16 @@ class ImportCryptoKeyVersionRequest(proto.Message): this field (but not both) must be specified. This field is a member of `oneof`_ ``wrapped_key_material``. + trusted_wrapping_enabled (bool): + Optional. Whether trusted wrapping will be enabled on the + imported [CryptoKeyVersion]. This field is only supported + for keys with + [CryptoKeyVersionTemplate.protection_level][google.cloud.kms.v1.CryptoKeyVersionTemplate.protection_level] + [HSM_SINGLE_TENANT][google.cloud.kms.v1.ProtectionLevel.HSM_SINGLE_TENANT]. + This field is supported for all + [CryptoKeyPurposes][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose] + besides + [ENCRYPT_DECRYPT][google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT]. """ parent: str = proto.Field( @@ -964,6 +993,160 @@ class ImportCryptoKeyVersionRequest(proto.Message): number=5, oneof="wrapped_key_material", ) + trusted_wrapping_enabled: bool = proto.Field( + proto.BOOL, + number=9, + ) + + +class ImportTrustedKeyWrappedCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion]. + + Attributes: + parent (str): + Required. The [name][google.cloud.kms.v1.CryptoKey.name] of + the [CryptoKey][google.cloud.kms.v1.CryptoKey] to be + imported into. + importing_key (str): + Required. Required - the CKV of the trusted + key used to import. This can be the name of a + CryptoKeyVersion or a CryptoKey. + crypto_key_version (str): + Optional. The optional + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of an + existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + target for an import operation. If this field is not + present, a new + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + containing the supplied key material is created. + + If this field is present, the supplied key material is + imported into the existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. To + import into an existing + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], + the [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must be a child of + [ImportTrustedKeyWrappedCryptoKeyVersionRequest.parent][google.cloud.kms.v1.ImportTrustedKeyWrappedCryptoKeyVersionRequest.parent], + have been previously created via + [ImportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion], + and be in + [DESTROYED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DESTROYED] + or + [IMPORT_FAILED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.IMPORT_FAILED] + state. The key material and algorithm must match the + previous + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + exactly if the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] has + ever contained key material + wrapped_key (bytes): + Required. The target key pre-wrapped on + premises. + algorithm (google.cloud.kms_v1.types.CryptoKeyVersion.CryptoKeyVersionAlgorithm): + Required. Required - The + [algorithm][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm] + of the key being imported. This does not need to match the + [version_template][google.cloud.kms.v1.CryptoKey.version_template] + of the [CryptoKey][google.cloud.kms.v1.CryptoKey] this + version imports into. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + importing_key: str = proto.Field( + proto.STRING, + number=2, + ) + crypto_key_version: str = proto.Field( + proto.STRING, + number=3, + ) + wrapped_key: bytes = proto.Field( + proto.BYTES, + number=4, + ) + algorithm: resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm = proto.Field( + proto.ENUM, + number=5, + enum=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm, + ) + + +class ExportTrustedKeyWrappedCryptoKeyVersionRequest(proto.Message): + r"""Request message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + + Attributes: + name (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + export. The + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must have + [trusted_wrapping_enabled][google.cloud.kms.v1.CryptoKeyVersion.trusted_wrapping_enabled] + set to true. + wrapping_key (str): + Required. The + [name][google.cloud.kms.v1.CryptoKeyVersion.name] of the + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] to + use as a wrapping key. The + [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion] + must have + [hsm_trusted][google.cloud.kms.v1.CryptoKeyVersion.hsm_trusted] + set to true. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + wrapping_key: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportTrustedKeyWrappedCryptoKeyVersionResponse(proto.Message): + r"""Response message for + [KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion]. + + Attributes: + wrapped_key (bytes): + The wrapped key material. + wrapped_key_crc32c (google.protobuf.wrappers_pb2.Int64Value): + Integrity verification field. A CRC32C checksum of the + returned + [ExportTrustedKeyWrappedCryptoKeyVersionResponse.wrapped_key][google.cloud.kms.v1.ExportTrustedKeyWrappedCryptoKeyVersionResponse.wrapped_key]. + An integrity check of + [ExportTrustedKeyWrappedCryptoKeyVersionResponse.wrapped_key][google.cloud.kms.v1.ExportTrustedKeyWrappedCryptoKeyVersionResponse.wrapped_key] + can be performed by computing the CRC32C checksum of + [ExportTrustedKeyWrappedCryptoKeyVersionResponse.wrapped_key][google.cloud.kms.v1.ExportTrustedKeyWrappedCryptoKeyVersionResponse.wrapped_key] + and comparing your results to this field. Discard the + response in case of non-matching checksum values, and + perform a limited number of retries. A persistent mismatch + may indicate an issue in your computation of the CRC32C + checksum. Note: This field is defined as int64 for reasons + of compatibility across different languages. However, it is + a non-negative integer, which will never exceed 2^32-1, and + can be safely downconverted to uint32 in languages that + support this type. + """ + + wrapped_key: bytes = proto.Field( + proto.BYTES, + number=1, + ) + wrapped_key_crc32c: wrappers_pb2.Int64Value = proto.Field( + proto.MESSAGE, + number=2, + message=wrappers_pb2.Int64Value, + ) class CreateImportJobRequest(proto.Message): diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_async.py new file mode 100644 index 000000000000..77df02346c95 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ExportTrustedKeyWrappedCryptoKeyVersion +# 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-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ExportTrustedKeyWrappedCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_export_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ExportTrustedKeyWrappedCryptoKeyVersionRequest( + name="name_value", + wrapping_key="wrapping_key_value", + ) + + # Make the request + response = await client.export_trusted_key_wrapped_crypto_key_version( + request=request + ) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_KeyManagementService_ExportTrustedKeyWrappedCryptoKeyVersion_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_sync.py new file mode 100644 index 000000000000..fea3fd2bbb96 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ExportTrustedKeyWrappedCryptoKeyVersion +# 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-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ExportTrustedKeyWrappedCryptoKeyVersion_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 kms_v1 + + +def sample_export_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ExportTrustedKeyWrappedCryptoKeyVersionRequest( + name="name_value", + wrapping_key="wrapping_key_value", + ) + + # Make the request + response = client.export_trusted_key_wrapped_crypto_key_version(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_KeyManagementService_ExportTrustedKeyWrappedCryptoKeyVersion_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py index a1e2c5cae41d..4e4482e2648b 100644 --- a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_async.py @@ -42,7 +42,7 @@ async def sample_import_crypto_key_version(): request = kms_v1.ImportCryptoKeyVersionRequest( rsa_aes_wrapped_key=b"rsa_aes_wrapped_key_blob", parent="parent_value", - algorithm="PQ_SIGN_ML_DSA_87_EXTERNAL_MU", + algorithm="AES_256_KWP", import_job="import_job_value", ) diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py index cc02a62dc71e..927d99c451e5 100644 --- a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py @@ -42,7 +42,7 @@ def sample_import_crypto_key_version(): request = kms_v1.ImportCryptoKeyVersionRequest( rsa_aes_wrapped_key=b"rsa_aes_wrapped_key_blob", parent="parent_value", - algorithm="PQ_SIGN_ML_DSA_87_EXTERNAL_MU", + algorithm="AES_256_KWP", import_job="import_job_value", ) diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_async.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_async.py new file mode 100644 index 000000000000..3634de240ca5 --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ImportTrustedKeyWrappedCryptoKeyVersion +# 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-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ImportTrustedKeyWrappedCryptoKeyVersion_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import kms_v1 + + +async def sample_import_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceAsyncClient() + + # Initialize request argument(s) + request = kms_v1.ImportTrustedKeyWrappedCryptoKeyVersionRequest( + parent="parent_value", + importing_key="importing_key_value", + wrapped_key=b"wrapped_key_blob", + algorithm="AES_256_KWP", + ) + + # Make the request + response = await client.import_trusted_key_wrapped_crypto_key_version( + request=request + ) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_KeyManagementService_ImportTrustedKeyWrappedCryptoKeyVersion_async] diff --git a/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_sync.py b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_sync.py new file mode 100644 index 000000000000..ae01708f192e --- /dev/null +++ b/packages/google-cloud-kms/samples/generated_samples/cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ImportTrustedKeyWrappedCryptoKeyVersion +# 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-kms + + +# [START cloudkms_v1_generated_KeyManagementService_ImportTrustedKeyWrappedCryptoKeyVersion_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 kms_v1 + + +def sample_import_trusted_key_wrapped_crypto_key_version(): + # Create a client + client = kms_v1.KeyManagementServiceClient() + + # Initialize request argument(s) + request = kms_v1.ImportTrustedKeyWrappedCryptoKeyVersionRequest( + parent="parent_value", + importing_key="importing_key_value", + wrapped_key=b"wrapped_key_blob", + algorithm="AES_256_KWP", + ) + + # Make the request + response = client.import_trusted_key_wrapped_crypto_key_version(request=request) + + # Handle the response + print(response) + + +# [END cloudkms_v1_generated_KeyManagementService_ImportTrustedKeyWrappedCryptoKeyVersion_sync] diff --git a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json index c53ebb9dabfc..c7163d04b9c6 100644 --- a/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json +++ b/packages/google-cloud-kms/samples/generated_samples/snippet_metadata_google.cloud.kms.v1.json @@ -5655,6 +5655,159 @@ ], "title": "cloudkms_v1_generated_key_management_service_encrypt_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.export_trusted_key_wrapped_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ExportTrustedKeyWrappedCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionResponse", + "shortName": "export_trusted_key_wrapped_crypto_key_version" + }, + "description": "Sample for ExportTrustedKeyWrappedCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ExportTrustedKeyWrappedCryptoKeyVersion_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.export_trusted_key_wrapped_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ExportTrustedKeyWrappedCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ExportTrustedKeyWrappedCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.ExportTrustedKeyWrappedCryptoKeyVersionResponse", + "shortName": "export_trusted_key_wrapped_crypto_key_version" + }, + "description": "Sample for ExportTrustedKeyWrappedCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ExportTrustedKeyWrappedCryptoKeyVersion_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "cloudkms_v1_generated_key_management_service_export_trusted_key_wrapped_crypto_key_version_sync.py" + }, { "canonical": true, "clientMethod": { @@ -6951,6 +7104,159 @@ ], "title": "cloudkms_v1_generated_key_management_service_import_crypto_key_version_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient", + "shortName": "KeyManagementServiceAsyncClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceAsyncClient.import_trusted_key_wrapped_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ImportTrustedKeyWrappedCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ImportTrustedKeyWrappedCryptoKeyVersionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "import_trusted_key_wrapped_crypto_key_version" + }, + "description": "Sample for ImportTrustedKeyWrappedCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ImportTrustedKeyWrappedCryptoKeyVersion_async", + "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": "cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient", + "shortName": "KeyManagementServiceClient" + }, + "fullName": "google.cloud.kms_v1.KeyManagementServiceClient.import_trusted_key_wrapped_crypto_key_version", + "method": { + "fullName": "google.cloud.kms.v1.KeyManagementService.ImportTrustedKeyWrappedCryptoKeyVersion", + "service": { + "fullName": "google.cloud.kms.v1.KeyManagementService", + "shortName": "KeyManagementService" + }, + "shortName": "ImportTrustedKeyWrappedCryptoKeyVersion" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.kms_v1.types.ImportTrustedKeyWrappedCryptoKeyVersionRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.kms_v1.types.CryptoKeyVersion", + "shortName": "import_trusted_key_wrapped_crypto_key_version" + }, + "description": "Sample for ImportTrustedKeyWrappedCryptoKeyVersion", + "file": "cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "cloudkms_v1_generated_KeyManagementService_ImportTrustedKeyWrappedCryptoKeyVersion_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": "cloudkms_v1_generated_key_management_service_import_trusted_key_wrapped_crypto_key_version_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py index 8e4e86f55505..726bb11300c2 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_hsm_management.py @@ -8185,6 +8185,10 @@ def test_create_single_tenant_hsm_instance_proposal_rest_call_success(request_ty "two_factor_public_key_pem": "two_factor_public_key_pem_value" }, "refresh_single_tenant_hsm_instance": {}, + "upgrade_key_trust": { + "name": "name_value", + "two_factor_public_key_pem": "two_factor_public_key_pem_value", + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency diff --git a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py index 77d3c87eb7e5..3351fae25ea0 100644 --- a/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py +++ b/packages/google-cloud-kms/tests/unit/gapic/kms_v1/test_key_management_service.py @@ -4791,6 +4791,8 @@ def test_get_crypto_key_version(request_type, transport: str = "grpc"): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) response = client.get_crypto_key_version(request) @@ -4820,6 +4822,8 @@ def test_get_crypto_key_version(request_type, transport: str = "grpc"): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True def test_get_crypto_key_version_non_empty_request_with_auto_populated_field(): @@ -4971,6 +4975,8 @@ async def test_get_crypto_key_version_async( generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) response = await client.get_crypto_key_version(request) @@ -5001,6 +5007,8 @@ async def test_get_crypto_key_version_async( == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True def test_get_crypto_key_version_field_headers(): @@ -6938,6 +6946,8 @@ def test_create_crypto_key_version(request_type, transport: str = "grpc"): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) response = client.create_crypto_key_version(request) @@ -6967,6 +6977,8 @@ def test_create_crypto_key_version(request_type, transport: str = "grpc"): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True def test_create_crypto_key_version_non_empty_request_with_auto_populated_field(): @@ -7118,6 +7130,8 @@ async def test_create_crypto_key_version_async( generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) response = await client.create_crypto_key_version(request) @@ -7148,6 +7162,8 @@ async def test_create_crypto_key_version_async( == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True def test_create_crypto_key_version_field_headers(): @@ -8036,6 +8052,8 @@ def test_import_crypto_key_version(request_type, transport: str = "grpc"): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) response = client.import_crypto_key_version(request) @@ -8065,6 +8083,8 @@ def test_import_crypto_key_version(request_type, transport: str = "grpc"): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True def test_import_crypto_key_version_non_empty_request_with_auto_populated_field(): @@ -8220,6 +8240,8 @@ async def test_import_crypto_key_version_async( generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) response = await client.import_crypto_key_version(request) @@ -8250,6 +8272,8 @@ async def test_import_crypto_key_version_async( == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True def test_import_crypto_key_version_field_headers(): @@ -8320,11 +8344,13 @@ async def test_import_crypto_key_version_field_headers_async(): @pytest.mark.parametrize( "request_type", [ - service.CreateImportJobRequest(), + service.ImportTrustedKeyWrappedCryptoKeyVersionRequest(), {}, ], ) -def test_create_import_job(request_type, transport: str = "grpc"): +def test_import_trusted_key_wrapped_crypto_key_version( + request_type, transport: str = "grpc" +): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8336,39 +8362,55 @@ def test_create_import_job(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_import_job), "__call__" + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob( + call.return_value = resources.CryptoKeyVersion( name="name_value", - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - public_key_format=resources.PublicKey.PublicKeyFormat.PEM, - crypto_key_backend="crypto_key_backend_value", + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) - response = client.create_import_job(request) + response = client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateImportJobRequest() + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" assert ( - response.import_method - == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM - assert response.crypto_key_backend == "crypto_key_backend_value" + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_create_import_job_non_empty_request_with_auto_populated_field(): +def test_import_trusted_key_wrapped_crypto_key_version_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -8379,29 +8421,31 @@ def test_create_import_job_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateImportJobRequest( + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest( parent="parent_value", - import_job_id="import_job_id_value", + importing_key="importing_key_value", + crypto_key_version="crypto_key_version_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_import_job), "__call__" + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_import_job(request=request) + client.import_trusted_key_wrapped_crypto_key_version(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.CreateImportJobRequest( + request_msg = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest( parent="parent_value", - import_job_id="import_job_id_value", + importing_key="importing_key_value", + crypto_key_version="crypto_key_version_value", ) assert args[0] == request_msg -def test_create_import_job_use_cached_wrapped_rpc(): +def test_import_trusted_key_wrapped_crypto_key_version_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: @@ -8415,23 +8459,26 @@ def test_create_import_job_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_import_job in client._transport._wrapped_methods + assert ( + client._transport.import_trusted_key_wrapped_crypto_key_version + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_import_job] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.import_trusted_key_wrapped_crypto_key_version + ] = mock_rpc request = {} - client.create_import_job(request) + client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_import_job(request) + client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8439,7 +8486,7 @@ def test_create_import_job_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_import_job_async_use_cached_wrapped_rpc( +async def test_import_trusted_key_wrapped_crypto_key_version_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8456,7 +8503,7 @@ async def test_create_import_job_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_import_job + client._client._transport.import_trusted_key_wrapped_crypto_key_version in client._client._transport._wrapped_methods ) @@ -8464,16 +8511,16 @@ async def test_create_import_job_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_import_job + client._client._transport.import_trusted_key_wrapped_crypto_key_version ] = mock_rpc request = {} - await client.create_import_job(request) + await client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_import_job(request) + await client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8484,11 +8531,13 @@ async def test_create_import_job_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.CreateImportJobRequest(), + service.ImportTrustedKeyWrappedCryptoKeyVersionRequest(), {}, ], ) -async def test_create_import_job_async(request_type, transport: str = "grpc_asyncio"): +async def test_import_trusted_key_wrapped_crypto_key_version_async( + request_type, transport: str = "grpc_asyncio" +): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8500,57 +8549,73 @@ async def test_create_import_job_async(request_type, transport: str = "grpc_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_import_job), "__call__" + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.ImportJob( + resources.CryptoKeyVersion( name="name_value", - import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, protection_level=resources.ProtectionLevel.SOFTWARE, - state=resources.ImportJob.ImportJobState.PENDING_GENERATION, - public_key_format=resources.PublicKey.PublicKeyFormat.PEM, - crypto_key_backend="crypto_key_backend_value", + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) - response = await client.create_import_job(request) + response = await client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateImportJobRequest() + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.ImportJob) + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" assert ( - response.import_method - == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION - assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM - assert response.crypto_key_backend == "crypto_key_backend_value" + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_create_import_job_field_headers(): +def test_import_trusted_key_wrapped_crypto_key_version_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateImportJobRequest() + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_import_job), "__call__" + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: - call.return_value = resources.ImportJob() - client.create_import_job(request) + call.return_value = resources.CryptoKeyVersion() + client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8566,23 +8631,25 @@ def test_create_import_job_field_headers(): @pytest.mark.asyncio -async def test_create_import_job_field_headers_async(): +async def test_import_trusted_key_wrapped_crypto_key_version_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateImportJobRequest() + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.create_import_job), "__call__" + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - await client.create_import_job(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CryptoKeyVersion() + ) + await client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8597,118 +8664,16 @@ async def test_create_import_job_field_headers_async(): ) in kw["metadata"] -def test_create_import_job_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_import_job( - parent="parent_value", - import_job_id="import_job_id_value", - import_job=resources.ImportJob(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].import_job_id - mock_val = "import_job_id_value" - assert arg == mock_val - arg = args[0].import_job - mock_val = resources.ImportJob(name="name_value") - assert arg == mock_val - - -def test_create_import_job_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_import_job( - service.CreateImportJobRequest(), - parent="parent_value", - import_job_id="import_job_id_value", - import_job=resources.ImportJob(name="name_value"), - ) - - -@pytest.mark.asyncio -async def test_create_import_job_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_import_job), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.ImportJob() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_import_job( - parent="parent_value", - import_job_id="import_job_id_value", - import_job=resources.ImportJob(name="name_value"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].import_job_id - mock_val = "import_job_id_value" - assert arg == mock_val - arg = args[0].import_job - mock_val = resources.ImportJob(name="name_value") - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_import_job_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_import_job( - service.CreateImportJobRequest(), - parent="parent_value", - import_job_id="import_job_id_value", - import_job=resources.ImportJob(name="name_value"), - ) - - @pytest.mark.parametrize( "request_type", [ - service.UpdateCryptoKeyRequest(), + service.ExportTrustedKeyWrappedCryptoKeyVersionRequest(), {}, ], ) -def test_update_crypto_key(request_type, transport: str = "grpc"): +def test_export_trusted_key_wrapped_crypto_key_version( + request_type, transport: str = "grpc" +): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8720,32 +8685,26 @@ def test_update_crypto_key(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey( - name="name_value", - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend="crypto_key_backend_value", + call.return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse( + wrapped_key=b"wrapped_key_blob", ) - response = client.update_crypto_key(request) + response = client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyRequest() + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == "name_value" - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == "crypto_key_backend_value" + assert isinstance(response, service.ExportTrustedKeyWrappedCryptoKeyVersionResponse) + assert response.wrapped_key == b"wrapped_key_blob" -def test_update_crypto_key_non_empty_request_with_auto_populated_field(): +def test_export_trusted_key_wrapped_crypto_key_version_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -8756,23 +8715,29 @@ def test_update_crypto_key_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateCryptoKeyRequest() + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest( + name="name_value", + wrapping_key="wrapping_key_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_crypto_key(request=request) + client.export_trusted_key_wrapped_crypto_key_version(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyRequest() + request_msg = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest( + name="name_value", + wrapping_key="wrapping_key_value", + ) assert args[0] == request_msg -def test_update_crypto_key_use_cached_wrapped_rpc(): +def test_export_trusted_key_wrapped_crypto_key_version_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: @@ -8786,23 +8751,26 @@ def test_update_crypto_key_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_crypto_key in client._transport._wrapped_methods + assert ( + client._transport.export_trusted_key_wrapped_crypto_key_version + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.export_trusted_key_wrapped_crypto_key_version + ] = mock_rpc request = {} - client.update_crypto_key(request) + client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_crypto_key(request) + client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8810,7 +8778,7 @@ def test_update_crypto_key_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_crypto_key_async_use_cached_wrapped_rpc( +async def test_export_trusted_key_wrapped_crypto_key_version_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8827,7 +8795,7 @@ async def test_update_crypto_key_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_crypto_key + client._client._transport.export_trusted_key_wrapped_crypto_key_version in client._client._transport._wrapped_methods ) @@ -8835,16 +8803,16 @@ async def test_update_crypto_key_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_crypto_key + client._client._transport.export_trusted_key_wrapped_crypto_key_version ] = mock_rpc request = {} - await client.update_crypto_key(request) + await client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_crypto_key(request) + await client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8855,11 +8823,13 @@ async def test_update_crypto_key_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.UpdateCryptoKeyRequest(), + service.ExportTrustedKeyWrappedCryptoKeyVersionRequest(), {}, ], ) -async def test_update_crypto_key_async(request_type, transport: str = "grpc_asyncio"): +async def test_export_trusted_key_wrapped_crypto_key_version_async( + request_type, transport: str = "grpc_asyncio" +): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -8871,50 +8841,44 @@ async def test_update_crypto_key_async(request_type, transport: str = "grpc_asyn # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKey( - name="name_value", - purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, - import_only=True, - crypto_key_backend="crypto_key_backend_value", + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse( + wrapped_key=b"wrapped_key_blob", ) ) - response = await client.update_crypto_key(request) + response = await client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyRequest() + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKey) - assert response.name == "name_value" - assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT - assert response.import_only is True - assert response.crypto_key_backend == "crypto_key_backend_value" + assert isinstance(response, service.ExportTrustedKeyWrappedCryptoKeyVersionResponse) + assert response.wrapped_key == b"wrapped_key_blob" -def test_update_crypto_key_field_headers(): +def test_export_trusted_key_wrapped_crypto_key_version_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyRequest() + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() - request.crypto_key.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: - call.return_value = resources.CryptoKey() - client.update_crypto_key(request) + call.return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() + client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8925,28 +8889,30 @@ def test_update_crypto_key_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "crypto_key.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_crypto_key_field_headers_async(): +async def test_export_trusted_key_wrapped_crypto_key_version_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyRequest() + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() - request.crypto_key.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.update_crypto_key(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() + ) + await client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8957,112 +8923,18 @@ async def test_update_crypto_key_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "crypto_key.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_crypto_key_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_crypto_key( - crypto_key=resources.CryptoKey(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].crypto_key - mock_val = resources.CryptoKey(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -def test_update_crypto_key_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - -@pytest.mark.asyncio -async def test_update_crypto_key_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.update_crypto_key), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKey() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.update_crypto_key( - crypto_key=resources.CryptoKey(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].crypto_key - mock_val = resources.CryptoKey(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_update_crypto_key_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.update_crypto_key( - service.UpdateCryptoKeyRequest(), - crypto_key=resources.CryptoKey(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), - ) - - @pytest.mark.parametrize( "request_type", [ - service.UpdateCryptoKeyVersionRequest(), + service.CreateImportJobRequest(), {}, ], ) -def test_update_crypto_key_version(request_type, transport: str = "grpc"): +def test_create_import_job(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9074,51 +8946,39 @@ def test_update_crypto_key_version(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( + call.return_value = resources.ImportJob( name="name_value", - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job="import_job_value", - import_failure_reason="import_failure_reason_value", - generation_failure_reason="generation_failure_reason_value", - external_destruction_failure_reason="external_destruction_failure_reason_value", - reimport_eligible=True, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, + crypto_key_backend="crypto_key_backend_value", ) - response = client.update_crypto_key_version(request) + response = client.create_import_job(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyVersionRequest() + request = service.CreateImportJobRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) + assert isinstance(response, resources.ImportJob) assert response.name == "name_value" assert ( - response.state - == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + response.import_method + == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert ( - response.algorithm - == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - ) - assert response.import_job == "import_job_value" - assert response.import_failure_reason == "import_failure_reason_value" - assert response.generation_failure_reason == "generation_failure_reason_value" - assert ( - response.external_destruction_failure_reason - == "external_destruction_failure_reason_value" - ) - assert response.reimport_eligible is True + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM + assert response.crypto_key_backend == "crypto_key_backend_value" -def test_update_crypto_key_version_non_empty_request_with_auto_populated_field(): +def test_create_import_job_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -9129,23 +8989,29 @@ def test_update_crypto_key_version_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateCryptoKeyVersionRequest() + request = service.CreateImportJobRequest( + parent="parent_value", + import_job_id="import_job_id_value", + ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_crypto_key_version(request=request) + client.create_import_job(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyVersionRequest() + request_msg = service.CreateImportJobRequest( + parent="parent_value", + import_job_id="import_job_id_value", + ) assert args[0] == request_msg -def test_update_crypto_key_version_use_cached_wrapped_rpc(): +def test_create_import_job_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: @@ -9159,26 +9025,23 @@ def test_update_crypto_key_version_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_crypto_key_version - in client._transport._wrapped_methods - ) + assert client._transport.create_import_job in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_crypto_key_version - ] = mock_rpc + client._transport._wrapped_methods[client._transport.create_import_job] = ( + mock_rpc + ) request = {} - client.update_crypto_key_version(request) + client.create_import_job(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_crypto_key_version(request) + client.create_import_job(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9186,7 +9049,7 @@ def test_update_crypto_key_version_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_crypto_key_version_async_use_cached_wrapped_rpc( +async def test_create_import_job_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9203,7 +9066,7 @@ async def test_update_crypto_key_version_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_crypto_key_version + client._client._transport.create_import_job in client._client._transport._wrapped_methods ) @@ -9211,16 +9074,16 @@ async def test_update_crypto_key_version_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_crypto_key_version + client._client._transport.create_import_job ] = mock_rpc request = {} - await client.update_crypto_key_version(request) + await client.create_import_job(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_crypto_key_version(request) + await client.create_import_job(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9231,13 +9094,11 @@ async def test_update_crypto_key_version_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.UpdateCryptoKeyVersionRequest(), + service.CreateImportJobRequest(), {}, ], ) -async def test_update_crypto_key_version_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_create_import_job_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9249,69 +9110,57 @@ async def test_update_crypto_key_version_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKeyVersion( + resources.ImportJob( name="name_value", - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + import_method=resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256, protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job="import_job_value", - import_failure_reason="import_failure_reason_value", - generation_failure_reason="generation_failure_reason_value", - external_destruction_failure_reason="external_destruction_failure_reason_value", - reimport_eligible=True, + state=resources.ImportJob.ImportJobState.PENDING_GENERATION, + public_key_format=resources.PublicKey.PublicKeyFormat.PEM, + crypto_key_backend="crypto_key_backend_value", ) ) - response = await client.update_crypto_key_version(request) + response = await client.create_import_job(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyVersionRequest() + request = service.CreateImportJobRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) + assert isinstance(response, resources.ImportJob) assert response.name == "name_value" assert ( - response.state - == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + response.import_method + == resources.ImportJob.ImportMethod.RSA_OAEP_3072_SHA1_AES_256 ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert ( - response.algorithm - == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - ) - assert response.import_job == "import_job_value" - assert response.import_failure_reason == "import_failure_reason_value" - assert response.generation_failure_reason == "generation_failure_reason_value" - assert ( - response.external_destruction_failure_reason - == "external_destruction_failure_reason_value" - ) - assert response.reimport_eligible is True + assert response.state == resources.ImportJob.ImportJobState.PENDING_GENERATION + assert response.public_key_format == resources.PublicKey.PublicKeyFormat.PEM + assert response.crypto_key_backend == "crypto_key_backend_value" -def test_update_crypto_key_version_field_headers(): +def test_create_import_job_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyVersionRequest() + request = service.CreateImportJobRequest() - request.crypto_key_version.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: - call.return_value = resources.CryptoKeyVersion() - client.update_crypto_key_version(request) + call.return_value = resources.ImportJob() + client.create_import_job(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9322,30 +9171,28 @@ def test_update_crypto_key_version_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "crypto_key_version.name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_crypto_key_version_field_headers_async(): +async def test_create_import_job_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyVersionRequest() + request = service.CreateImportJobRequest() - request.crypto_key_version.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKeyVersion() - ) - await client.update_crypto_key_version(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) + await client.create_import_job(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9356,41 +9203,45 @@ async def test_update_crypto_key_version_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "crypto_key_version.name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_update_crypto_key_version_flattened(): +def test_create_import_job_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() + call.return_value = resources.ImportJob() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_crypto_key_version( - crypto_key_version=resources.CryptoKeyVersion(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_import_job( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=resources.ImportJob(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].crypto_key_version - mock_val = resources.CryptoKeyVersion(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].import_job_id + mock_val = "import_job_id_value" + assert arg == mock_val + arg = args[0].import_job + mock_val = resources.ImportJob(name="name_value") assert arg == mock_val -def test_update_crypto_key_version_flattened_error(): +def test_create_import_job_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9398,50 +9249,53 @@ def test_update_crypto_key_version_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.create_import_job( + service.CreateImportJobRequest(), + parent="parent_value", + import_job_id="import_job_id_value", + import_job=resources.ImportJob(name="name_value"), ) @pytest.mark.asyncio -async def test_update_crypto_key_version_flattened_async(): +async def test_create_import_job_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_version), "__call__" + type(client.transport.create_import_job), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() + call.return_value = resources.ImportJob() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKeyVersion() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.ImportJob()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_crypto_key_version( - crypto_key_version=resources.CryptoKeyVersion(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.create_import_job( + parent="parent_value", + import_job_id="import_job_id_value", + import_job=resources.ImportJob(name="name_value"), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].crypto_key_version - mock_val = resources.CryptoKeyVersion(name="name_value") + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].import_job_id + mock_val = "import_job_id_value" + assert arg == mock_val + arg = args[0].import_job + mock_val = resources.ImportJob(name="name_value") assert arg == mock_val @pytest.mark.asyncio -async def test_update_crypto_key_version_flattened_error_async(): +async def test_create_import_job_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9449,21 +9303,22 @@ async def test_update_crypto_key_version_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_crypto_key_version( - service.UpdateCryptoKeyVersionRequest(), - crypto_key_version=resources.CryptoKeyVersion(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.create_import_job( + service.CreateImportJobRequest(), + parent="parent_value", + import_job_id="import_job_id_value", + import_job=resources.ImportJob(name="name_value"), ) @pytest.mark.parametrize( "request_type", [ - service.UpdateCryptoKeyPrimaryVersionRequest(), + service.UpdateCryptoKeyRequest(), {}, ], ) -def test_update_crypto_key_primary_version(request_type, transport: str = "grpc"): +def test_update_crypto_key(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9475,7 +9330,7 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey( @@ -9484,12 +9339,12 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" import_only=True, crypto_key_backend="crypto_key_backend_value", ) - response = client.update_crypto_key_primary_version(request) + response = client.update_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyPrimaryVersionRequest() + request = service.UpdateCryptoKeyRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -9500,7 +9355,7 @@ def test_update_crypto_key_primary_version(request_type, transport: str = "grpc" assert response.crypto_key_backend == "crypto_key_backend_value" -def test_update_crypto_key_primary_version_non_empty_request_with_auto_populated_field(): +def test_update_crypto_key_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -9511,29 +9366,23 @@ def test_update_crypto_key_primary_version_non_empty_request_with_auto_populated # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateCryptoKeyPrimaryVersionRequest( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", - ) + request = service.UpdateCryptoKeyRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_crypto_key_primary_version(request=request) + client.update_crypto_key(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.UpdateCryptoKeyPrimaryVersionRequest( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", - ) + request_msg = service.UpdateCryptoKeyRequest() assert args[0] == request_msg -def test_update_crypto_key_primary_version_use_cached_wrapped_rpc(): +def test_update_crypto_key_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: @@ -9547,26 +9396,23 @@ def test_update_crypto_key_primary_version_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.update_crypto_key_primary_version - in client._transport._wrapped_methods - ) + assert client._transport.update_crypto_key in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.update_crypto_key_primary_version - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_crypto_key] = ( + mock_rpc + ) request = {} - client.update_crypto_key_primary_version(request) + client.update_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_crypto_key_primary_version(request) + client.update_crypto_key(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9574,7 +9420,7 @@ def test_update_crypto_key_primary_version_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc( +async def test_update_crypto_key_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9591,7 +9437,7 @@ async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_crypto_key_primary_version + client._client._transport.update_crypto_key in client._client._transport._wrapped_methods ) @@ -9599,16 +9445,16 @@ async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_crypto_key_primary_version + client._client._transport.update_crypto_key ] = mock_rpc request = {} - await client.update_crypto_key_primary_version(request) + await client.update_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_crypto_key_primary_version(request) + await client.update_crypto_key(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9619,13 +9465,11 @@ async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.UpdateCryptoKeyPrimaryVersionRequest(), + service.UpdateCryptoKeyRequest(), {}, ], ) -async def test_update_crypto_key_primary_version_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_update_crypto_key_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -9637,7 +9481,7 @@ async def test_update_crypto_key_primary_version_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -9648,12 +9492,12 @@ async def test_update_crypto_key_primary_version_async( crypto_key_backend="crypto_key_backend_value", ) ) - response = await client.update_crypto_key_primary_version(request) + response = await client.update_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateCryptoKeyPrimaryVersionRequest() + request = service.UpdateCryptoKeyRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -9664,23 +9508,23 @@ async def test_update_crypto_key_primary_version_async( assert response.crypto_key_backend == "crypto_key_backend_value" -def test_update_crypto_key_primary_version_field_headers(): +def test_update_crypto_key_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyPrimaryVersionRequest() + request = service.UpdateCryptoKeyRequest() - request.name = "name_value" + request.crypto_key.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: call.return_value = resources.CryptoKey() - client.update_crypto_key_primary_version(request) + client.update_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9691,28 +9535,28 @@ def test_update_crypto_key_primary_version_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "crypto_key.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_crypto_key_primary_version_field_headers_async(): +async def test_update_crypto_key_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateCryptoKeyPrimaryVersionRequest() + request = service.UpdateCryptoKeyRequest() - request.name = "name_value" + request.crypto_key.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) - await client.update_crypto_key_primary_version(request) + await client.update_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9723,41 +9567,41 @@ async def test_update_crypto_key_primary_version_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "crypto_key.name=name_value", ) in kw["metadata"] -def test_update_crypto_key_primary_version_flattened(): +def test_update_crypto_key_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_crypto_key_primary_version( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", + client.update_crypto_key( + crypto_key=resources.CryptoKey(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name="name_value") assert arg == mock_val - arg = args[0].crypto_key_version_id - mock_val = "crypto_key_version_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_update_crypto_key_primary_version_flattened_error(): +def test_update_crypto_key_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9765,22 +9609,22 @@ def test_update_crypto_key_primary_version_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", + client.update_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_update_crypto_key_primary_version_flattened_async(): +async def test_update_crypto_key_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.update_crypto_key_primary_version), "__call__" + type(client.transport.update_crypto_key), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKey() @@ -9788,25 +9632,25 @@ async def test_update_crypto_key_primary_version_flattened_async(): call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_crypto_key_primary_version( - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", + response = await client.update_crypto_key( + crypto_key=resources.CryptoKey(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].crypto_key + mock_val = resources.CryptoKey(name="name_value") assert arg == mock_val - arg = args[0].crypto_key_version_id - mock_val = "crypto_key_version_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_update_crypto_key_primary_version_flattened_error_async(): +async def test_update_crypto_key_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9814,21 +9658,21 @@ async def test_update_crypto_key_primary_version_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_crypto_key_primary_version( - service.UpdateCryptoKeyPrimaryVersionRequest(), - name="name_value", - crypto_key_version_id="crypto_key_version_id_value", + await client.update_crypto_key( + service.UpdateCryptoKeyRequest(), + crypto_key=resources.CryptoKey(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - service.DestroyCryptoKeyVersionRequest(), + service.UpdateCryptoKeyVersionRequest(), {}, ], ) -def test_destroy_crypto_key_version(request_type, transport: str = "grpc"): +def test_update_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9840,7 +9684,7 @@ def test_destroy_crypto_key_version(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion( @@ -9853,13 +9697,15 @@ def test_destroy_crypto_key_version(request_type, transport: str = "grpc"): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) - response = client.destroy_crypto_key_version(request) + response = client.update_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DestroyCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -9882,9 +9728,11 @@ def test_destroy_crypto_key_version(request_type, transport: str = "grpc"): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_destroy_crypto_key_version_non_empty_request_with_auto_populated_field(): +def test_update_crypto_key_version_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -9895,27 +9743,23 @@ def test_destroy_crypto_key_version_non_empty_request_with_auto_populated_field( # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DestroyCryptoKeyVersionRequest( - name="name_value", - ) + request = service.UpdateCryptoKeyVersionRequest() # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.destroy_crypto_key_version(request=request) + client.update_crypto_key_version(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.DestroyCryptoKeyVersionRequest( - name="name_value", - ) + request_msg = service.UpdateCryptoKeyVersionRequest() assert args[0] == request_msg -def test_destroy_crypto_key_version_use_cached_wrapped_rpc(): +def test_update_crypto_key_version_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: @@ -9930,7 +9774,7 @@ def test_destroy_crypto_key_version_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.destroy_crypto_key_version + client._transport.update_crypto_key_version in client._transport._wrapped_methods ) @@ -9940,15 +9784,15 @@ def test_destroy_crypto_key_version_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.destroy_crypto_key_version + client._transport.update_crypto_key_version ] = mock_rpc request = {} - client.destroy_crypto_key_version(request) + client.update_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.destroy_crypto_key_version(request) + client.update_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9956,7 +9800,7 @@ def test_destroy_crypto_key_version_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc( +async def test_update_crypto_key_version_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9973,7 +9817,7 @@ async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.destroy_crypto_key_version + client._client._transport.update_crypto_key_version in client._client._transport._wrapped_methods ) @@ -9981,16 +9825,16 @@ async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.destroy_crypto_key_version + client._client._transport.update_crypto_key_version ] = mock_rpc request = {} - await client.destroy_crypto_key_version(request) + await client.update_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.destroy_crypto_key_version(request) + await client.update_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10001,11 +9845,11 @@ async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.DestroyCryptoKeyVersionRequest(), + service.UpdateCryptoKeyVersionRequest(), {}, ], ) -async def test_destroy_crypto_key_version_async( +async def test_update_crypto_key_version_async( request_type, transport: str = "grpc_asyncio" ): client = KeyManagementServiceAsyncClient( @@ -10019,7 +9863,7 @@ async def test_destroy_crypto_key_version_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( @@ -10033,14 +9877,16 @@ async def test_destroy_crypto_key_version_async( generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) - response = await client.destroy_crypto_key_version(request) + response = await client.update_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DestroyCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -10063,25 +9909,27 @@ async def test_destroy_crypto_key_version_async( == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_destroy_crypto_key_version_field_headers(): +def test_update_crypto_key_version_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DestroyCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyVersionRequest() - request.name = "name_value" + request.crypto_key_version.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: call.return_value = resources.CryptoKeyVersion() - client.destroy_crypto_key_version(request) + client.update_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10092,30 +9940,30 @@ def test_destroy_crypto_key_version_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "crypto_key_version.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_destroy_crypto_key_version_field_headers_async(): +async def test_update_crypto_key_version_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DestroyCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyVersionRequest() - request.name = "name_value" + request.crypto_key_version.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.CryptoKeyVersion() ) - await client.destroy_crypto_key_version(request) + await client.update_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10126,37 +9974,41 @@ async def test_destroy_crypto_key_version_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "crypto_key_version.name=name_value", ) in kw["metadata"] -def test_destroy_crypto_key_version_flattened(): +def test_update_crypto_key_version_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.destroy_crypto_key_version( - name="name_value", + client.update_crypto_key_version( + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].crypto_key_version + mock_val = resources.CryptoKeyVersion(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_destroy_crypto_key_version_flattened_error(): +def test_update_crypto_key_version_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10164,21 +10016,22 @@ def test_destroy_crypto_key_version_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name="name_value", + client.update_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_destroy_crypto_key_version_flattened_async(): +async def test_update_crypto_key_version_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.destroy_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = resources.CryptoKeyVersion() @@ -10188,21 +10041,25 @@ async def test_destroy_crypto_key_version_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.destroy_crypto_key_version( - name="name_value", + response = await client.update_crypto_key_version( + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].crypto_key_version + mock_val = resources.CryptoKeyVersion(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_destroy_crypto_key_version_flattened_error_async(): +async def test_update_crypto_key_version_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10210,20 +10067,21 @@ async def test_destroy_crypto_key_version_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.destroy_crypto_key_version( - service.DestroyCryptoKeyVersionRequest(), - name="name_value", + await client.update_crypto_key_version( + service.UpdateCryptoKeyVersionRequest(), + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - service.RestoreCryptoKeyVersionRequest(), + service.UpdateCryptoKeyPrimaryVersionRequest(), {}, ], ) -def test_restore_crypto_key_version(request_type, transport: str = "grpc"): +def test_update_crypto_key_primary_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10235,51 +10093,32 @@ def test_restore_crypto_key_version(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion( + call.return_value = resources.CryptoKey( name="name_value", - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job="import_job_value", - import_failure_reason="import_failure_reason_value", - generation_failure_reason="generation_failure_reason_value", - external_destruction_failure_reason="external_destruction_failure_reason_value", - reimport_eligible=True, + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend="crypto_key_backend_value", ) - response = client.restore_crypto_key_version(request) + response = client.update_crypto_key_primary_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.RestoreCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyPrimaryVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) + assert isinstance(response, resources.CryptoKey) assert response.name == "name_value" - assert ( - response.state - == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - ) - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert ( - response.algorithm - == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - ) - assert response.import_job == "import_job_value" - assert response.import_failure_reason == "import_failure_reason_value" - assert response.generation_failure_reason == "generation_failure_reason_value" - assert ( - response.external_destruction_failure_reason - == "external_destruction_failure_reason_value" - ) - assert response.reimport_eligible is True + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" -def test_restore_crypto_key_version_non_empty_request_with_auto_populated_field(): +def test_update_crypto_key_primary_version_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -10290,27 +10129,29 @@ def test_restore_crypto_key_version_non_empty_request_with_auto_populated_field( # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.RestoreCryptoKeyVersionRequest( + request = service.UpdateCryptoKeyPrimaryVersionRequest( name="name_value", + crypto_key_version_id="crypto_key_version_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.restore_crypto_key_version(request=request) + client.update_crypto_key_primary_version(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.RestoreCryptoKeyVersionRequest( + request_msg = service.UpdateCryptoKeyPrimaryVersionRequest( name="name_value", + crypto_key_version_id="crypto_key_version_id_value", ) assert args[0] == request_msg -def test_restore_crypto_key_version_use_cached_wrapped_rpc(): +def test_update_crypto_key_primary_version_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: @@ -10325,7 +10166,7 @@ def test_restore_crypto_key_version_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.restore_crypto_key_version + client._transport.update_crypto_key_primary_version in client._transport._wrapped_methods ) @@ -10335,15 +10176,15 @@ def test_restore_crypto_key_version_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.restore_crypto_key_version + client._transport.update_crypto_key_primary_version ] = mock_rpc request = {} - client.restore_crypto_key_version(request) + client.update_crypto_key_primary_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.restore_crypto_key_version(request) + client.update_crypto_key_primary_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10351,7 +10192,7 @@ def test_restore_crypto_key_version_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc( +async def test_update_crypto_key_primary_version_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10368,7 +10209,7 @@ async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.restore_crypto_key_version + client._client._transport.update_crypto_key_primary_version in client._client._transport._wrapped_methods ) @@ -10376,16 +10217,16 @@ async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.restore_crypto_key_version + client._client._transport.update_crypto_key_primary_version ] = mock_rpc request = {} - await client.restore_crypto_key_version(request) + await client.update_crypto_key_primary_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.restore_crypto_key_version(request) + await client.update_crypto_key_primary_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10396,11 +10237,11 @@ async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.RestoreCryptoKeyVersionRequest(), + service.UpdateCryptoKeyPrimaryVersionRequest(), {}, ], ) -async def test_restore_crypto_key_version_async( +async def test_update_crypto_key_primary_version_async( request_type, transport: str = "grpc_asyncio" ): client = KeyManagementServiceAsyncClient( @@ -10414,69 +10255,50 @@ async def test_restore_crypto_key_version_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKeyVersion( + resources.CryptoKey( name="name_value", - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job="import_job_value", - import_failure_reason="import_failure_reason_value", - generation_failure_reason="generation_failure_reason_value", - external_destruction_failure_reason="external_destruction_failure_reason_value", - reimport_eligible=True, + purpose=resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT, + import_only=True, + crypto_key_backend="crypto_key_backend_value", ) ) - response = await client.restore_crypto_key_version(request) + response = await client.update_crypto_key_primary_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.RestoreCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyPrimaryVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) + assert isinstance(response, resources.CryptoKey) assert response.name == "name_value" - assert ( - response.state - == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - ) - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert ( - response.algorithm - == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - ) - assert response.import_job == "import_job_value" - assert response.import_failure_reason == "import_failure_reason_value" - assert response.generation_failure_reason == "generation_failure_reason_value" - assert ( - response.external_destruction_failure_reason - == "external_destruction_failure_reason_value" - ) - assert response.reimport_eligible is True - - -def test_restore_crypto_key_version_field_headers(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), + assert response.purpose == resources.CryptoKey.CryptoKeyPurpose.ENCRYPT_DECRYPT + assert response.import_only is True + assert response.crypto_key_backend == "crypto_key_backend_value" + + +def test_update_crypto_key_primary_version_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RestoreCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyPrimaryVersionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: - call.return_value = resources.CryptoKeyVersion() - client.restore_crypto_key_version(request) + call.return_value = resources.CryptoKey() + client.update_crypto_key_primary_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10492,25 +10314,23 @@ def test_restore_crypto_key_version_field_headers(): @pytest.mark.asyncio -async def test_restore_crypto_key_version_field_headers_async(): +async def test_update_crypto_key_primary_version_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RestoreCryptoKeyVersionRequest() + request = service.UpdateCryptoKeyPrimaryVersionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKeyVersion() - ) - await client.restore_crypto_key_version(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) + await client.update_crypto_key_primary_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10525,21 +10345,22 @@ async def test_restore_crypto_key_version_field_headers_async(): ) in kw["metadata"] -def test_restore_crypto_key_version_flattened(): +def test_update_crypto_key_primary_version_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() + call.return_value = resources.CryptoKey() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.restore_crypto_key_version( + client.update_crypto_key_primary_version( name="name_value", + crypto_key_version_id="crypto_key_version_id_value", ) # Establish that the underlying call was made with the expected @@ -10549,9 +10370,12 @@ def test_restore_crypto_key_version_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].crypto_key_version_id + mock_val = "crypto_key_version_id_value" + assert arg == mock_val -def test_restore_crypto_key_version_flattened_error(): +def test_update_crypto_key_primary_version_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10559,32 +10383,32 @@ def test_restore_crypto_key_version_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), + client.update_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), name="name_value", + crypto_key_version_id="crypto_key_version_id_value", ) @pytest.mark.asyncio -async def test_restore_crypto_key_version_flattened_async(): +async def test_update_crypto_key_primary_version_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.restore_crypto_key_version), "__call__" + type(client.transport.update_crypto_key_primary_version), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.CryptoKeyVersion() + call.return_value = resources.CryptoKey() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.CryptoKeyVersion() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.CryptoKey()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.restore_crypto_key_version( + response = await client.update_crypto_key_primary_version( name="name_value", + crypto_key_version_id="crypto_key_version_id_value", ) # Establish that the underlying call was made with the expected @@ -10594,10 +10418,13 @@ async def test_restore_crypto_key_version_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val + arg = args[0].crypto_key_version_id + mock_val = "crypto_key_version_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_restore_crypto_key_version_flattened_error_async(): +async def test_update_crypto_key_primary_version_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10605,20 +10432,21 @@ async def test_restore_crypto_key_version_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.restore_crypto_key_version( - service.RestoreCryptoKeyVersionRequest(), + await client.update_crypto_key_primary_version( + service.UpdateCryptoKeyPrimaryVersionRequest(), name="name_value", + crypto_key_version_id="crypto_key_version_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.EncryptRequest(), + service.DestroyCryptoKeyVersionRequest(), {}, ], ) -def test_encrypt(request_type, transport: str = "grpc"): +def test_destroy_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10629,33 +10457,56 @@ def test_encrypt(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse( + call.return_value = resources.CryptoKeyVersion( name="name_value", - ciphertext=b"ciphertext_blob", - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) - response = client.encrypt(request) + response = client.destroy_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.EncryptRequest() + request = service.DestroyCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" - assert response.ciphertext == b"ciphertext_blob" - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_encrypt_non_empty_request_with_auto_populated_field(): +def test_destroy_crypto_key_version_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -10666,25 +10517,27 @@ def test_encrypt_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.EncryptRequest( + request = service.DestroyCryptoKeyVersionRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.encrypt(request=request) + client.destroy_crypto_key_version(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.EncryptRequest( + request_msg = service.DestroyCryptoKeyVersionRequest( name="name_value", ) assert args[0] == request_msg -def test_encrypt_use_cached_wrapped_rpc(): +def test_destroy_crypto_key_version_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: @@ -10698,21 +10551,26 @@ def test_encrypt_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.encrypt in client._transport._wrapped_methods + assert ( + client._transport.destroy_crypto_key_version + 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.encrypt] = mock_rpc + client._transport._wrapped_methods[ + client._transport.destroy_crypto_key_version + ] = mock_rpc request = {} - client.encrypt(request) + client.destroy_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.encrypt(request) + client.destroy_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10720,7 +10578,9 @@ def test_encrypt_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_destroy_crypto_key_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -10735,7 +10595,7 @@ async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_async # Ensure method has been cached assert ( - client._client._transport.encrypt + client._client._transport.destroy_crypto_key_version in client._client._transport._wrapped_methods ) @@ -10743,16 +10603,16 @@ async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_async mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.encrypt + client._client._transport.destroy_crypto_key_version ] = mock_rpc request = {} - await client.encrypt(request) + await client.destroy_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.encrypt(request) + await client.destroy_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10763,11 +10623,13 @@ async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_async @pytest.mark.parametrize( "request_type", [ - service.EncryptRequest(), + service.DestroyCryptoKeyVersionRequest(), {}, ], ) -async def test_encrypt_async(request_type, transport: str = "grpc_asyncio"): +async def test_destroy_crypto_key_version_async( + request_type, transport: str = "grpc_asyncio" +): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -10778,49 +10640,74 @@ async def test_encrypt_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.EncryptResponse( + resources.CryptoKeyVersion( name="name_value", - ciphertext=b"ciphertext_blob", - verified_plaintext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) - response = await client.encrypt(request) + response = await client.destroy_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.EncryptRequest() + request = service.DestroyCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.EncryptResponse) + assert isinstance(response, resources.CryptoKeyVersion) assert response.name == "name_value" - assert response.ciphertext == b"ciphertext_blob" - assert response.verified_plaintext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_encrypt_field_headers(): +def test_destroy_crypto_key_version_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.EncryptRequest() + request = service.DestroyCryptoKeyVersionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: - call.return_value = service.EncryptResponse() - client.encrypt(request) + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: + call.return_value = resources.CryptoKeyVersion() + client.destroy_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10836,23 +10723,25 @@ def test_encrypt_field_headers(): @pytest.mark.asyncio -async def test_encrypt_field_headers_async(): +async def test_destroy_crypto_key_version_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.EncryptRequest() + request = service.DestroyCryptoKeyVersionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.EncryptResponse() + resources.CryptoKeyVersion() ) - await client.encrypt(request) + await client.destroy_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10867,20 +10756,21 @@ async def test_encrypt_field_headers_async(): ) in kw["metadata"] -def test_encrypt_flattened(): +def test_destroy_crypto_key_version_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse() + call.return_value = resources.CryptoKeyVersion() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.encrypt( + client.destroy_crypto_key_version( name="name_value", - plaintext=b"plaintext_blob", ) # Establish that the underlying call was made with the expected @@ -10890,12 +10780,9 @@ def test_encrypt_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].plaintext - mock_val = b"plaintext_blob" - assert arg == mock_val -def test_encrypt_flattened_error(): +def test_destroy_crypto_key_version_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10903,32 +10790,32 @@ def test_encrypt_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.encrypt( - service.EncryptRequest(), + client.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), name="name_value", - plaintext=b"plaintext_blob", ) @pytest.mark.asyncio -async def test_encrypt_flattened_async(): +async def test_destroy_crypto_key_version_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.destroy_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.EncryptResponse() + call.return_value = resources.CryptoKeyVersion() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.EncryptResponse() + resources.CryptoKeyVersion() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.encrypt( + response = await client.destroy_crypto_key_version( name="name_value", - plaintext=b"plaintext_blob", ) # Establish that the underlying call was made with the expected @@ -10938,13 +10825,10 @@ async def test_encrypt_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].plaintext - mock_val = b"plaintext_blob" - assert arg == mock_val @pytest.mark.asyncio -async def test_encrypt_flattened_error_async(): +async def test_destroy_crypto_key_version_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10952,21 +10836,20 @@ async def test_encrypt_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.encrypt( - service.EncryptRequest(), + await client.destroy_crypto_key_version( + service.DestroyCryptoKeyVersionRequest(), name="name_value", - plaintext=b"plaintext_blob", ) @pytest.mark.parametrize( "request_type", [ - service.DecryptRequest(), + service.RestoreCryptoKeyVersionRequest(), {}, ], ) -def test_decrypt(request_type, transport: str = "grpc"): +def test_restore_crypto_key_version(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10977,29 +10860,56 @@ def test_decrypt(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse( - plaintext=b"plaintext_blob", - used_primary=True, + call.return_value = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) - response = client.decrypt(request) + response = client.restore_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DecryptRequest() + request = service.RestoreCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b"plaintext_blob" - assert response.used_primary is True + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_decrypt_non_empty_request_with_auto_populated_field(): +def test_restore_crypto_key_version_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -11010,25 +10920,27 @@ def test_decrypt_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DecryptRequest( + request = service.RestoreCryptoKeyVersionRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.decrypt(request=request) + client.restore_crypto_key_version(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.DecryptRequest( + request_msg = service.RestoreCryptoKeyVersionRequest( name="name_value", ) assert args[0] == request_msg -def test_decrypt_use_cached_wrapped_rpc(): +def test_restore_crypto_key_version_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: @@ -11042,21 +10954,26 @@ def test_decrypt_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.decrypt in client._transport._wrapped_methods + assert ( + client._transport.restore_crypto_key_version + 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.decrypt] = mock_rpc + client._transport._wrapped_methods[ + client._transport.restore_crypto_key_version + ] = mock_rpc request = {} - client.decrypt(request) + client.restore_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.decrypt(request) + client.restore_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11064,7 +10981,9 @@ def test_decrypt_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_restore_crypto_key_version_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -11079,7 +10998,7 @@ async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_async # Ensure method has been cached assert ( - client._client._transport.decrypt + client._client._transport.restore_crypto_key_version in client._client._transport._wrapped_methods ) @@ -11087,16 +11006,16 @@ async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_async mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.decrypt + client._client._transport.restore_crypto_key_version ] = mock_rpc request = {} - await client.decrypt(request) + await client.restore_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.decrypt(request) + await client.restore_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11107,11 +11026,13 @@ async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_async @pytest.mark.parametrize( "request_type", [ - service.DecryptRequest(), + service.RestoreCryptoKeyVersionRequest(), {}, ], ) -async def test_decrypt_async(request_type, transport: str = "grpc_asyncio"): +async def test_restore_crypto_key_version_async( + request_type, transport: str = "grpc_asyncio" +): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11122,45 +11043,74 @@ async def test_decrypt_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.DecryptResponse( - plaintext=b"plaintext_blob", - used_primary=True, + resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) - response = await client.decrypt(request) + response = await client.restore_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DecryptRequest() + request = service.RestoreCryptoKeyVersionRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.DecryptResponse) - assert response.plaintext == b"plaintext_blob" - assert response.used_primary is True + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True -def test_decrypt_field_headers(): +def test_restore_crypto_key_version_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DecryptRequest() + request = service.RestoreCryptoKeyVersionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: - call.return_value = service.DecryptResponse() - client.decrypt(request) + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: + call.return_value = resources.CryptoKeyVersion() + client.restore_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11176,23 +11126,25 @@ def test_decrypt_field_headers(): @pytest.mark.asyncio -async def test_decrypt_field_headers_async(): +async def test_restore_crypto_key_version_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DecryptRequest() + request = service.RestoreCryptoKeyVersionRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.DecryptResponse() + resources.CryptoKeyVersion() ) - await client.decrypt(request) + await client.restore_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11207,20 +11159,21 @@ async def test_decrypt_field_headers_async(): ) in kw["metadata"] -def test_decrypt_flattened(): +def test_restore_crypto_key_version_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse() + call.return_value = resources.CryptoKeyVersion() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.decrypt( + client.restore_crypto_key_version( name="name_value", - ciphertext=b"ciphertext_blob", ) # Establish that the underlying call was made with the expected @@ -11230,12 +11183,9 @@ def test_decrypt_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].ciphertext - mock_val = b"ciphertext_blob" - assert arg == mock_val -def test_decrypt_flattened_error(): +def test_restore_crypto_key_version_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11243,32 +11193,32 @@ def test_decrypt_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.decrypt( - service.DecryptRequest(), + client.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), name="name_value", - ciphertext=b"ciphertext_blob", ) @pytest.mark.asyncio -async def test_decrypt_flattened_async(): +async def test_restore_crypto_key_version_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + with mock.patch.object( + type(client.transport.restore_crypto_key_version), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.DecryptResponse() + call.return_value = resources.CryptoKeyVersion() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.DecryptResponse() + resources.CryptoKeyVersion() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.decrypt( + response = await client.restore_crypto_key_version( name="name_value", - ciphertext=b"ciphertext_blob", ) # Establish that the underlying call was made with the expected @@ -11278,13 +11228,10 @@ async def test_decrypt_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].ciphertext - mock_val = b"ciphertext_blob" - assert arg == mock_val @pytest.mark.asyncio -async def test_decrypt_flattened_error_async(): +async def test_restore_crypto_key_version_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11292,21 +11239,20 @@ async def test_decrypt_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.decrypt( - service.DecryptRequest(), + await client.restore_crypto_key_version( + service.RestoreCryptoKeyVersionRequest(), name="name_value", - ciphertext=b"ciphertext_blob", ) @pytest.mark.parametrize( "request_type", [ - service.RawEncryptRequest(), + service.EncryptRequest(), {}, ], ) -def test_raw_encrypt(request_type, transport: str = "grpc"): +def test_encrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11317,39 +11263,33 @@ def test_raw_encrypt(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.RawEncryptResponse( + call.return_value = service.EncryptResponse( + name="name_value", ciphertext=b"ciphertext_blob", - initialization_vector=b"initialization_vector_blob", - tag_length=1053, verified_plaintext_crc32c=True, verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - name="name_value", protection_level=resources.ProtectionLevel.SOFTWARE, ) - response = client.raw_encrypt(request) + response = client.encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.RawEncryptRequest() + request = service.EncryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.RawEncryptResponse) + assert isinstance(response, service.EncryptResponse) + assert response.name == "name_value" assert response.ciphertext == b"ciphertext_blob" - assert response.initialization_vector == b"initialization_vector_blob" - assert response.tag_length == 1053 assert response.verified_plaintext_crc32c is True assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - assert response.name == "name_value" assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_raw_encrypt_non_empty_request_with_auto_populated_field(): +def test_encrypt_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -11360,25 +11300,25 @@ def test_raw_encrypt_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.RawEncryptRequest( + request = service.EncryptRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.raw_encrypt(request=request) + client.encrypt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.RawEncryptRequest( + request_msg = service.EncryptRequest( name="name_value", ) assert args[0] == request_msg -def test_raw_encrypt_use_cached_wrapped_rpc(): +def test_encrypt_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: @@ -11392,21 +11332,21 @@ def test_raw_encrypt_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.raw_encrypt in client._transport._wrapped_methods + assert client._transport.encrypt 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.raw_encrypt] = mock_rpc + client._transport._wrapped_methods[client._transport.encrypt] = mock_rpc request = {} - client.raw_encrypt(request) + client.encrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.raw_encrypt(request) + client.encrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11414,9 +11354,7 @@ def test_raw_encrypt_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_raw_encrypt_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_encrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -11431,7 +11369,7 @@ async def test_raw_encrypt_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.raw_encrypt + client._client._transport.encrypt in client._client._transport._wrapped_methods ) @@ -11439,16 +11377,16 @@ async def test_raw_encrypt_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.raw_encrypt + client._client._transport.encrypt ] = mock_rpc request = {} - await client.raw_encrypt(request) + await client.encrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.raw_encrypt(request) + await client.encrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11459,11 +11397,11 @@ async def test_raw_encrypt_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.RawEncryptRequest(), + service.EncryptRequest(), {}, ], ) -async def test_raw_encrypt_async(request_type, transport: str = "grpc_asyncio"): +async def test_encrypt_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11474,55 +11412,49 @@ async def test_raw_encrypt_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.RawEncryptResponse( + service.EncryptResponse( + name="name_value", ciphertext=b"ciphertext_blob", - initialization_vector=b"initialization_vector_blob", - tag_length=1053, verified_plaintext_crc32c=True, verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, - name="name_value", protection_level=resources.ProtectionLevel.SOFTWARE, ) ) - response = await client.raw_encrypt(request) + response = await client.encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.RawEncryptRequest() + request = service.EncryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.RawEncryptResponse) + assert isinstance(response, service.EncryptResponse) + assert response.name == "name_value" assert response.ciphertext == b"ciphertext_blob" - assert response.initialization_vector == b"initialization_vector_blob" - assert response.tag_length == 1053 assert response.verified_plaintext_crc32c is True assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True - assert response.name == "name_value" assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_raw_encrypt_field_headers(): +def test_encrypt_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RawEncryptRequest() + request = service.EncryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: - call.return_value = service.RawEncryptResponse() - client.raw_encrypt(request) + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + call.return_value = service.EncryptResponse() + client.encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11538,23 +11470,23 @@ def test_raw_encrypt_field_headers(): @pytest.mark.asyncio -async def test_raw_encrypt_field_headers_async(): +async def test_encrypt_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RawEncryptRequest() + request = service.EncryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.RawEncryptResponse() + service.EncryptResponse() ) - await client.raw_encrypt(request) + await client.encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11569,14 +11501,106 @@ async def test_raw_encrypt_field_headers_async(): ) in kw["metadata"] +def test_encrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.encrypt( + name="name_value", + plaintext=b"plaintext_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].plaintext + mock_val = b"plaintext_blob" + assert arg == mock_val + + +def test_encrypt_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.encrypt( + service.EncryptRequest(), + name="name_value", + plaintext=b"plaintext_blob", + ) + + +@pytest.mark.asyncio +async def test_encrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.encrypt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.EncryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.EncryptResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.encrypt( + name="name_value", + plaintext=b"plaintext_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].plaintext + mock_val = b"plaintext_blob" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_encrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.encrypt( + service.EncryptRequest(), + name="name_value", + plaintext=b"plaintext_blob", + ) + + @pytest.mark.parametrize( "request_type", [ - service.RawDecryptRequest(), + service.DecryptRequest(), {}, ], ) -def test_raw_decrypt(request_type, transport: str = "grpc"): +def test_decrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11587,33 +11611,29 @@ def test_raw_decrypt(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.RawDecryptResponse( + call.return_value = service.DecryptResponse( plaintext=b"plaintext_blob", + used_primary=True, protection_level=resources.ProtectionLevel.SOFTWARE, - verified_ciphertext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, ) - response = client.raw_decrypt(request) + response = client.decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.RawDecryptRequest() + request = service.DecryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.RawDecryptResponse) + assert isinstance(response, service.DecryptResponse) assert response.plaintext == b"plaintext_blob" + assert response.used_primary is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.verified_ciphertext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True -def test_raw_decrypt_non_empty_request_with_auto_populated_field(): +def test_decrypt_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -11624,25 +11644,25 @@ def test_raw_decrypt_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.RawDecryptRequest( + request = service.DecryptRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.raw_decrypt(request=request) + client.decrypt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.RawDecryptRequest( + request_msg = service.DecryptRequest( name="name_value", ) assert args[0] == request_msg -def test_raw_decrypt_use_cached_wrapped_rpc(): +def test_decrypt_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: @@ -11656,21 +11676,21 @@ def test_raw_decrypt_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.raw_decrypt in client._transport._wrapped_methods + assert client._transport.decrypt 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.raw_decrypt] = mock_rpc + client._transport._wrapped_methods[client._transport.decrypt] = mock_rpc request = {} - client.raw_decrypt(request) + client.decrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.raw_decrypt(request) + client.decrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11678,9 +11698,7 @@ def test_raw_decrypt_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_raw_decrypt_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_decrypt_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -11695,7 +11713,7 @@ async def test_raw_decrypt_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.raw_decrypt + client._client._transport.decrypt in client._client._transport._wrapped_methods ) @@ -11703,16 +11721,16 @@ async def test_raw_decrypt_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.raw_decrypt + client._client._transport.decrypt ] = mock_rpc request = {} - await client.raw_decrypt(request) + await client.decrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.raw_decrypt(request) + await client.decrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11723,11 +11741,11 @@ async def test_raw_decrypt_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.RawDecryptRequest(), + service.DecryptRequest(), {}, ], ) -async def test_raw_decrypt_async(request_type, transport: str = "grpc_asyncio"): +async def test_decrypt_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11738,49 +11756,45 @@ async def test_raw_decrypt_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.RawDecryptResponse( + service.DecryptResponse( plaintext=b"plaintext_blob", + used_primary=True, protection_level=resources.ProtectionLevel.SOFTWARE, - verified_ciphertext_crc32c=True, - verified_additional_authenticated_data_crc32c=True, - verified_initialization_vector_crc32c=True, ) ) - response = await client.raw_decrypt(request) + response = await client.decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.RawDecryptRequest() + request = service.DecryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.RawDecryptResponse) + assert isinstance(response, service.DecryptResponse) assert response.plaintext == b"plaintext_blob" + assert response.used_primary is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert response.verified_ciphertext_crc32c is True - assert response.verified_additional_authenticated_data_crc32c is True - assert response.verified_initialization_vector_crc32c is True -def test_raw_decrypt_field_headers(): +def test_decrypt_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RawDecryptRequest() + request = service.DecryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: - call.return_value = service.RawDecryptResponse() - client.raw_decrypt(request) + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + call.return_value = service.DecryptResponse() + client.decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11796,23 +11810,23 @@ def test_raw_decrypt_field_headers(): @pytest.mark.asyncio -async def test_raw_decrypt_field_headers_async(): +async def test_decrypt_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RawDecryptRequest() + request = service.DecryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.RawDecryptResponse() + service.DecryptResponse() ) - await client.raw_decrypt(request) + await client.decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11827,14 +11841,106 @@ async def test_raw_decrypt_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - service.AsymmetricSignRequest(), +def test_decrypt_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.decrypt( + name="name_value", + ciphertext=b"ciphertext_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" + assert arg == mock_val + + +def test_decrypt_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.decrypt( + service.DecryptRequest(), + name="name_value", + ciphertext=b"ciphertext_blob", + ) + + +@pytest.mark.asyncio +async def test_decrypt_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decrypt), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecryptResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.DecryptResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.decrypt( + name="name_value", + ciphertext=b"ciphertext_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_decrypt_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.decrypt( + service.DecryptRequest(), + name="name_value", + ciphertext=b"ciphertext_blob", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.RawEncryptRequest(), {}, ], ) -def test_asymmetric_sign(request_type, transport: str = "grpc"): +def test_raw_encrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11845,33 +11951,39 @@ def test_asymmetric_sign(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse( - signature=b"signature_blob", - verified_digest_crc32c=True, + call.return_value = service.RawEncryptResponse( + ciphertext=b"ciphertext_blob", + initialization_vector=b"initialization_vector_blob", + tag_length=1053, + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, name="name_value", - verified_data_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) - response = client.asymmetric_sign(request) + response = client.raw_encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.AsymmetricSignRequest() + request = service.RawEncryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b"signature_blob" - assert response.verified_digest_crc32c is True + assert isinstance(response, service.RawEncryptResponse) + assert response.ciphertext == b"ciphertext_blob" + assert response.initialization_vector == b"initialization_vector_blob" + assert response.tag_length == 1053 + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True assert response.name == "name_value" - assert response.verified_data_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_asymmetric_sign_non_empty_request_with_auto_populated_field(): +def test_raw_encrypt_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -11882,25 +11994,25 @@ def test_asymmetric_sign_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.AsymmetricSignRequest( + request = service.RawEncryptRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.asymmetric_sign(request=request) + client.raw_encrypt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricSignRequest( + request_msg = service.RawEncryptRequest( name="name_value", ) assert args[0] == request_msg -def test_asymmetric_sign_use_cached_wrapped_rpc(): +def test_raw_encrypt_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: @@ -11914,21 +12026,21 @@ def test_asymmetric_sign_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.asymmetric_sign in client._transport._wrapped_methods + assert client._transport.raw_encrypt 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.asymmetric_sign] = mock_rpc + client._transport._wrapped_methods[client._transport.raw_encrypt] = mock_rpc request = {} - client.asymmetric_sign(request) + client.raw_encrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.asymmetric_sign(request) + client.raw_encrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11936,7 +12048,7 @@ def test_asymmetric_sign_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_asymmetric_sign_async_use_cached_wrapped_rpc( +async def test_raw_encrypt_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11953,7 +12065,7 @@ async def test_asymmetric_sign_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.asymmetric_sign + client._client._transport.raw_encrypt in client._client._transport._wrapped_methods ) @@ -11961,16 +12073,16 @@ async def test_asymmetric_sign_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.asymmetric_sign + client._client._transport.raw_encrypt ] = mock_rpc request = {} - await client.asymmetric_sign(request) + await client.raw_encrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.asymmetric_sign(request) + await client.raw_encrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11981,11 +12093,11 @@ async def test_asymmetric_sign_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.AsymmetricSignRequest(), + service.RawEncryptRequest(), {}, ], ) -async def test_asymmetric_sign_async(request_type, transport: str = "grpc_asyncio"): +async def test_raw_encrypt_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -11996,49 +12108,55 @@ async def test_asymmetric_sign_async(request_type, transport: str = "grpc_asynci request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.AsymmetricSignResponse( - signature=b"signature_blob", - verified_digest_crc32c=True, + service.RawEncryptResponse( + ciphertext=b"ciphertext_blob", + initialization_vector=b"initialization_vector_blob", + tag_length=1053, + verified_plaintext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, name="name_value", - verified_data_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) ) - response = await client.asymmetric_sign(request) + response = await client.raw_encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.AsymmetricSignRequest() + request = service.RawEncryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricSignResponse) - assert response.signature == b"signature_blob" - assert response.verified_digest_crc32c is True + assert isinstance(response, service.RawEncryptResponse) + assert response.ciphertext == b"ciphertext_blob" + assert response.initialization_vector == b"initialization_vector_blob" + assert response.tag_length == 1053 + assert response.verified_plaintext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True assert response.name == "name_value" - assert response.verified_data_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_asymmetric_sign_field_headers(): +def test_raw_encrypt_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.AsymmetricSignRequest() + request = service.RawEncryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: - call.return_value = service.AsymmetricSignResponse() - client.asymmetric_sign(request) + with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: + call.return_value = service.RawEncryptResponse() + client.raw_encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12054,23 +12172,23 @@ def test_asymmetric_sign_field_headers(): @pytest.mark.asyncio -async def test_asymmetric_sign_field_headers_async(): +async def test_raw_encrypt_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.AsymmetricSignRequest() + request = service.RawEncryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.raw_encrypt), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.AsymmetricSignResponse() + service.RawEncryptResponse() ) - await client.asymmetric_sign(request) + await client.raw_encrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12085,141 +12203,51 @@ async def test_asymmetric_sign_field_headers_async(): ) in kw["metadata"] -def test_asymmetric_sign_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.RawDecryptRequest(), + {}, + ], +) +def test_raw_decrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.asymmetric_sign( - name="name_value", - digest=service.Digest(sha256=b"sha256_blob"), + call.return_value = service.RawDecryptResponse( + plaintext=b"plaintext_blob", + protection_level=resources.ProtectionLevel.SOFTWARE, + verified_ciphertext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, ) + response = client.raw_decrypt(request) - # Establish that the underlying call was made with the expected - # request object values. + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].digest - mock_val = service.Digest(sha256=b"sha256_blob") - assert arg == mock_val + request = service.RawDecryptRequest() + assert args[0] == request - -def test_asymmetric_sign_flattened_error(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.asymmetric_sign( - service.AsymmetricSignRequest(), - name="name_value", - digest=service.Digest(sha256=b"sha256_blob"), - ) - - -@pytest.mark.asyncio -async def test_asymmetric_sign_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricSignResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.AsymmetricSignResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.asymmetric_sign( - name="name_value", - digest=service.Digest(sha256=b"sha256_blob"), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].digest - mock_val = service.Digest(sha256=b"sha256_blob") - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_asymmetric_sign_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.asymmetric_sign( - service.AsymmetricSignRequest(), - name="name_value", - digest=service.Digest(sha256=b"sha256_blob"), - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.AsymmetricDecryptRequest(), - {}, - ], -) -def test_asymmetric_decrypt(request_type, transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse( - plaintext=b"plaintext_blob", - verified_ciphertext_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.asymmetric_decrypt(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.AsymmetricDecryptRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) - assert response.plaintext == b"plaintext_blob" - assert response.verified_ciphertext_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE + # Establish that the response is the type that we expect. + assert isinstance(response, service.RawDecryptResponse) + assert response.plaintext == b"plaintext_blob" + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.verified_ciphertext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True -def test_asymmetric_decrypt_non_empty_request_with_auto_populated_field(): +def test_raw_decrypt_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -12230,27 +12258,25 @@ def test_asymmetric_decrypt_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.AsymmetricDecryptRequest( + request = service.RawDecryptRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: + with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.asymmetric_decrypt(request=request) + client.raw_decrypt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.AsymmetricDecryptRequest( + request_msg = service.RawDecryptRequest( name="name_value", ) assert args[0] == request_msg -def test_asymmetric_decrypt_use_cached_wrapped_rpc(): +def test_raw_decrypt_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: @@ -12264,25 +12290,21 @@ def test_asymmetric_decrypt_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.asymmetric_decrypt in client._transport._wrapped_methods - ) + assert client._transport.raw_decrypt 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.asymmetric_decrypt] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.raw_decrypt] = mock_rpc request = {} - client.asymmetric_decrypt(request) + client.raw_decrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.asymmetric_decrypt(request) + client.raw_decrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12290,7 +12312,7 @@ def test_asymmetric_decrypt_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc( +async def test_raw_decrypt_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12307,7 +12329,7 @@ async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.asymmetric_decrypt + client._client._transport.raw_decrypt in client._client._transport._wrapped_methods ) @@ -12315,16 +12337,16 @@ async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.asymmetric_decrypt + client._client._transport.raw_decrypt ] = mock_rpc request = {} - await client.asymmetric_decrypt(request) + await client.raw_decrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.asymmetric_decrypt(request) + await client.raw_decrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12335,11 +12357,11 @@ async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.AsymmetricDecryptRequest(), + service.RawDecryptRequest(), {}, ], ) -async def test_asymmetric_decrypt_async(request_type, transport: str = "grpc_asyncio"): +async def test_raw_decrypt_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12350,49 +12372,49 @@ async def test_asymmetric_decrypt_async(request_type, transport: str = "grpc_asy request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: + with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.AsymmetricDecryptResponse( + service.RawDecryptResponse( plaintext=b"plaintext_blob", - verified_ciphertext_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, + verified_ciphertext_crc32c=True, + verified_additional_authenticated_data_crc32c=True, + verified_initialization_vector_crc32c=True, ) ) - response = await client.asymmetric_decrypt(request) + response = await client.raw_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.AsymmetricDecryptRequest() + request = service.RawDecryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.AsymmetricDecryptResponse) + assert isinstance(response, service.RawDecryptResponse) assert response.plaintext == b"plaintext_blob" - assert response.verified_ciphertext_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert response.verified_ciphertext_crc32c is True + assert response.verified_additional_authenticated_data_crc32c is True + assert response.verified_initialization_vector_crc32c is True -def test_asymmetric_decrypt_field_headers(): +def test_raw_decrypt_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.AsymmetricDecryptRequest() + request = service.RawDecryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: - call.return_value = service.AsymmetricDecryptResponse() - client.asymmetric_decrypt(request) + with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: + call.return_value = service.RawDecryptResponse() + client.raw_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12408,25 +12430,23 @@ def test_asymmetric_decrypt_field_headers(): @pytest.mark.asyncio -async def test_asymmetric_decrypt_field_headers_async(): +async def test_raw_decrypt_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.AsymmetricDecryptRequest() + request = service.RawDecryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: + with mock.patch.object(type(client.transport.raw_decrypt), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.AsymmetricDecryptResponse() + service.RawDecryptResponse() ) - await client.asymmetric_decrypt(request) + await client.raw_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12441,174 +12461,80 @@ async def test_asymmetric_decrypt_field_headers_async(): ) in kw["metadata"] -def test_asymmetric_decrypt_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.AsymmetricSignRequest(), + {}, + ], +) +def test_asymmetric_sign(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.asymmetric_decrypt( + call.return_value = service.AsymmetricSignResponse( + signature=b"signature_blob", + verified_digest_crc32c=True, name="name_value", - ciphertext=b"ciphertext_blob", + verified_data_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, ) + response = client.asymmetric_sign(request) - # Establish that the underlying call was made with the expected - # request object values. + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].ciphertext - mock_val = b"ciphertext_blob" - assert arg == mock_val + request = service.AsymmetricSignRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b"signature_blob" + assert response.verified_digest_crc32c is True + assert response.name == "name_value" + assert response.verified_data_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_asymmetric_decrypt_flattened_error(): +def test_asymmetric_sign_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name="name_value", - ciphertext=b"ciphertext_blob", - ) - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.asymmetric_decrypt), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = service.AsymmetricDecryptResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.AsymmetricDecryptResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.asymmetric_decrypt( - name="name_value", - ciphertext=b"ciphertext_blob", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" - assert arg == mock_val - arg = args[0].ciphertext - mock_val = b"ciphertext_blob" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_asymmetric_decrypt_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.asymmetric_decrypt( - service.AsymmetricDecryptRequest(), - name="name_value", - ciphertext=b"ciphertext_blob", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.MacSignRequest(), - {}, - ], -) -def test_mac_sign(request_type, transport: str = "grpc"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse( - name="name_value", - mac=b"mac_blob", - verified_data_crc32c=True, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) - response = client.mac_sign(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.MacSignRequest() - assert args[0] == request - - # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) - assert response.name == "name_value" - assert response.mac == b"mac_blob" - assert response.verified_data_crc32c is True - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - - -def test_mac_sign_non_empty_request_with_auto_populated_field(): - # This test is a coverage failsafe to make sure that UUID4 fields are - # automatically populated, according to AIP-4235, with non-empty requests. - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Populate all string fields in the request which are not UUID4 - # since we want to check that UUID4 are populated automatically - # if they meet the requirements of AIP 4235. - request = service.MacSignRequest( - name="name_value", - ) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.AsymmetricSignRequest( + name="name_value", + ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mac_sign(request=request) + client.asymmetric_sign(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.MacSignRequest( + request_msg = service.AsymmetricSignRequest( name="name_value", ) assert args[0] == request_msg -def test_mac_sign_use_cached_wrapped_rpc(): +def test_asymmetric_sign_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: @@ -12622,21 +12548,21 @@ def test_mac_sign_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.mac_sign in client._transport._wrapped_methods + assert client._transport.asymmetric_sign 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.mac_sign] = mock_rpc + client._transport._wrapped_methods[client._transport.asymmetric_sign] = mock_rpc request = {} - client.mac_sign(request) + client.asymmetric_sign(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.mac_sign(request) + client.asymmetric_sign(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12644,7 +12570,9 @@ def test_mac_sign_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_asymmetric_sign_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -12659,7 +12587,7 @@ async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn # Ensure method has been cached assert ( - client._client._transport.mac_sign + client._client._transport.asymmetric_sign in client._client._transport._wrapped_methods ) @@ -12667,16 +12595,16 @@ async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.mac_sign + client._client._transport.asymmetric_sign ] = mock_rpc request = {} - await client.mac_sign(request) + await client.asymmetric_sign(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.mac_sign(request) + await client.asymmetric_sign(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12687,11 +12615,11 @@ async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn @pytest.mark.parametrize( "request_type", [ - service.MacSignRequest(), + service.AsymmetricSignRequest(), {}, ], ) -async def test_mac_sign_async(request_type, transport: str = "grpc_asyncio"): +async def test_asymmetric_sign_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -12702,47 +12630,49 @@ async def test_mac_sign_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.MacSignResponse( + service.AsymmetricSignResponse( + signature=b"signature_blob", + verified_digest_crc32c=True, name="name_value", - mac=b"mac_blob", verified_data_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) ) - response = await client.mac_sign(request) + response = await client.asymmetric_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.MacSignRequest() + request = service.AsymmetricSignRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.MacSignResponse) + assert isinstance(response, service.AsymmetricSignResponse) + assert response.signature == b"signature_blob" + assert response.verified_digest_crc32c is True assert response.name == "name_value" - assert response.mac == b"mac_blob" assert response.verified_data_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_mac_sign_field_headers(): +def test_asymmetric_sign_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.MacSignRequest() + request = service.AsymmetricSignRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: - call.return_value = service.MacSignResponse() - client.mac_sign(request) + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: + call.return_value = service.AsymmetricSignResponse() + client.asymmetric_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12758,23 +12688,23 @@ def test_mac_sign_field_headers(): @pytest.mark.asyncio -async def test_mac_sign_field_headers_async(): +async def test_asymmetric_sign_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.MacSignRequest() + request = service.AsymmetricSignRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.MacSignResponse() + service.AsymmetricSignResponse() ) - await client.mac_sign(request) + await client.asymmetric_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12789,20 +12719,20 @@ async def test_mac_sign_field_headers_async(): ) in kw["metadata"] -def test_mac_sign_flattened(): +def test_asymmetric_sign_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse() + call.return_value = service.AsymmetricSignResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.mac_sign( + client.asymmetric_sign( name="name_value", - data=b"data_blob", + digest=service.Digest(sha256=b"sha256_blob"), ) # Establish that the underlying call was made with the expected @@ -12812,12 +12742,12 @@ def test_mac_sign_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].data - mock_val = b"data_blob" + arg = args[0].digest + mock_val = service.Digest(sha256=b"sha256_blob") assert arg == mock_val -def test_mac_sign_flattened_error(): +def test_asymmetric_sign_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12825,32 +12755,32 @@ def test_mac_sign_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.mac_sign( - service.MacSignRequest(), + client.asymmetric_sign( + service.AsymmetricSignRequest(), name="name_value", - data=b"data_blob", + digest=service.Digest(sha256=b"sha256_blob"), ) @pytest.mark.asyncio -async def test_mac_sign_flattened_async(): +async def test_asymmetric_sign_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + with mock.patch.object(type(client.transport.asymmetric_sign), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.MacSignResponse() + call.return_value = service.AsymmetricSignResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.MacSignResponse() + service.AsymmetricSignResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.mac_sign( + response = await client.asymmetric_sign( name="name_value", - data=b"data_blob", + digest=service.Digest(sha256=b"sha256_blob"), ) # Establish that the underlying call was made with the expected @@ -12860,13 +12790,13 @@ async def test_mac_sign_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].data - mock_val = b"data_blob" + arg = args[0].digest + mock_val = service.Digest(sha256=b"sha256_blob") assert arg == mock_val @pytest.mark.asyncio -async def test_mac_sign_flattened_error_async(): +async def test_asymmetric_sign_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12874,21 +12804,21 @@ async def test_mac_sign_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.mac_sign( - service.MacSignRequest(), + await client.asymmetric_sign( + service.AsymmetricSignRequest(), name="name_value", - data=b"data_blob", + digest=service.Digest(sha256=b"sha256_blob"), ) @pytest.mark.parametrize( "request_type", [ - service.MacVerifyRequest(), + service.AsymmetricDecryptRequest(), {}, ], ) -def test_mac_verify(request_type, transport: str = "grpc"): +def test_asymmetric_decrypt(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12899,35 +12829,31 @@ def test_mac_verify(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse( - name="name_value", - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, + call.return_value = service.AsymmetricDecryptResponse( + plaintext=b"plaintext_blob", + verified_ciphertext_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) - response = client.mac_verify(request) + response = client.asymmetric_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.MacVerifyRequest() + request = service.AsymmetricDecryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == "name_value" - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b"plaintext_blob" + assert response.verified_ciphertext_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_mac_verify_non_empty_request_with_auto_populated_field(): +def test_asymmetric_decrypt_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -12938,25 +12864,27 @@ def test_mac_verify_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.MacVerifyRequest( + request = service.AsymmetricDecryptRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.mac_verify(request=request) + client.asymmetric_decrypt(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.MacVerifyRequest( + request_msg = service.AsymmetricDecryptRequest( name="name_value", ) assert args[0] == request_msg -def test_mac_verify_use_cached_wrapped_rpc(): +def test_asymmetric_decrypt_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: @@ -12970,21 +12898,25 @@ def test_mac_verify_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.mac_verify in client._transport._wrapped_methods + assert ( + client._transport.asymmetric_decrypt 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.mac_verify] = mock_rpc + client._transport._wrapped_methods[client._transport.asymmetric_decrypt] = ( + mock_rpc + ) request = {} - client.mac_verify(request) + client.asymmetric_decrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.mac_verify(request) + client.asymmetric_decrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12992,7 +12924,9 @@ def test_mac_verify_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_asymmetric_decrypt_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -13007,7 +12941,7 @@ async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.mac_verify + client._client._transport.asymmetric_decrypt in client._client._transport._wrapped_methods ) @@ -13015,16 +12949,16 @@ async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_as mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.mac_verify + client._client._transport.asymmetric_decrypt ] = mock_rpc request = {} - await client.mac_verify(request) + await client.asymmetric_decrypt(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.mac_verify(request) + await client.asymmetric_decrypt(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13035,11 +12969,11 @@ async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.parametrize( "request_type", [ - service.MacVerifyRequest(), + service.AsymmetricDecryptRequest(), {}, ], ) -async def test_mac_verify_async(request_type, transport: str = "grpc_asyncio"): +async def test_asymmetric_decrypt_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13050,51 +12984,49 @@ async def test_mac_verify_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.MacVerifyResponse( - name="name_value", - success=True, - verified_data_crc32c=True, - verified_mac_crc32c=True, - verified_success_integrity=True, + service.AsymmetricDecryptResponse( + plaintext=b"plaintext_blob", + verified_ciphertext_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) ) - response = await client.mac_verify(request) + response = await client.asymmetric_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.MacVerifyRequest() + request = service.AsymmetricDecryptRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.MacVerifyResponse) - assert response.name == "name_value" - assert response.success is True - assert response.verified_data_crc32c is True - assert response.verified_mac_crc32c is True - assert response.verified_success_integrity is True + assert isinstance(response, service.AsymmetricDecryptResponse) + assert response.plaintext == b"plaintext_blob" + assert response.verified_ciphertext_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_mac_verify_field_headers(): +def test_asymmetric_decrypt_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.MacVerifyRequest() + request = service.AsymmetricDecryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: - call.return_value = service.MacVerifyResponse() - client.mac_verify(request) + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: + call.return_value = service.AsymmetricDecryptResponse() + client.asymmetric_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13110,23 +13042,25 @@ def test_mac_verify_field_headers(): @pytest.mark.asyncio -async def test_mac_verify_field_headers_async(): +async def test_asymmetric_decrypt_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.MacVerifyRequest() + request = service.AsymmetricDecryptRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.MacVerifyResponse() + service.AsymmetricDecryptResponse() ) - await client.mac_verify(request) + await client.asymmetric_decrypt(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13141,21 +13075,22 @@ async def test_mac_verify_field_headers_async(): ) in kw["metadata"] -def test_mac_verify_flattened(): +def test_asymmetric_decrypt_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse() + call.return_value = service.AsymmetricDecryptResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.mac_verify( + client.asymmetric_decrypt( name="name_value", - data=b"data_blob", - mac=b"mac_blob", + ciphertext=b"ciphertext_blob", ) # Establish that the underlying call was made with the expected @@ -13165,15 +13100,12 @@ def test_mac_verify_flattened(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].data - mock_val = b"data_blob" - assert arg == mock_val - arg = args[0].mac - mock_val = b"mac_blob" + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" assert arg == mock_val -def test_mac_verify_flattened_error(): +def test_asymmetric_decrypt_flattened_error(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -13181,34 +13113,34 @@ def test_mac_verify_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.mac_verify( - service.MacVerifyRequest(), + client.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), name="name_value", - data=b"data_blob", - mac=b"mac_blob", + ciphertext=b"ciphertext_blob", ) @pytest.mark.asyncio -async def test_mac_verify_flattened_async(): +async def test_asymmetric_decrypt_flattened_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + with mock.patch.object( + type(client.transport.asymmetric_decrypt), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.MacVerifyResponse() + call.return_value = service.AsymmetricDecryptResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.MacVerifyResponse() + service.AsymmetricDecryptResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.mac_verify( + response = await client.asymmetric_decrypt( name="name_value", - data=b"data_blob", - mac=b"mac_blob", + ciphertext=b"ciphertext_blob", ) # Establish that the underlying call was made with the expected @@ -13218,16 +13150,13 @@ async def test_mac_verify_flattened_async(): arg = args[0].name mock_val = "name_value" assert arg == mock_val - arg = args[0].data - mock_val = b"data_blob" - assert arg == mock_val - arg = args[0].mac - mock_val = b"mac_blob" + arg = args[0].ciphertext + mock_val = b"ciphertext_blob" assert arg == mock_val @pytest.mark.asyncio -async def test_mac_verify_flattened_error_async(): +async def test_asymmetric_decrypt_flattened_error_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) @@ -13235,22 +13164,21 @@ async def test_mac_verify_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.mac_verify( - service.MacVerifyRequest(), + await client.asymmetric_decrypt( + service.AsymmetricDecryptRequest(), name="name_value", - data=b"data_blob", - mac=b"mac_blob", + ciphertext=b"ciphertext_blob", ) @pytest.mark.parametrize( "request_type", [ - service.DecapsulateRequest(), + service.MacSignRequest(), {}, ], ) -def test_decapsulate(request_type, transport: str = "grpc"): +def test_mac_sign(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13261,33 +13189,31 @@ def test_decapsulate(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.DecapsulateResponse( + call.return_value = service.MacSignResponse( name="name_value", - shared_secret=b"shared_secret_blob", - shared_secret_crc32c=1979, - verified_ciphertext_crc32c=True, + mac=b"mac_blob", + verified_data_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) - response = client.decapsulate(request) + response = client.mac_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DecapsulateRequest() + request = service.MacSignRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.DecapsulateResponse) + assert isinstance(response, service.MacSignResponse) assert response.name == "name_value" - assert response.shared_secret == b"shared_secret_blob" - assert response.shared_secret_crc32c == 1979 - assert response.verified_ciphertext_crc32c is True + assert response.mac == b"mac_blob" + assert response.verified_data_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_decapsulate_non_empty_request_with_auto_populated_field(): +def test_mac_sign_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -13298,25 +13224,25 @@ def test_decapsulate_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DecapsulateRequest( + request = service.MacSignRequest( name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.decapsulate(request=request) + client.mac_sign(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.DecapsulateRequest( + request_msg = service.MacSignRequest( name="name_value", ) assert args[0] == request_msg -def test_decapsulate_use_cached_wrapped_rpc(): +def test_mac_sign_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: @@ -13330,21 +13256,21 @@ def test_decapsulate_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.decapsulate in client._transport._wrapped_methods + assert client._transport.mac_sign 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.decapsulate] = mock_rpc + client._transport._wrapped_methods[client._transport.mac_sign] = mock_rpc request = {} - client.decapsulate(request) + client.mac_sign(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.decapsulate(request) + client.mac_sign(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13352,9 +13278,7 @@ def test_decapsulate_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_decapsulate_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_mac_sign_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -13369,7 +13293,7 @@ async def test_decapsulate_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.decapsulate + client._client._transport.mac_sign in client._client._transport._wrapped_methods ) @@ -13377,16 +13301,16 @@ async def test_decapsulate_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.decapsulate + client._client._transport.mac_sign ] = mock_rpc request = {} - await client.decapsulate(request) + await client.mac_sign(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.decapsulate(request) + await client.mac_sign(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13397,11 +13321,11 @@ async def test_decapsulate_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.DecapsulateRequest(), + service.MacSignRequest(), {}, ], ) -async def test_decapsulate_async(request_type, transport: str = "grpc_asyncio"): +async def test_mac_sign_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13412,49 +13336,47 @@ async def test_decapsulate_async(request_type, transport: str = "grpc_asyncio"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.DecapsulateResponse( + service.MacSignResponse( name="name_value", - shared_secret=b"shared_secret_blob", - shared_secret_crc32c=1979, - verified_ciphertext_crc32c=True, + mac=b"mac_blob", + verified_data_crc32c=True, protection_level=resources.ProtectionLevel.SOFTWARE, ) ) - response = await client.decapsulate(request) + response = await client.mac_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DecapsulateRequest() + request = service.MacSignRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.DecapsulateResponse) + assert isinstance(response, service.MacSignResponse) assert response.name == "name_value" - assert response.shared_secret == b"shared_secret_blob" - assert response.shared_secret_crc32c == 1979 - assert response.verified_ciphertext_crc32c is True + assert response.mac == b"mac_blob" + assert response.verified_data_crc32c is True assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_decapsulate_field_headers(): +def test_mac_sign_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DecapsulateRequest() + request = service.MacSignRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: - call.return_value = service.DecapsulateResponse() - client.decapsulate(request) + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + call.return_value = service.MacSignResponse() + client.mac_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13470,23 +13392,23 @@ def test_decapsulate_field_headers(): @pytest.mark.asyncio -async def test_decapsulate_field_headers_async(): +async def test_mac_sign_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DecapsulateRequest() + request = service.MacSignRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.DecapsulateResponse() + service.MacSignResponse() ) - await client.decapsulate(request) + await client.mac_sign(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13501,14 +13423,106 @@ async def test_decapsulate_field_headers_async(): ) in kw["metadata"] -@pytest.mark.parametrize( - "request_type", - [ - service.GenerateRandomBytesRequest(), - {}, - ], -) -def test_generate_random_bytes(request_type, transport: str = "grpc"): +def test_mac_sign_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mac_sign( + name="name_value", + data=b"data_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val + + +def test_mac_sign_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mac_sign( + service.MacSignRequest(), + name="name_value", + data=b"data_blob", + ) + + +@pytest.mark.asyncio +async def test_mac_sign_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.mac_sign), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacSignResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.MacSignResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mac_sign( + name="name_value", + data=b"data_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_mac_sign_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mac_sign( + service.MacSignRequest(), + name="name_value", + data=b"data_blob", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.MacVerifyRequest(), + {}, + ], +) +def test_mac_verify(request_type, transport: str = "grpc"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13519,27 +13533,35 @@ def test_generate_random_bytes(request_type, transport: str = "grpc"): request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse( - data=b"data_blob", + call.return_value = service.MacVerifyResponse( + name="name_value", + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, ) - response = client.generate_random_bytes(request) + response = client.mac_verify(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GenerateRandomBytesRequest() + request = service.MacVerifyRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b"data_blob" + assert isinstance(response, service.MacVerifyResponse) + assert response.name == "name_value" + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_generate_random_bytes_non_empty_request_with_auto_populated_field(): +def test_mac_verify_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = KeyManagementServiceClient( @@ -13550,27 +13572,25 @@ def test_generate_random_bytes_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GenerateRandomBytesRequest( - location="location_value", + request = service.MacVerifyRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.generate_random_bytes(request=request) + client.mac_verify(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.GenerateRandomBytesRequest( - location="location_value", + request_msg = service.MacVerifyRequest( + name="name_value", ) assert args[0] == request_msg -def test_generate_random_bytes_use_cached_wrapped_rpc(): +def test_mac_verify_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: @@ -13584,26 +13604,21 @@ def test_generate_random_bytes_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.generate_random_bytes - in client._transport._wrapped_methods - ) + assert client._transport.mac_verify 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.generate_random_bytes] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.mac_verify] = mock_rpc request = {} - client.generate_random_bytes(request) + client.mac_verify(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_random_bytes(request) + client.mac_verify(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13611,9 +13626,7 @@ def test_generate_random_bytes_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_generate_random_bytes_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_mac_verify_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -13628,7 +13641,7 @@ async def test_generate_random_bytes_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.generate_random_bytes + client._client._transport.mac_verify in client._client._transport._wrapped_methods ) @@ -13636,16 +13649,16 @@ async def test_generate_random_bytes_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.generate_random_bytes + client._client._transport.mac_verify ] = mock_rpc request = {} - await client.generate_random_bytes(request) + await client.mac_verify(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.generate_random_bytes(request) + await client.mac_verify(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -13656,13 +13669,11 @@ async def test_generate_random_bytes_async_use_cached_wrapped_rpc( @pytest.mark.parametrize( "request_type", [ - service.GenerateRandomBytesRequest(), + service.MacVerifyRequest(), {}, ], ) -async def test_generate_random_bytes_async( - request_type, transport: str = "grpc_asyncio" -): +async def test_mac_verify_async(request_type, transport: str = "grpc_asyncio"): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), transport=transport, @@ -13673,45 +13684,51 @@ async def test_generate_random_bytes_async( request = request_type # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateRandomBytesResponse( - data=b"data_blob", + service.MacVerifyResponse( + name="name_value", + success=True, + verified_data_crc32c=True, + verified_mac_crc32c=True, + verified_success_integrity=True, + protection_level=resources.ProtectionLevel.SOFTWARE, ) ) - response = await client.generate_random_bytes(request) + response = await client.mac_verify(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GenerateRandomBytesRequest() + request = service.MacVerifyRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateRandomBytesResponse) - assert response.data == b"data_blob" + assert isinstance(response, service.MacVerifyResponse) + assert response.name == "name_value" + assert response.success is True + assert response.verified_data_crc32c is True + assert response.verified_mac_crc32c is True + assert response.verified_success_integrity is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE -def test_generate_random_bytes_field_headers(): +def test_mac_verify_field_headers(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GenerateRandomBytesRequest() + request = service.MacVerifyRequest() - request.location = "location_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: - call.return_value = service.GenerateRandomBytesResponse() - client.generate_random_bytes(request) + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + call.return_value = service.MacVerifyResponse() + client.mac_verify(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -13722,30 +13739,28 @@ def test_generate_random_bytes_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "location=location_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_generate_random_bytes_field_headers_async(): +async def test_mac_verify_field_headers_async(): client = KeyManagementServiceAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GenerateRandomBytesRequest() + request = service.MacVerifyRequest() - request.location = "location_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateRandomBytesResponse() + service.MacVerifyResponse() ) - await client.generate_random_bytes(request) + await client.mac_verify(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -13756,117 +13771,1263 @@ async def test_generate_random_bytes_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "location=location_value", + "name=name_value", ) in kw["metadata"] -def test_generate_random_bytes_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - ) +def test_mac_verify_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.mac_verify( + name="name_value", + data=b"data_blob", + mac=b"mac_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val + arg = args[0].mac + mock_val = b"mac_blob" + assert arg == mock_val + + +def test_mac_verify_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.mac_verify( + service.MacVerifyRequest(), + name="name_value", + data=b"data_blob", + mac=b"mac_blob", + ) + + +@pytest.mark.asyncio +async def test_mac_verify_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.mac_verify), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.MacVerifyResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.MacVerifyResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.mac_verify( + name="name_value", + data=b"data_blob", + mac=b"mac_blob", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].data + mock_val = b"data_blob" + assert arg == mock_val + arg = args[0].mac + mock_val = b"mac_blob" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_mac_verify_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.mac_verify( + service.MacVerifyRequest(), + name="name_value", + data=b"data_blob", + mac=b"mac_blob", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DecapsulateRequest(), + {}, + ], +) +def test_decapsulate(request_type, transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.DecapsulateResponse( + name="name_value", + shared_secret=b"shared_secret_blob", + shared_secret_crc32c=1979, + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + response = client.decapsulate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.DecapsulateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecapsulateResponse) + assert response.name == "name_value" + assert response.shared_secret == b"shared_secret_blob" + assert response.shared_secret_crc32c == 1979 + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_decapsulate_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.DecapsulateRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.decapsulate(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DecapsulateRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_decapsulate_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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.decapsulate 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.decapsulate] = mock_rpc + request = {} + client.decapsulate(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.decapsulate(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_decapsulate_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.decapsulate + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.decapsulate + ] = mock_rpc + + request = {} + await client.decapsulate(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.decapsulate(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.DecapsulateRequest(), + {}, + ], +) +async def test_decapsulate_async(request_type, transport: str = "grpc_asyncio"): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.DecapsulateResponse( + name="name_value", + shared_secret=b"shared_secret_blob", + shared_secret_crc32c=1979, + verified_ciphertext_crc32c=True, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + ) + response = await client.decapsulate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.DecapsulateRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.DecapsulateResponse) + assert response.name == "name_value" + assert response.shared_secret == b"shared_secret_blob" + assert response.shared_secret_crc32c == 1979 + assert response.verified_ciphertext_crc32c is True + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + + +def test_decapsulate_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DecapsulateRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + call.return_value = service.DecapsulateResponse() + client.decapsulate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_decapsulate_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DecapsulateRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.decapsulate), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.DecapsulateResponse() + ) + await client.decapsulate(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + service.GenerateRandomBytesRequest(), + {}, + ], +) +def test_generate_random_bytes(request_type, transport: str = "grpc"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse( + data=b"data_blob", + ) + response = client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GenerateRandomBytesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b"data_blob" + + +def test_generate_random_bytes_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GenerateRandomBytesRequest( + location="location_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.generate_random_bytes(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.GenerateRandomBytesRequest( + location="location_value", + ) + assert args[0] == request_msg + + +def test_generate_random_bytes_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 = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.generate_random_bytes + 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.generate_random_bytes] = ( + mock_rpc + ) + request = {} + client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.generate_random_bytes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_generate_random_bytes_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.generate_random_bytes + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.generate_random_bytes + ] = mock_rpc + + request = {} + await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.generate_random_bytes(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.GenerateRandomBytesRequest(), + {}, + ], +) +async def test_generate_random_bytes_async( + request_type, transport: str = "grpc_asyncio" +): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateRandomBytesResponse( + data=b"data_blob", + ) + ) + response = await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GenerateRandomBytesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, service.GenerateRandomBytesResponse) + assert response.data == b"data_blob" + + +def test_generate_random_bytes_field_headers(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateRandomBytesRequest() + + request.location = "location_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + call.return_value = service.GenerateRandomBytesResponse() + client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "location=location_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_generate_random_bytes_field_headers_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GenerateRandomBytesRequest() + + request.location = "location_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateRandomBytesResponse() + ) + await client.generate_random_bytes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "location=location_value", + ) in kw["metadata"] + + +def test_generate_random_bytes_flattened(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.generate_random_bytes( + location="location_value", + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].location + mock_val = "location_value" + assert arg == mock_val + arg = args[0].length_bytes + mock_val = 1288 + assert arg == mock_val + arg = args[0].protection_level + mock_val = resources.ProtectionLevel.SOFTWARE + assert arg == mock_val + + +def test_generate_random_bytes_flattened_error(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location="location_value", + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +@pytest.mark.asyncio +async def test_generate_random_bytes_flattened_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.generate_random_bytes), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.GenerateRandomBytesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.GenerateRandomBytesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.generate_random_bytes( + location="location_value", + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].location + mock_val = "location_value" + assert arg == mock_val + arg = args[0].length_bytes + mock_val = 1288 + assert arg == mock_val + arg = args[0].protection_level + mock_val = resources.ProtectionLevel.SOFTWARE + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_generate_random_bytes_flattened_error_async(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.generate_random_bytes( + service.GenerateRandomBytesRequest(), + location="location_value", + length_bytes=1288, + protection_level=resources.ProtectionLevel.SOFTWARE, + ) + + +def test_list_key_rings_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 = KeyManagementServiceClient( + 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_key_rings 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_key_rings] = mock_rpc + + request = {} + client.list_key_rings(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_key_rings(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_key_rings_rest_required_fields(request_type=service.ListKeyRingsRequest): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_key_rings._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_key_rings._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListKeyRingsResponse() + # 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 = service.ListKeyRingsResponse.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_key_rings(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_key_rings_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_key_rings._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_key_rings_rest_flattened(): + client = KeyManagementServiceClient( + 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 = service.ListKeyRingsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListKeyRingsResponse.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_key_rings(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/keyRings" % client.transport._host, + args[1], + ) + + +def test_list_key_rings_rest_flattened_error(transport: str = "rest"): + client = KeyManagementServiceClient( + 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_key_rings( + service.ListKeyRingsRequest(), + parent="parent_value", + ) + + +def test_list_key_rings_rest_pager(transport: str = "rest"): + client = KeyManagementServiceClient( + 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 = ( + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + resources.KeyRing(), + ], + next_page_token="abc", + ), + service.ListKeyRingsResponse( + key_rings=[], + next_page_token="def", + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + ], + next_page_token="ghi", + ), + service.ListKeyRingsResponse( + key_rings=[ + resources.KeyRing(), + resources.KeyRing(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListKeyRingsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_key_rings(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.KeyRing) for i in results) + + pages = list(client.list_key_rings(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_crypto_keys_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 = KeyManagementServiceClient( + 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_crypto_keys 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_crypto_keys] = ( + mock_rpc + ) + + request = {} + client.list_crypto_keys(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_crypto_keys(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_crypto_keys_rest_required_fields( + request_type=service.ListCryptoKeysRequest, +): + transport_class = transports.KeyManagementServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_crypto_keys._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_crypto_keys._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + "version_view", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListCryptoKeysResponse() + # 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 = service.ListCryptoKeysResponse.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_crypto_keys(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_crypto_keys_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_crypto_keys._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + "versionView", + ) + ) + & set(("parent",)) + ) + + +def test_list_crypto_keys_rest_flattened(): + client = KeyManagementServiceClient( + 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 = service.ListCryptoKeysResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ListCryptoKeysResponse.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"} - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.generate_random_bytes( - location="location_value", - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) + client.list_crypto_keys(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - arg = args[0].location - mock_val = "location_value" - assert arg == mock_val - arg = args[0].length_bytes - mock_val = 1288 - assert arg == mock_val - arg = args[0].protection_level - mock_val = resources.ProtectionLevel.SOFTWARE - assert arg == mock_val + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys" + % client.transport._host, + args[1], + ) -def test_generate_random_bytes_flattened_error(): +def test_list_crypto_keys_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( 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.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location="location_value", - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, + client.list_crypto_keys( + service.ListCryptoKeysRequest(), + parent="parent_value", ) -@pytest.mark.asyncio -async def test_generate_random_bytes_flattened_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), +def test_list_crypto_keys_rest_pager(transport: str = "rest"): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.generate_random_bytes), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = service.GenerateRandomBytesResponse() - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateRandomBytesResponse() - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.generate_random_bytes( - location="location_value", - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, + # 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 = ( + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + resources.CryptoKey(), + ], + next_page_token="abc", + ), + service.ListCryptoKeysResponse( + crypto_keys=[], + next_page_token="def", + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + ], + next_page_token="ghi", + ), + service.ListCryptoKeysResponse( + crypto_keys=[ + resources.CryptoKey(), + resources.CryptoKey(), + ], + ), ) + # Two responses for two calls + response = response + response - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - arg = args[0].location - mock_val = "location_value" - assert arg == mock_val - arg = args[0].length_bytes - mock_val = 1288 - assert arg == mock_val - arg = args[0].protection_level - mock_val = resources.ProtectionLevel.SOFTWARE - assert arg == mock_val + # Wrap the values into proper Response objs + response = tuple(service.ListCryptoKeysResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3" + } -@pytest.mark.asyncio -async def test_generate_random_bytes_flattened_error_async(): - client = KeyManagementServiceAsyncClient( - credentials=async_anonymous_credentials(), - ) + pager = client.list_crypto_keys(request=sample_request) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.generate_random_bytes( - service.GenerateRandomBytesRequest(), - location="location_value", - length_bytes=1288, - protection_level=resources.ProtectionLevel.SOFTWARE, - ) + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.CryptoKey) for i in results) -def test_list_key_rings_rest_use_cached_wrapped_rpc(): + pages = list(client.list_crypto_keys(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_list_crypto_key_versions_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: @@ -13880,29 +15041,36 @@ def test_list_key_rings_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_key_rings in client._transport._wrapped_methods + assert ( + client._transport.list_crypto_key_versions + 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_key_rings] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_crypto_key_versions + ] = mock_rpc request = {} - client.list_key_rings(request) + client.list_crypto_key_versions(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_key_rings(request) + client.list_crypto_key_versions(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_key_rings_rest_required_fields(request_type=service.ListKeyRingsRequest): +def test_list_crypto_key_versions_rest_required_fields( + request_type=service.ListCryptoKeyVersionsRequest, +): transport_class = transports.KeyManagementServiceRestTransport request_init = {} @@ -13917,7 +15085,7 @@ def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_key_rings._get_unset_required_fields(jsonified_request) + ).list_crypto_key_versions._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13926,7 +15094,7 @@ def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_key_rings._get_unset_required_fields(jsonified_request) + ).list_crypto_key_versions._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -13934,6 +15102,7 @@ def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRe "order_by", "page_size", "page_token", + "view", ) ) jsonified_request.update(unset_fields) @@ -13949,7 +15118,7 @@ def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListKeyRingsResponse() + return_value = service.ListCryptoKeyVersionsResponse() # 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 @@ -13970,26 +15139,26 @@ def test_list_key_rings_rest_required_fields(request_type=service.ListKeyRingsRe response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListKeyRingsResponse.pb(return_value) + return_value = service.ListCryptoKeyVersionsResponse.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_key_rings(request) + response = client.list_crypto_key_versions(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_key_rings_rest_unset_required_fields(): +def test_list_crypto_key_versions_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_key_rings._get_unset_required_fields({}) + unset_fields = transport.list_crypto_key_versions._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -13997,13 +15166,14 @@ def test_list_key_rings_rest_unset_required_fields(): "orderBy", "pageSize", "pageToken", + "view", ) ) & set(("parent",)) ) -def test_list_key_rings_rest_flattened(): +def test_list_crypto_key_versions_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14012,10 +15182,12 @@ def test_list_key_rings_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListKeyRingsResponse() + return_value = service.ListCryptoKeyVersionsResponse() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } # get truthy value for each flattened field mock_args = dict( @@ -14027,25 +15199,26 @@ def test_list_key_rings_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListKeyRingsResponse.pb(return_value) + return_value = service.ListCryptoKeyVersionsResponse.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_key_rings(**mock_args) + client.list_crypto_key_versions(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/keyRings" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" + % client.transport._host, args[1], ) -def test_list_key_rings_rest_flattened_error(transport: str = "rest"): +def test_list_crypto_key_versions_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14054,13 +15227,13 @@ def test_list_key_rings_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_key_rings( - service.ListKeyRingsRequest(), + client.list_crypto_key_versions( + service.ListCryptoKeyVersionsRequest(), parent="parent_value", ) -def test_list_key_rings_rest_pager(transport: str = "rest"): +def test_list_crypto_key_versions_rest_pager(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14072,28 +15245,28 @@ def test_list_key_rings_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), - resources.KeyRing(), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), ], next_page_token="abc", ), - service.ListKeyRingsResponse( - key_rings=[], + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[], next_page_token="def", ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), ], next_page_token="ghi", ), - service.ListKeyRingsResponse( - key_rings=[ - resources.KeyRing(), - resources.KeyRing(), + service.ListCryptoKeyVersionsResponse( + crypto_key_versions=[ + resources.CryptoKeyVersion(), + resources.CryptoKeyVersion(), ], ), ) @@ -14101,30 +15274,34 @@ def test_list_key_rings_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListKeyRingsResponse.to_json(x) for x in response) + response = tuple( + service.ListCryptoKeyVersionsResponse.to_json(x) for x in response + ) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } - pager = client.list_key_rings(request=sample_request) + pager = client.list_crypto_key_versions(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.KeyRing) for i in results) + assert all(isinstance(i, resources.CryptoKeyVersion) for i in results) - pages = list(client.list_key_rings(request=sample_request).pages) + pages = list(client.list_crypto_key_versions(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_list_crypto_keys_rest_use_cached_wrapped_rpc(): +def test_list_import_jobs_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: @@ -14138,32 +15315,32 @@ def test_list_crypto_keys_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_crypto_keys in client._transport._wrapped_methods + assert client._transport.list_import_jobs 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_crypto_keys] = ( + client._transport._wrapped_methods[client._transport.list_import_jobs] = ( mock_rpc ) request = {} - client.list_crypto_keys(request) + client.list_import_jobs(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_crypto_keys(request) + client.list_import_jobs(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_crypto_keys_rest_required_fields( - request_type=service.ListCryptoKeysRequest, +def test_list_import_jobs_rest_required_fields( + request_type=service.ListImportJobsRequest, ): transport_class = transports.KeyManagementServiceRestTransport @@ -14179,7 +15356,7 @@ def test_list_crypto_keys_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_crypto_keys._get_unset_required_fields(jsonified_request) + ).list_import_jobs._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14188,7 +15365,7 @@ def test_list_crypto_keys_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_crypto_keys._get_unset_required_fields(jsonified_request) + ).list_import_jobs._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( @@ -14196,7 +15373,6 @@ def test_list_crypto_keys_rest_required_fields( "order_by", "page_size", "page_token", - "version_view", ) ) jsonified_request.update(unset_fields) @@ -14212,7 +15388,7 @@ def test_list_crypto_keys_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeysResponse() + return_value = service.ListImportJobsResponse() # 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 @@ -14233,26 +15409,26 @@ def test_list_crypto_keys_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListCryptoKeysResponse.pb(return_value) + return_value = service.ListImportJobsResponse.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_crypto_keys(request) + response = client.list_import_jobs(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_crypto_keys_rest_unset_required_fields(): +def test_list_import_jobs_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_crypto_keys._get_unset_required_fields({}) + unset_fields = transport.list_import_jobs._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( @@ -14260,14 +15436,13 @@ def test_list_crypto_keys_rest_unset_required_fields(): "orderBy", "pageSize", "pageToken", - "versionView", ) ) & set(("parent",)) ) -def test_list_crypto_keys_rest_flattened(): +def test_list_import_jobs_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14276,7 +15451,7 @@ def test_list_crypto_keys_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeysResponse() + return_value = service.ListImportJobsResponse() # get arguments that satisfy an http rule for this method sample_request = { @@ -14293,26 +15468,26 @@ def test_list_crypto_keys_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListCryptoKeysResponse.pb(return_value) + return_value = service.ListImportJobsResponse.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_crypto_keys(**mock_args) + client.list_import_jobs(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys" + "%s/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs" % client.transport._host, args[1], ) -def test_list_crypto_keys_rest_flattened_error(transport: str = "rest"): +def test_list_import_jobs_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14321,13 +15496,13 @@ def test_list_crypto_keys_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_crypto_keys( - service.ListCryptoKeysRequest(), + client.list_import_jobs( + service.ListImportJobsRequest(), parent="parent_value", ) -def test_list_crypto_keys_rest_pager(transport: str = "rest"): +def test_list_import_jobs_rest_pager(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14339,28 +15514,28 @@ def test_list_crypto_keys_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), - resources.CryptoKey(), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), + resources.ImportJob(), ], next_page_token="abc", ), - service.ListCryptoKeysResponse( - crypto_keys=[], + service.ListImportJobsResponse( + import_jobs=[], next_page_token="def", ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), ], next_page_token="ghi", ), - service.ListCryptoKeysResponse( - crypto_keys=[ - resources.CryptoKey(), - resources.CryptoKey(), + service.ListImportJobsResponse( + import_jobs=[ + resources.ImportJob(), + resources.ImportJob(), ], ), ) @@ -14368,7 +15543,7 @@ def test_list_crypto_keys_rest_pager(transport: str = "rest"): response = response + response # Wrap the values into proper Response objs - response = tuple(service.ListCryptoKeysResponse.to_json(x) for x in response) + response = tuple(service.ListImportJobsResponse.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") @@ -14379,21 +15554,21 @@ def test_list_crypto_keys_rest_pager(transport: str = "rest"): "parent": "projects/sample1/locations/sample2/keyRings/sample3" } - pager = client.list_crypto_keys(request=sample_request) + pager = client.list_import_jobs(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKey) for i in results) + assert all(isinstance(i, resources.ImportJob) for i in results) - pages = list(client.list_crypto_keys(request=sample_request).pages) + pages = list(client.list_import_jobs(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_list_crypto_key_versions_rest_use_cached_wrapped_rpc(): +def test_list_retired_resources_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: @@ -14408,7 +15583,7 @@ def test_list_crypto_key_versions_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_crypto_key_versions + client._transport.list_retired_resources in client._transport._wrapped_methods ) @@ -14417,25 +15592,25 @@ def test_list_crypto_key_versions_rest_use_cached_wrapped_rpc(): mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.list_crypto_key_versions - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_retired_resources] = ( + mock_rpc + ) request = {} - client.list_crypto_key_versions(request) + client.list_retired_resources(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_crypto_key_versions(request) + client.list_retired_resources(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_crypto_key_versions_rest_required_fields( - request_type=service.ListCryptoKeyVersionsRequest, +def test_list_retired_resources_rest_required_fields( + request_type=service.ListRetiredResourcesRequest, ): transport_class = transports.KeyManagementServiceRestTransport @@ -14451,7 +15626,7 @@ def test_list_crypto_key_versions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_crypto_key_versions._get_unset_required_fields(jsonified_request) + ).list_retired_resources._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14460,15 +15635,12 @@ def test_list_crypto_key_versions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_crypto_key_versions._get_unset_required_fields(jsonified_request) + ).list_retired_resources._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "order_by", "page_size", "page_token", - "view", ) ) jsonified_request.update(unset_fields) @@ -14484,7 +15656,7 @@ def test_list_crypto_key_versions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeyVersionsResponse() + return_value = service.ListRetiredResourcesResponse() # 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 @@ -14505,41 +15677,38 @@ def test_list_crypto_key_versions_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListCryptoKeyVersionsResponse.pb(return_value) + return_value = service.ListRetiredResourcesResponse.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_crypto_key_versions(request) + response = client.list_retired_resources(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_crypto_key_versions_rest_unset_required_fields(): +def test_list_retired_resources_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_crypto_key_versions._get_unset_required_fields({}) + unset_fields = transport.list_retired_resources._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", "pageSize", "pageToken", - "view", ) ) & set(("parent",)) ) -def test_list_crypto_key_versions_rest_flattened(): +def test_list_retired_resources_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14548,12 +15717,10 @@ def test_list_crypto_key_versions_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListCryptoKeyVersionsResponse() + return_value = service.ListRetiredResourcesResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( @@ -14565,26 +15732,26 @@ def test_list_crypto_key_versions_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListCryptoKeyVersionsResponse.pb(return_value) + return_value = service.ListRetiredResourcesResponse.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_crypto_key_versions(**mock_args) + client.list_retired_resources(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" + "%s/v1/{parent=projects/*/locations/*}/retiredResources" % client.transport._host, args[1], ) -def test_list_crypto_key_versions_rest_flattened_error(transport: str = "rest"): +def test_list_retired_resources_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14593,13 +15760,13 @@ def test_list_crypto_key_versions_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_crypto_key_versions( - service.ListCryptoKeyVersionsRequest(), + client.list_retired_resources( + service.ListRetiredResourcesRequest(), parent="parent_value", ) -def test_list_crypto_key_versions_rest_pager(transport: str = "rest"): +def test_list_retired_resources_rest_pager(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14611,28 +15778,28 @@ def test_list_crypto_key_versions_rest_pager(transport: str = "rest"): # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), + service.ListRetiredResourcesResponse( + retired_resources=[ + resources.RetiredResource(), + resources.RetiredResource(), + resources.RetiredResource(), ], next_page_token="abc", ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[], + service.ListRetiredResourcesResponse( + retired_resources=[], next_page_token="def", ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), + service.ListRetiredResourcesResponse( + retired_resources=[ + resources.RetiredResource(), ], next_page_token="ghi", ), - service.ListCryptoKeyVersionsResponse( - crypto_key_versions=[ - resources.CryptoKeyVersion(), - resources.CryptoKeyVersion(), + service.ListRetiredResourcesResponse( + retired_resources=[ + resources.RetiredResource(), + resources.RetiredResource(), ], ), ) @@ -14641,7 +15808,7 @@ def test_list_crypto_key_versions_rest_pager(transport: str = "rest"): # Wrap the values into proper Response objs response = tuple( - service.ListCryptoKeyVersionsResponse.to_json(x) for x in response + service.ListRetiredResourcesResponse.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): @@ -14649,25 +15816,23 @@ def test_list_crypto_key_versions_rest_pager(transport: str = "rest"): return_val.status_code = 200 req.side_effect = return_values - sample_request = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} - pager = client.list_crypto_key_versions(request=sample_request) + pager = client.list_retired_resources(request=sample_request) assert pager.next_page_token == "abc" assert str(pager).startswith(f"{pager.__class__.__name__}<") results = list(pager) assert len(results) == 6 - assert all(isinstance(i, resources.CryptoKeyVersion) for i in results) + assert all(isinstance(i, resources.RetiredResource) for i in results) - pages = list(client.list_crypto_key_versions(request=sample_request).pages) + pages = list(client.list_retired_resources(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token -def test_list_import_jobs_rest_use_cached_wrapped_rpc(): +def test_get_key_ring_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: @@ -14681,37 +15846,33 @@ def test_list_import_jobs_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_import_jobs in client._transport._wrapped_methods + assert client._transport.get_key_ring 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_import_jobs] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_key_ring] = mock_rpc request = {} - client.list_import_jobs(request) + client.get_key_ring(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_import_jobs(request) + client.get_key_ring(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_import_jobs_rest_required_fields( - request_type=service.ListImportJobsRequest, -): +def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingRequest): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14722,30 +15883,21 @@ def test_list_import_jobs_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_import_jobs._get_unset_required_fields(jsonified_request) + ).get_key_ring._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_import_jobs._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", - ) - ) + ).get_key_ring._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14754,7 +15906,7 @@ def test_list_import_jobs_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListImportJobsResponse() + return_value = resources.KeyRing() # 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 @@ -14775,40 +15927,30 @@ def test_list_import_jobs_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListImportJobsResponse.pb(return_value) + return_value = resources.KeyRing.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_import_jobs(request) + response = client.get_key_ring(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_import_jobs_rest_unset_required_fields(): +def test_get_key_ring_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_import_jobs._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_key_ring._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_import_jobs_rest_flattened(): +def test_get_key_ring_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14817,16 +15959,14 @@ def test_list_import_jobs_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListImportJobsResponse() - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3" - } + return_value = resources.KeyRing() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/keyRings/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -14834,26 +15974,25 @@ def test_list_import_jobs_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListImportJobsResponse.pb(return_value) + return_value = resources.KeyRing.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_import_jobs(**mock_args) + client.get_key_ring(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/keyRings/*}/importJobs" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/keyRings/*}" % client.transport._host, args[1], ) -def test_list_import_jobs_rest_flattened_error(transport: str = "rest"): +def test_get_key_ring_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14862,79 +16001,13 @@ def test_list_import_jobs_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_import_jobs( - service.ListImportJobsRequest(), - parent="parent_value", - ) - - -def test_list_import_jobs_rest_pager(transport: str = "rest"): - client = KeyManagementServiceClient( - 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 = ( - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - resources.ImportJob(), - ], - next_page_token="abc", - ), - service.ListImportJobsResponse( - import_jobs=[], - next_page_token="def", - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - ], - next_page_token="ghi", - ), - service.ListImportJobsResponse( - import_jobs=[ - resources.ImportJob(), - resources.ImportJob(), - ], - ), + client.get_key_ring( + service.GetKeyRingRequest(), + name="name_value", ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListImportJobsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3" - } - - pager = client.list_import_jobs(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.ImportJob) for i in results) - - pages = list(client.list_import_jobs(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_list_retired_resources_rest_use_cached_wrapped_rpc(): +def test_get_crypto_key_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: @@ -14948,40 +16021,33 @@ def test_list_retired_resources_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.list_retired_resources - in client._transport._wrapped_methods - ) + assert client._transport.get_crypto_key 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_retired_resources] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_crypto_key] = mock_rpc request = {} - client.list_retired_resources(request) + client.get_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_retired_resources(request) + client.get_crypto_key(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_retired_resources_rest_required_fields( - request_type=service.ListRetiredResourcesRequest, -): +def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRequest): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14992,28 +16058,21 @@ def test_list_retired_resources_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_retired_resources._get_unset_required_fields(jsonified_request) + ).get_crypto_key._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_retired_resources._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + ).get_crypto_key._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15022,7 +16081,7 @@ def test_list_retired_resources_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListRetiredResourcesResponse() + return_value = resources.CryptoKey() # 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 @@ -15043,38 +16102,30 @@ def test_list_retired_resources_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRetiredResourcesResponse.pb(return_value) + return_value = resources.CryptoKey.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_retired_resources(request) + response = client.get_crypto_key(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_list_retired_resources_rest_unset_required_fields(): +def test_get_crypto_key_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_retired_resources._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_list_retired_resources_rest_flattened(): +def test_get_crypto_key_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15083,14 +16134,16 @@ def test_list_retired_resources_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListRetiredResourcesResponse() + return_value = resources.CryptoKey() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", + name="name_value", ) mock_args.update(sample_request) @@ -15098,26 +16151,26 @@ def test_list_retired_resources_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListRetiredResourcesResponse.pb(return_value) + return_value = resources.CryptoKey.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_retired_resources(**mock_args) + client.get_crypto_key(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/retiredResources" + "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" % client.transport._host, args[1], ) -def test_list_retired_resources_rest_flattened_error(transport: str = "rest"): +def test_get_crypto_key_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15126,79 +16179,13 @@ def test_list_retired_resources_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_retired_resources( - service.ListRetiredResourcesRequest(), - parent="parent_value", - ) - - -def test_list_retired_resources_rest_pager(transport: str = "rest"): - client = KeyManagementServiceClient( - 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 = ( - service.ListRetiredResourcesResponse( - retired_resources=[ - resources.RetiredResource(), - resources.RetiredResource(), - resources.RetiredResource(), - ], - next_page_token="abc", - ), - service.ListRetiredResourcesResponse( - retired_resources=[], - next_page_token="def", - ), - service.ListRetiredResourcesResponse( - retired_resources=[ - resources.RetiredResource(), - ], - next_page_token="ghi", - ), - service.ListRetiredResourcesResponse( - retired_resources=[ - resources.RetiredResource(), - resources.RetiredResource(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - service.ListRetiredResourcesResponse.to_json(x) for x in response + client.get_crypto_key( + service.GetCryptoKeyRequest(), + name="name_value", ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_retired_resources(request=sample_request) - - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.RetiredResource) for i in results) - - pages = list(client.list_retired_resources(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token -def test_get_key_ring_rest_use_cached_wrapped_rpc(): +def test_get_crypto_key_version_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: @@ -15212,29 +16199,36 @@ def test_get_key_ring_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_key_ring in client._transport._wrapped_methods + assert ( + client._transport.get_crypto_key_version + 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_key_ring] = mock_rpc + client._transport._wrapped_methods[client._transport.get_crypto_key_version] = ( + mock_rpc + ) request = {} - client.get_key_ring(request) + client.get_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_key_ring(request) + client.get_crypto_key_version(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_key_ring_rest_required_fields(request_type=service.GetKeyRingRequest): +def test_get_crypto_key_version_rest_required_fields( + request_type=service.GetCryptoKeyVersionRequest, +): transport_class = transports.KeyManagementServiceRestTransport request_init = {} @@ -15249,7 +16243,7 @@ def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingReques unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_key_ring._get_unset_required_fields(jsonified_request) + ).get_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -15258,7 +16252,7 @@ def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingReques unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_key_ring._get_unset_required_fields(jsonified_request) + ).get_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -15272,7 +16266,7 @@ def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingReques request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() + return_value = resources.CryptoKeyVersion() # 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 @@ -15293,30 +16287,30 @@ def test_get_key_ring_rest_required_fields(request_type=service.GetKeyRingReques response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) + return_value = resources.CryptoKeyVersion.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_key_ring(request) + response = client.get_crypto_key_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_key_ring_rest_unset_required_fields(): +def test_get_crypto_key_version_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_key_ring._get_unset_required_fields({}) + unset_fields = transport.get_crypto_key_version._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_key_ring_rest_flattened(): +def test_get_crypto_key_version_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15325,10 +16319,12 @@ def test_get_key_ring_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() + return_value = resources.CryptoKeyVersion() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/keyRings/sample3"} + sample_request = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } # get truthy value for each flattened field mock_args = dict( @@ -15340,25 +16336,26 @@ def test_get_key_ring_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) + return_value = resources.CryptoKeyVersion.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_key_ring(**mock_args) + client.get_crypto_key_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" + % client.transport._host, args[1], ) -def test_get_key_ring_rest_flattened_error(transport: str = "rest"): +def test_get_crypto_key_version_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15367,13 +16364,13 @@ def test_get_key_ring_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_key_ring( - service.GetKeyRingRequest(), + client.get_crypto_key_version( + service.GetCryptoKeyVersionRequest(), name="name_value", ) -def test_get_crypto_key_rest_use_cached_wrapped_rpc(): +def test_get_public_key_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: @@ -15387,29 +16384,29 @@ def test_get_crypto_key_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_crypto_key in client._transport._wrapped_methods + assert client._transport.get_public_key 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_crypto_key] = mock_rpc + client._transport._wrapped_methods[client._transport.get_public_key] = mock_rpc request = {} - client.get_crypto_key(request) + client.get_public_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_crypto_key(request) + client.get_public_key(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_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRequest): +def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRequest): transport_class = transports.KeyManagementServiceRestTransport request_init = {} @@ -15424,7 +16421,7 @@ def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_crypto_key._get_unset_required_fields(jsonified_request) + ).get_public_key._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -15433,7 +16430,9 @@ def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_crypto_key._get_unset_required_fields(jsonified_request) + ).get_public_key._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("public_key_format",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -15447,7 +16446,7 @@ def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() + return_value = resources.PublicKey() # 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 @@ -15468,30 +16467,30 @@ def test_get_crypto_key_rest_required_fields(request_type=service.GetCryptoKeyRe response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) + return_value = resources.PublicKey.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_crypto_key(request) + response = client.get_public_key(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_crypto_key_rest_unset_required_fields(): +def test_get_public_key_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_crypto_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.get_public_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(("publicKeyFormat",)) & set(("name",))) -def test_get_crypto_key_rest_flattened(): +def test_get_public_key_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15500,11 +16499,11 @@ def test_get_crypto_key_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() + return_value = resources.PublicKey() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" } # get truthy value for each flattened field @@ -15517,26 +16516,26 @@ def test_get_crypto_key_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CryptoKey.pb(return_value) + return_value = resources.PublicKey.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_crypto_key(**mock_args) + client.get_public_key(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" + "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey" % client.transport._host, args[1], ) -def test_get_crypto_key_rest_flattened_error(transport: str = "rest"): +def test_get_public_key_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15545,13 +16544,13 @@ def test_get_crypto_key_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_crypto_key( - service.GetCryptoKeyRequest(), + client.get_public_key( + service.GetPublicKeyRequest(), name="name_value", ) -def test_get_crypto_key_version_rest_use_cached_wrapped_rpc(): +def test_get_import_job_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: @@ -15565,36 +16564,29 @@ def test_get_crypto_key_version_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_crypto_key_version - in client._transport._wrapped_methods - ) + assert client._transport.get_import_job 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_crypto_key_version] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.get_import_job] = mock_rpc request = {} - client.get_crypto_key_version(request) + client.get_import_job(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_crypto_key_version(request) + client.get_import_job(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_crypto_key_version_rest_required_fields( - request_type=service.GetCryptoKeyVersionRequest, -): +def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRequest): transport_class = transports.KeyManagementServiceRestTransport request_init = {} @@ -15609,7 +16601,7 @@ def test_get_crypto_key_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_crypto_key_version._get_unset_required_fields(jsonified_request) + ).get_import_job._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -15618,7 +16610,9 @@ def test_get_crypto_key_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_crypto_key_version._get_unset_required_fields(jsonified_request) + ).get_import_job._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("public_key_format",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -15632,7 +16626,7 @@ def test_get_crypto_key_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() + return_value = resources.ImportJob() # 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 @@ -15653,30 +16647,30 @@ def test_get_crypto_key_version_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) + return_value = resources.ImportJob.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_crypto_key_version(request) + response = client.get_import_job(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_crypto_key_version_rest_unset_required_fields(): +def test_get_import_job_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.get_import_job._get_unset_required_fields({}) + assert set(unset_fields) == (set(("publicKeyFormat",)) & set(("name",))) -def test_get_crypto_key_version_rest_flattened(): +def test_get_import_job_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15685,11 +16679,11 @@ def test_get_crypto_key_version_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() + return_value = resources.ImportJob() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + "name": "projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4" } # get truthy value for each flattened field @@ -15702,26 +16696,26 @@ def test_get_crypto_key_version_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) + return_value = resources.ImportJob.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_crypto_key_version(**mock_args) + client.get_import_job(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" + "%s/v1/{name=projects/*/locations/*/keyRings/*/importJobs/*}" % client.transport._host, args[1], ) -def test_get_crypto_key_version_rest_flattened_error(transport: str = "rest"): +def test_get_import_job_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15730,13 +16724,13 @@ def test_get_crypto_key_version_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_crypto_key_version( - service.GetCryptoKeyVersionRequest(), + client.get_import_job( + service.GetImportJobRequest(), name="name_value", ) -def test_get_public_key_rest_use_cached_wrapped_rpc(): +def test_get_retired_resource_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: @@ -15750,29 +16744,35 @@ def test_get_public_key_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_public_key in client._transport._wrapped_methods + assert ( + client._transport.get_retired_resource 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_public_key] = mock_rpc + client._transport._wrapped_methods[client._transport.get_retired_resource] = ( + mock_rpc + ) request = {} - client.get_public_key(request) + client.get_retired_resource(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_public_key(request) + client.get_retired_resource(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_public_key_rest_required_fields(request_type=service.GetPublicKeyRequest): +def test_get_retired_resource_rest_required_fields( + request_type=service.GetRetiredResourceRequest, +): transport_class = transports.KeyManagementServiceRestTransport request_init = {} @@ -15787,7 +16787,7 @@ def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_public_key._get_unset_required_fields(jsonified_request) + ).get_retired_resource._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -15796,9 +16796,7 @@ def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRe unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_public_key._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("public_key_format",)) + ).get_retired_resource._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -15812,7 +16810,7 @@ def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.PublicKey() + return_value = resources.RetiredResource() # 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 @@ -15833,30 +16831,30 @@ def test_get_public_key_rest_required_fields(request_type=service.GetPublicKeyRe response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.PublicKey.pb(return_value) + return_value = resources.RetiredResource.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_public_key(request) + response = client.get_retired_resource(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_public_key_rest_unset_required_fields(): +def test_get_retired_resource_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_public_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(("publicKeyFormat",)) & set(("name",))) + unset_fields = transport.get_retired_resource._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_get_public_key_rest_flattened(): +def test_get_retired_resource_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15865,11 +16863,11 @@ def test_get_public_key_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.PublicKey() + return_value = resources.RetiredResource() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + "name": "projects/sample1/locations/sample2/retiredResources/sample3" } # get truthy value for each flattened field @@ -15882,26 +16880,26 @@ def test_get_public_key_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.PublicKey.pb(return_value) + return_value = resources.RetiredResource.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_public_key(**mock_args) + client.get_retired_resource(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}/publicKey" + "%s/v1/{name=projects/*/locations/*/retiredResources/*}" % client.transport._host, args[1], ) -def test_get_public_key_rest_flattened_error(transport: str = "rest"): +def test_get_retired_resource_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15910,13 +16908,13 @@ def test_get_public_key_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_public_key( - service.GetPublicKeyRequest(), + client.get_retired_resource( + service.GetRetiredResourceRequest(), name="name_value", ) -def test_get_import_job_rest_use_cached_wrapped_rpc(): +def test_create_key_ring_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: @@ -15930,33 +16928,36 @@ def test_get_import_job_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_import_job in client._transport._wrapped_methods + assert client._transport.create_key_ring 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_import_job] = mock_rpc + client._transport._wrapped_methods[client._transport.create_key_ring] = mock_rpc request = {} - client.get_import_job(request) + client.create_key_ring(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_import_job(request) + client.create_key_ring(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_import_job_rest_required_fields(request_type=service.GetImportJobRequest): +def test_create_key_ring_rest_required_fields( + request_type=service.CreateKeyRingRequest, +): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["key_ring_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15964,26 +16965,32 @@ def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRe ) # verify fields with default values are dropped + assert "keyRingId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_import_job._get_unset_required_fields(jsonified_request) + ).create_key_ring._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "keyRingId" in jsonified_request + assert jsonified_request["keyRingId"] == request_init["key_ring_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["keyRingId"] = "key_ring_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_import_job._get_unset_required_fields(jsonified_request) + ).create_key_ring._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("public_key_format",)) + assert not set(unset_fields) - set(("key_ring_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "keyRingId" in jsonified_request + assert jsonified_request["keyRingId"] == "key_ring_id_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15992,7 +16999,7 @@ def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRe request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.ImportJob() + return_value = resources.KeyRing() # 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 @@ -16004,39 +17011,55 @@ def test_get_import_job_rest_required_fields(request_type=service.GetImportJobRe pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ImportJob.pb(return_value) + return_value = resources.KeyRing.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_import_job(request) + response = client.create_key_ring(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "keyRingId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_import_job_rest_unset_required_fields(): +def test_create_key_ring_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_import_job._get_unset_required_fields({}) - assert set(unset_fields) == (set(("publicKeyFormat",)) & set(("name",))) + unset_fields = transport.create_key_ring._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(("keyRingId",)) + & set( + ( + "parent", + "keyRingId", + "keyRing", + ) + ) + ) -def test_get_import_job_rest_flattened(): +def test_create_key_ring_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16045,16 +17068,16 @@ def test_get_import_job_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.ImportJob() + return_value = resources.KeyRing() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/importJobs/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + key_ring_id="key_ring_id_value", + key_ring=resources.KeyRing(name="name_value"), ) mock_args.update(sample_request) @@ -16062,26 +17085,25 @@ def test_get_import_job_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.ImportJob.pb(return_value) + return_value = resources.KeyRing.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_import_job(**mock_args) + client.create_key_ring(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*/importJobs/*}" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/keyRings" % client.transport._host, args[1], ) -def test_get_import_job_rest_flattened_error(transport: str = "rest"): +def test_create_key_ring_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16090,13 +17112,15 @@ def test_get_import_job_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_import_job( - service.GetImportJobRequest(), - name="name_value", + client.create_key_ring( + service.CreateKeyRingRequest(), + parent="parent_value", + key_ring_id="key_ring_id_value", + key_ring=resources.KeyRing(name="name_value"), ) -def test_get_retired_resource_rest_use_cached_wrapped_rpc(): +def test_create_crypto_key_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: @@ -16110,39 +17134,38 @@ def test_get_retired_resource_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_retired_resource in client._transport._wrapped_methods - ) + assert client._transport.create_crypto_key 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_retired_resource] = ( + client._transport._wrapped_methods[client._transport.create_crypto_key] = ( mock_rpc ) request = {} - client.get_retired_resource(request) + client.create_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_retired_resource(request) + client.create_crypto_key(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_retired_resource_rest_required_fields( - request_type=service.GetRetiredResourceRequest, +def test_create_crypto_key_rest_required_fields( + request_type=service.CreateCryptoKeyRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["crypto_key_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16150,24 +17173,38 @@ def test_get_retired_resource_rest_required_fields( ) # verify fields with default values are dropped + assert "cryptoKeyId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_retired_resource._get_unset_required_fields(jsonified_request) + ).create_crypto_key._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "cryptoKeyId" in jsonified_request + assert jsonified_request["cryptoKeyId"] == request_init["crypto_key_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["cryptoKeyId"] = "crypto_key_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_retired_resource._get_unset_required_fields(jsonified_request) + ).create_crypto_key._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "crypto_key_id", + "skip_initial_version_creation", + "trusted_wrapping_enabled", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "cryptoKeyId" in jsonified_request + assert jsonified_request["cryptoKeyId"] == "crypto_key_id_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16176,7 +17213,7 @@ def test_get_retired_resource_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.RetiredResource() + return_value = resources.CryptoKey() # 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 @@ -16188,39 +17225,61 @@ def test_get_retired_resource_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.RetiredResource.pb(return_value) + return_value = resources.CryptoKey.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_retired_resource(request) + response = client.create_crypto_key(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "cryptoKeyId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_retired_resource_rest_unset_required_fields(): +def test_create_crypto_key_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_retired_resource._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "cryptoKeyId", + "skipInitialVersionCreation", + "trustedWrappingEnabled", + ) + ) + & set( + ( + "parent", + "cryptoKeyId", + "cryptoKey", + ) + ) + ) -def test_get_retired_resource_rest_flattened(): +def test_create_crypto_key_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16229,16 +17288,18 @@ def test_get_retired_resource_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.RetiredResource() + return_value = resources.CryptoKey() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/retiredResources/sample3" + "parent": "projects/sample1/locations/sample2/keyRings/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + crypto_key_id="crypto_key_id_value", + crypto_key=resources.CryptoKey(name="name_value"), ) mock_args.update(sample_request) @@ -16246,26 +17307,26 @@ def test_get_retired_resource_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.RetiredResource.pb(return_value) + return_value = resources.CryptoKey.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_retired_resource(**mock_args) + client.create_crypto_key(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/retiredResources/*}" + "%s/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys" % client.transport._host, args[1], ) -def test_get_retired_resource_rest_flattened_error(transport: str = "rest"): +def test_create_crypto_key_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16274,13 +17335,15 @@ def test_get_retired_resource_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_retired_resource( - service.GetRetiredResourceRequest(), - name="name_value", + client.create_crypto_key( + service.CreateCryptoKeyRequest(), + parent="parent_value", + crypto_key_id="crypto_key_id_value", + crypto_key=resources.CryptoKey(name="name_value"), ) -def test_create_key_ring_rest_use_cached_wrapped_rpc(): +def test_create_crypto_key_version_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: @@ -16294,36 +17357,40 @@ def test_create_key_ring_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_key_ring in client._transport._wrapped_methods + assert ( + client._transport.create_crypto_key_version + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_key_ring] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_crypto_key_version + ] = mock_rpc request = {} - client.create_key_ring(request) + client.create_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_key_ring(request) + client.create_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_key_ring_rest_required_fields( - request_type=service.CreateKeyRingRequest, +def test_create_crypto_key_version_rest_required_fields( + request_type=service.CreateCryptoKeyVersionRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} request_init["parent"] = "" - request_init["key_ring_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16331,32 +17398,24 @@ def test_create_key_ring_rest_required_fields( ) # verify fields with default values are dropped - assert "keyRingId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_key_ring._get_unset_required_fields(jsonified_request) + ).create_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "keyRingId" in jsonified_request - assert jsonified_request["keyRingId"] == request_init["key_ring_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["keyRingId"] = "key_ring_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_key_ring._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("key_ring_id",)) + ).create_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "keyRingId" in jsonified_request - assert jsonified_request["keyRingId"] == "key_ring_id_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16365,7 +17424,7 @@ def test_create_key_ring_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() + return_value = resources.CryptoKeyVersion() # 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 @@ -16387,45 +17446,38 @@ def test_create_key_ring_rest_required_fields( response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) + return_value = resources.CryptoKeyVersion.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.create_key_ring(request) + response = client.create_crypto_key_version(request) - expected_params = [ - ( - "keyRingId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_key_ring_rest_unset_required_fields(): +def test_create_crypto_key_version_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_key_ring._get_unset_required_fields({}) + unset_fields = transport.create_crypto_key_version._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("keyRingId",)) + set(()) & set( ( "parent", - "keyRingId", - "keyRing", + "cryptoKeyVersion", ) ) ) -def test_create_key_ring_rest_flattened(): +def test_create_crypto_key_version_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16434,16 +17486,17 @@ def test_create_key_ring_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.KeyRing() + return_value = resources.CryptoKeyVersion() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + } # get truthy value for each flattened field mock_args = dict( parent="parent_value", - key_ring_id="key_ring_id_value", - key_ring=resources.KeyRing(name="name_value"), + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), ) mock_args.update(sample_request) @@ -16451,25 +17504,26 @@ def test_create_key_ring_rest_flattened(): response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.KeyRing.pb(return_value) + return_value = resources.CryptoKeyVersion.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.create_key_ring(**mock_args) + client.create_crypto_key_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/keyRings" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" + % client.transport._host, args[1], ) -def test_create_key_ring_rest_flattened_error(transport: str = "rest"): +def test_create_crypto_key_version_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16478,15 +17532,14 @@ def test_create_key_ring_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_key_ring( - service.CreateKeyRingRequest(), + client.create_crypto_key_version( + service.CreateCryptoKeyVersionRequest(), parent="parent_value", - key_ring_id="key_ring_id_value", - key_ring=resources.KeyRing(name="name_value"), + crypto_key_version=resources.CryptoKeyVersion(name="name_value"), ) -def test_create_crypto_key_rest_use_cached_wrapped_rpc(): +def test_delete_crypto_key_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: @@ -16500,38 +17553,41 @@ def test_create_crypto_key_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_crypto_key in client._transport._wrapped_methods + assert client._transport.delete_crypto_key in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_crypto_key] = ( + client._transport._wrapped_methods[client._transport.delete_crypto_key] = ( mock_rpc ) request = {} - client.create_crypto_key(request) + client.delete_crypto_key(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_crypto_key(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_crypto_key(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_crypto_key_rest_required_fields( - request_type=service.CreateCryptoKeyRequest, +def test_delete_crypto_key_rest_required_fields( + request_type=service.DeleteCryptoKeyRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["crypto_key_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16539,37 +17595,24 @@ def test_create_crypto_key_rest_required_fields( ) # verify fields with default values are dropped - assert "cryptoKeyId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_crypto_key._get_unset_required_fields(jsonified_request) + ).delete_crypto_key._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "cryptoKeyId" in jsonified_request - assert jsonified_request["cryptoKeyId"] == request_init["crypto_key_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["cryptoKeyId"] = "crypto_key_id_value" - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_crypto_key._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "crypto_key_id", - "skip_initial_version_creation", - ) - ) + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_crypto_key._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "cryptoKeyId" in jsonified_request - assert jsonified_request["cryptoKeyId"] == "crypto_key_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16578,7 +17621,7 @@ def test_create_crypto_key_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16590,60 +17633,36 @@ def test_create_crypto_key_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKey.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.create_crypto_key(request) + response = client.delete_crypto_key(request) - expected_params = [ - ( - "cryptoKeyId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_crypto_key_rest_unset_required_fields(): +def test_delete_crypto_key_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_crypto_key._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "cryptoKeyId", - "skipInitialVersionCreation", - ) - ) - & set( - ( - "parent", - "cryptoKeyId", - "cryptoKey", - ) - ) - ) + unset_fields = transport.delete_crypto_key._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_crypto_key_rest_flattened(): +def test_delete_crypto_key_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16652,45 +17671,41 @@ def test_create_crypto_key_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CryptoKey() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3" + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - crypto_key_id="crypto_key_id_value", - crypto_key=resources.CryptoKey(name="name_value"), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKey.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.create_crypto_key(**mock_args) + client.delete_crypto_key(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/keyRings/*}/cryptoKeys" + "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" % client.transport._host, args[1], ) -def test_create_crypto_key_rest_flattened_error(transport: str = "rest"): +def test_delete_crypto_key_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16699,15 +17714,13 @@ def test_create_crypto_key_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_crypto_key( - service.CreateCryptoKeyRequest(), - parent="parent_value", - crypto_key_id="crypto_key_id_value", - crypto_key=resources.CryptoKey(name="name_value"), + client.delete_crypto_key( + service.DeleteCryptoKeyRequest(), + name="name_value", ) -def test_create_crypto_key_version_rest_use_cached_wrapped_rpc(): +def test_delete_crypto_key_version_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: @@ -16722,7 +17735,7 @@ def test_create_crypto_key_version_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.create_crypto_key_version + client._transport.delete_crypto_key_version in client._transport._wrapped_methods ) @@ -16732,29 +17745,33 @@ def test_create_crypto_key_version_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.create_crypto_key_version + client._transport.delete_crypto_key_version ] = mock_rpc request = {} - client.create_crypto_key_version(request) + client.delete_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_crypto_key_version(request) + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_crypto_key_version(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_create_crypto_key_version_rest_required_fields( - request_type=service.CreateCryptoKeyVersionRequest, +def test_delete_crypto_key_version_rest_required_fields( + request_type=service.DeleteCryptoKeyVersionRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16765,21 +17782,21 @@ def test_create_crypto_key_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_crypto_key_version._get_unset_required_fields(jsonified_request) + ).delete_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_crypto_key_version._get_unset_required_fields(jsonified_request) + ).delete_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16788,7 +17805,7 @@ def test_create_crypto_key_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16800,48 +17817,36 @@ def test_create_crypto_key_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.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.create_crypto_key_version(request) + response = client.delete_crypto_key_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_create_crypto_key_version_rest_unset_required_fields(): +def test_delete_crypto_key_version_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "parent", - "cryptoKeyVersion", - ) - ) - ) + unset_fields = transport.delete_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_create_crypto_key_version_rest_flattened(): +def test_delete_crypto_key_version_rest_flattened(): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16850,44 +17855,41 @@ def test_create_crypto_key_version_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.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.create_crypto_key_version(**mock_args) + client.delete_crypto_key_version(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/keyRings/*/cryptoKeys/*}/cryptoKeyVersions" + "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" % client.transport._host, args[1], ) -def test_create_crypto_key_version_rest_flattened_error(transport: str = "rest"): +def test_delete_crypto_key_version_rest_flattened_error(transport: str = "rest"): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16896,14 +17898,13 @@ def test_create_crypto_key_version_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_crypto_key_version( - service.CreateCryptoKeyVersionRequest(), - parent="parent_value", - crypto_key_version=resources.CryptoKeyVersion(name="name_value"), + client.delete_crypto_key_version( + service.DeleteCryptoKeyVersionRequest(), + name="name_value", ) -def test_delete_crypto_key_rest_use_cached_wrapped_rpc(): +def test_import_crypto_key_version_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: @@ -16917,41 +17918,41 @@ def test_delete_crypto_key_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_crypto_key in client._transport._wrapped_methods + assert ( + client._transport.import_crypto_key_version + 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.delete_crypto_key] = ( - mock_rpc - ) + client._transport._wrapped_methods[ + client._transport.import_crypto_key_version + ] = mock_rpc request = {} - client.delete_crypto_key(request) + client.import_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_crypto_key(request) + client.import_crypto_key_version(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_delete_crypto_key_rest_required_fields( - request_type=service.DeleteCryptoKeyRequest, +def test_import_crypto_key_version_rest_required_fields( + request_type=service.ImportCryptoKeyVersionRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["import_job"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -16962,21 +17963,24 @@ def test_delete_crypto_key_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_crypto_key._get_unset_required_fields(jsonified_request) + ).import_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["importJob"] = "import_job_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_crypto_key._get_unset_required_fields(jsonified_request) + ).import_crypto_key_version._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "importJob" in jsonified_request + assert jsonified_request["importJob"] == "import_job_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16985,7 +17989,7 @@ def test_delete_crypto_key_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.CryptoKeyVersion() # 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 @@ -16997,94 +18001,49 @@ def test_delete_crypto_key_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.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.delete_crypto_key(request) + response = client.import_crypto_key_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) - - -def test_delete_crypto_key_rest_unset_required_fields(): - transport = transports.KeyManagementServiceRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) - - unset_fields = transport.delete_crypto_key._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_delete_crypto_key_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - 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.delete_crypto_key(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*}" - % client.transport._host, - args[1], - ) + assert sorted(expected_params) == sorted(actual_params) -def test_delete_crypto_key_rest_flattened_error(transport: str = "rest"): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, +def test_import_crypto_key_version_rest_unset_required_fields(): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_crypto_key( - service.DeleteCryptoKeyRequest(), - name="name_value", + unset_fields = transport.import_crypto_key_version._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "algorithm", + "importJob", + ) ) + ) -def test_delete_crypto_key_version_rest_use_cached_wrapped_rpc(): +def test_import_trusted_key_wrapped_crypto_key_version_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: @@ -17099,7 +18058,7 @@ def test_delete_crypto_key_version_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.delete_crypto_key_version + client._transport.import_trusted_key_wrapped_crypto_key_version in client._transport._wrapped_methods ) @@ -17109,33 +18068,31 @@ def test_delete_crypto_key_version_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.delete_crypto_key_version + client._transport.import_trusted_key_wrapped_crypto_key_version ] = mock_rpc request = {} - client.delete_crypto_key_version(request) + client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_crypto_key_version(request) + client.import_trusted_key_wrapped_crypto_key_version(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_delete_crypto_key_version_rest_required_fields( - request_type=service.DeleteCryptoKeyVersionRequest, +def test_import_trusted_key_wrapped_crypto_key_version_rest_required_fields( + request_type=service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["importing_key"] = "" + request_init["wrapped_key"] = b"" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17146,21 +18103,31 @@ def test_delete_crypto_key_version_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_crypto_key_version._get_unset_required_fields(jsonified_request) + ).import_trusted_key_wrapped_crypto_key_version._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["importingKey"] = "importing_key_value" + jsonified_request["wrappedKey"] = b"wrapped_key_blob" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_crypto_key_version._get_unset_required_fields(jsonified_request) + ).import_trusted_key_wrapped_crypto_key_version._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "importingKey" in jsonified_request + assert jsonified_request["importingKey"] == "importing_key_value" + assert "wrappedKey" in jsonified_request + assert jsonified_request["wrappedKey"] == b"wrapped_key_blob" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17169,7 +18136,7 @@ def test_delete_crypto_key_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.CryptoKeyVersion() # 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 @@ -17181,94 +18148,52 @@ def test_delete_crypto_key_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.CryptoKeyVersion.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.delete_crypto_key_version(request) + response = client.import_trusted_key_wrapped_crypto_key_version(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_delete_crypto_key_version_rest_unset_required_fields(): +def test_import_trusted_key_wrapped_crypto_key_version_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_crypto_key_version._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) - - -def test_delete_crypto_key_version_rest_flattened(): - client = KeyManagementServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + unset_fields = transport.import_trusted_key_wrapped_crypto_key_version._get_unset_required_fields( + {} ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_crypto_key_version(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/keyRings/*/cryptoKeys/*/cryptoKeyVersions/*}" - % client.transport._host, - args[1], + assert set(unset_fields) == ( + set(()) + & set( + ( + "parent", + "importingKey", + "wrappedKey", + "algorithm", + ) ) - - -def test_delete_crypto_key_version_rest_flattened_error(transport: str = "rest"): - client = KeyManagementServiceClient( - 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.delete_crypto_key_version( - service.DeleteCryptoKeyVersionRequest(), - name="name_value", - ) - -def test_import_crypto_key_version_rest_use_cached_wrapped_rpc(): +def test_export_trusted_key_wrapped_crypto_key_version_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: @@ -17283,7 +18208,7 @@ def test_import_crypto_key_version_rest_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.import_crypto_key_version + client._transport.export_trusted_key_wrapped_crypto_key_version in client._transport._wrapped_methods ) @@ -17293,30 +18218,30 @@ def test_import_crypto_key_version_rest_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.import_crypto_key_version + client._transport.export_trusted_key_wrapped_crypto_key_version ] = mock_rpc request = {} - client.import_crypto_key_version(request) + client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.import_crypto_key_version(request) + client.export_trusted_key_wrapped_crypto_key_version(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_import_crypto_key_version_rest_required_fields( - request_type=service.ImportCryptoKeyVersionRequest, +def test_export_trusted_key_wrapped_crypto_key_version_rest_required_fields( + request_type=service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, ): transport_class = transports.KeyManagementServiceRestTransport request_init = {} - request_init["parent"] = "" - request_init["import_job"] = "" + request_init["name"] = "" + request_init["wrapping_key"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -17324,27 +18249,36 @@ def test_import_crypto_key_version_rest_required_fields( ) # verify fields with default values are dropped + assert "wrappingKey" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_crypto_key_version._get_unset_required_fields(jsonified_request) + ).export_trusted_key_wrapped_crypto_key_version._get_unset_required_fields( + jsonified_request + ) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "wrappingKey" in jsonified_request + assert jsonified_request["wrappingKey"] == request_init["wrapping_key"] - jsonified_request["parent"] = "parent_value" - jsonified_request["importJob"] = "import_job_value" + jsonified_request["name"] = "name_value" + jsonified_request["wrappingKey"] = "wrapping_key_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).import_crypto_key_version._get_unset_required_fields(jsonified_request) + ).export_trusted_key_wrapped_crypto_key_version._get_unset_required_fields( + jsonified_request + ) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("wrapping_key",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "importJob" in jsonified_request - assert jsonified_request["importJob"] == "import_job_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + assert "wrappingKey" in jsonified_request + assert jsonified_request["wrappingKey"] == "wrapping_key_value" client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -17353,7 +18287,7 @@ def test_import_crypto_key_version_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.CryptoKeyVersion() + return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() # 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 @@ -17365,43 +18299,51 @@ def test_import_crypto_key_version_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) + return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.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.import_crypto_key_version(request) + response = client.export_trusted_key_wrapped_crypto_key_version(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "wrappingKey", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_import_crypto_key_version_rest_unset_required_fields(): +def test_export_trusted_key_wrapped_crypto_key_version_rest_unset_required_fields(): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.import_crypto_key_version._get_unset_required_fields({}) + unset_fields = transport.export_trusted_key_wrapped_crypto_key_version._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( - set(()) + set(("wrappingKey",)) & set( ( - "parent", - "algorithm", - "importJob", + "name", + "wrappingKey", ) ) ) @@ -20707,6 +21649,50 @@ def test_import_crypto_key_version_empty_call_grpc(): 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_import_trusted_key_wrapped_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" + ) as call: + call.return_value = resources.CryptoKeyVersion() + client.import_trusted_key_wrapped_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() + 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_export_trusted_key_wrapped_crypto_key_version_empty_call_grpc(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" + ) as call: + call.return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() + client.export_trusted_key_wrapped_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() + 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_create_import_job_empty_call_grpc(): @@ -21276,6 +22262,8 @@ async def test_get_crypto_key_version_empty_call_grpc_asyncio(): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) await client.get_crypto_key_version(request=None) @@ -21460,6 +22448,8 @@ async def test_create_crypto_key_version_empty_call_grpc_asyncio(): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) await client.create_crypto_key_version(request=None) @@ -21548,6 +22538,8 @@ async def test_import_crypto_key_version_empty_call_grpc_asyncio(): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) await client.import_crypto_key_version(request=None) @@ -21559,6 +22551,72 @@ async def test_import_crypto_key_version_empty_call_grpc_asyncio(): 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. +@pytest.mark.asyncio +async def test_import_trusted_key_wrapped_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, + ) + ) + await client.import_trusted_key_wrapped_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() + 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. +@pytest.mark.asyncio +async def test_export_trusted_key_wrapped_crypto_key_version_empty_call_grpc_asyncio(): + client = KeyManagementServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse( + wrapped_key=b"wrapped_key_blob", + ) + ) + await client.export_trusted_key_wrapped_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() + 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. @pytest.mark.asyncio @@ -21648,6 +22706,8 @@ async def test_update_crypto_key_version_empty_call_grpc_asyncio(): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) await client.update_crypto_key_version(request=None) @@ -21715,6 +22775,8 @@ async def test_destroy_crypto_key_version_empty_call_grpc_asyncio(): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) await client.destroy_crypto_key_version(request=None) @@ -21751,6 +22813,8 @@ async def test_restore_crypto_key_version_empty_call_grpc_asyncio(): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) ) await client.restore_crypto_key_version(request=None) @@ -23067,6 +24131,8 @@ def test_get_crypto_key_version_rest_call_success(request_type): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) # Wrap the value into a proper Response obj @@ -23101,6 +24167,8 @@ def test_get_crypto_key_version_rest_call_success(request_type): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -23868,6 +24936,8 @@ def test_create_crypto_key_rest_call_success(request_type): "ekm_connection_key_path": "ekm_connection_key_path_value", }, "reimport_eligible": True, + "trusted_wrapping_enabled": True, + "hsm_trusted": True, }, "purpose": 1, "create_time": {}, @@ -24120,6 +25190,8 @@ def test_create_crypto_key_version_rest_call_success(request_type): "ekm_connection_key_path": "ekm_connection_key_path_value", }, "reimport_eligible": True, + "trusted_wrapping_enabled": True, + "hsm_trusted": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -24203,6 +25275,8 @@ def get_message_fields(field): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) # Wrap the value into a proper Response obj @@ -24237,10 +25311,271 @@ def get_message_fields(field): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_crypto_key_version_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(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.KeyManagementServiceRestInterceptor, + "post_create_crypto_key_version", + ) as post, + mock.patch.object( + transports.KeyManagementServiceRestInterceptor, + "post_create_crypto_key_version_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.KeyManagementServiceRestInterceptor, + "pre_create_crypto_key_version", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.CreateCryptoKeyVersionRequest.pb( + service.CreateCryptoKeyVersionRequest() + ) + 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 = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + req.return_value.content = return_value + + request = service.CreateCryptoKeyVersionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.CryptoKeyVersion() + post_with_metadata.return_value = resources.CryptoKeyVersion(), metadata + + client.create_crypto_key_version( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_crypto_key_rest_bad_request( + request_type=service.DeleteCryptoKeyRequest, +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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.delete_crypto_key(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCryptoKeyRequest, + dict, + ], +) +def test_delete_crypto_key_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_crypto_key(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_crypto_key_rest_interceptors(null_interceptor): + transport = transports.KeyManagementServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.KeyManagementServiceRestInterceptor(), + ) + client = KeyManagementServiceClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "post_delete_crypto_key" + ) as post, + mock.patch.object( + transports.KeyManagementServiceRestInterceptor, + "post_delete_crypto_key_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.KeyManagementServiceRestInterceptor, "pre_delete_crypto_key" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.DeleteCryptoKeyRequest.pb(service.DeleteCryptoKeyRequest()) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.DeleteCryptoKeyRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_crypto_key( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_crypto_key_version_rest_bad_request( + request_type=service.DeleteCryptoKeyVersionRequest, +): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + 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.delete_crypto_key_version(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteCryptoKeyVersionRequest, + dict, + ], +) +def test_delete_crypto_key_version_rest_call_success(request_type): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_crypto_key_version(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_crypto_key_version_rest_interceptors(null_interceptor): +def test_delete_crypto_key_version_rest_interceptors(null_interceptor): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24252,24 +25587,25 @@ def test_create_crypto_key_version_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_create_crypto_key_version", + "post_delete_crypto_key_version", ) as post, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_create_crypto_key_version_with_metadata", + "post_delete_crypto_key_version_with_metadata", ) as post_with_metadata, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "pre_create_crypto_key_version", + "pre_delete_crypto_key_version", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.CreateCryptoKeyVersionRequest.pb( - service.CreateCryptoKeyVersionRequest() + pb_message = service.DeleteCryptoKeyVersionRequest.pb( + service.DeleteCryptoKeyVersionRequest() ) transcode.return_value = { "method": "post", @@ -24281,19 +25617,19 @@ def test_create_crypto_key_version_rest_interceptors(null_interceptor): 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 = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.CreateCryptoKeyVersionRequest() + request = service.DeleteCryptoKeyVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - post_with_metadata.return_value = resources.CryptoKeyVersion(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_crypto_key_version( + client.delete_crypto_key_version( request, metadata=[ ("key", "val"), @@ -24306,15 +25642,15 @@ def test_create_crypto_key_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_crypto_key_rest_bad_request( - request_type=service.DeleteCryptoKeyRequest, +def test_import_crypto_key_version_rest_bad_request( + request_type=service.ImportCryptoKeyVersionRequest, ): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" } request = request_type(**request_init) @@ -24331,47 +25667,82 @@ def test_delete_crypto_key_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_crypto_key(request) + client.import_crypto_key_version(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteCryptoKeyRequest, + service.ImportCryptoKeyVersionRequest, dict, ], ) -def test_delete_crypto_key_rest_call_success(request_type): +def test_import_crypto_key_version_rest_call_success(request_type): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = operations_pb2.Operation(name="operations/spam") + return_value = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, + ) # 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 = resources.CryptoKeyVersion.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.delete_crypto_key(request) + response = client.import_crypto_key_version(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_crypto_key_rest_interceptors(null_interceptor): +def test_import_crypto_key_version_rest_interceptors(null_interceptor): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24383,22 +25754,25 @@ def test_delete_crypto_key_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.KeyManagementServiceRestInterceptor, "post_delete_crypto_key" + transports.KeyManagementServiceRestInterceptor, + "post_import_crypto_key_version", ) as post, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_delete_crypto_key_with_metadata", + "post_import_crypto_key_version_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.KeyManagementServiceRestInterceptor, "pre_delete_crypto_key" + transports.KeyManagementServiceRestInterceptor, + "pre_import_crypto_key_version", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DeleteCryptoKeyRequest.pb(service.DeleteCryptoKeyRequest()) + pb_message = service.ImportCryptoKeyVersionRequest.pb( + service.ImportCryptoKeyVersionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -24409,19 +25783,19 @@ def test_delete_crypto_key_rest_interceptors(null_interceptor): 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 = json_format.MessageToJson(operations_pb2.Operation()) + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) req.return_value.content = return_value - request = service.DeleteCryptoKeyRequest() + request = service.ImportCryptoKeyVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = resources.CryptoKeyVersion() + post_with_metadata.return_value = resources.CryptoKeyVersion(), metadata - client.delete_crypto_key( + client.import_crypto_key_version( request, metadata=[ ("key", "val"), @@ -24434,15 +25808,15 @@ def test_delete_crypto_key_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_crypto_key_version_rest_bad_request( - request_type=service.DeleteCryptoKeyVersionRequest, +def test_import_trusted_key_wrapped_crypto_key_version_rest_bad_request( + request_type=service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, ): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" } request = request_type(**request_init) @@ -24459,47 +25833,84 @@ def test_delete_crypto_key_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_crypto_key_version(request) + client.import_trusted_key_wrapped_crypto_key_version(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteCryptoKeyVersionRequest, + service.ImportTrustedKeyWrappedCryptoKeyVersionRequest, dict, ], ) -def test_delete_crypto_key_version_rest_call_success(request_type): +def test_import_trusted_key_wrapped_crypto_key_version_rest_call_success(request_type): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" + "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/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 = operations_pb2.Operation(name="operations/spam") + return_value = resources.CryptoKeyVersion( + name="name_value", + state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, + protection_level=resources.ProtectionLevel.SOFTWARE, + algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, + import_job="import_job_value", + import_failure_reason="import_failure_reason_value", + generation_failure_reason="generation_failure_reason_value", + external_destruction_failure_reason="external_destruction_failure_reason_value", + reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, + ) # 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 = resources.CryptoKeyVersion.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.delete_crypto_key_version(request) + response = client.import_trusted_key_wrapped_crypto_key_version(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, resources.CryptoKeyVersion) + assert response.name == "name_value" + assert ( + response.state + == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION + ) + assert response.protection_level == resources.ProtectionLevel.SOFTWARE + assert ( + response.algorithm + == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION + ) + assert response.import_job == "import_job_value" + assert response.import_failure_reason == "import_failure_reason_value" + assert response.generation_failure_reason == "generation_failure_reason_value" + assert ( + response.external_destruction_failure_reason + == "external_destruction_failure_reason_value" + ) + assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_crypto_key_version_rest_interceptors(null_interceptor): +def test_import_trusted_key_wrapped_crypto_key_version_rest_interceptors( + null_interceptor, +): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24511,25 +25922,24 @@ def test_delete_crypto_key_version_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, - mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_delete_crypto_key_version", + "post_import_trusted_key_wrapped_crypto_key_version", ) as post, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_delete_crypto_key_version_with_metadata", + "post_import_trusted_key_wrapped_crypto_key_version_with_metadata", ) as post_with_metadata, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "pre_delete_crypto_key_version", + "pre_import_trusted_key_wrapped_crypto_key_version", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DeleteCryptoKeyVersionRequest.pb( - service.DeleteCryptoKeyVersionRequest() + pb_message = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest.pb( + service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() ) transcode.return_value = { "method": "post", @@ -24541,19 +25951,19 @@ def test_delete_crypto_key_version_rest_interceptors(null_interceptor): 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 = json_format.MessageToJson(operations_pb2.Operation()) + return_value = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) req.return_value.content = return_value - request = service.DeleteCryptoKeyVersionRequest() + request = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() - post_with_metadata.return_value = operations_pb2.Operation(), metadata + post.return_value = resources.CryptoKeyVersion() + post_with_metadata.return_value = resources.CryptoKeyVersion(), metadata - client.delete_crypto_key_version( + client.import_trusted_key_wrapped_crypto_key_version( request, metadata=[ ("key", "val"), @@ -24566,15 +25976,15 @@ def test_delete_crypto_key_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_import_crypto_key_version_rest_bad_request( - request_type=service.ImportCryptoKeyVersionRequest, +def test_export_trusted_key_wrapped_crypto_key_version_rest_bad_request( + request_type=service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, ): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" } request = request_type(**request_init) @@ -24591,40 +26001,32 @@ def test_import_crypto_key_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.import_crypto_key_version(request) + client.export_trusted_key_wrapped_crypto_key_version(request) @pytest.mark.parametrize( "request_type", [ - service.ImportCryptoKeyVersionRequest, + service.ExportTrustedKeyWrappedCryptoKeyVersionRequest, dict, ], ) -def test_import_crypto_key_version_rest_call_success(request_type): +def test_export_trusted_key_wrapped_crypto_key_version_rest_call_success(request_type): client = KeyManagementServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "parent": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4" + "name": "projects/sample1/locations/sample2/keyRings/sample3/cryptoKeys/sample4/cryptoKeyVersions/sample5" } 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 = resources.CryptoKeyVersion( - name="name_value", - state=resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION, - protection_level=resources.ProtectionLevel.SOFTWARE, - algorithm=resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION, - import_job="import_job_value", - import_failure_reason="import_failure_reason_value", - generation_failure_reason="generation_failure_reason_value", - external_destruction_failure_reason="external_destruction_failure_reason_value", - reimport_eligible=True, + return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse( + wrapped_key=b"wrapped_key_blob", ) # Wrap the value into a proper Response obj @@ -24632,37 +26034,24 @@ def test_import_crypto_key_version_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = resources.CryptoKeyVersion.pb(return_value) + return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.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.import_crypto_key_version(request) + response = client.export_trusted_key_wrapped_crypto_key_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.CryptoKeyVersion) - assert response.name == "name_value" - assert ( - response.state - == resources.CryptoKeyVersion.CryptoKeyVersionState.PENDING_GENERATION - ) - assert response.protection_level == resources.ProtectionLevel.SOFTWARE - assert ( - response.algorithm - == resources.CryptoKeyVersion.CryptoKeyVersionAlgorithm.GOOGLE_SYMMETRIC_ENCRYPTION - ) - assert response.import_job == "import_job_value" - assert response.import_failure_reason == "import_failure_reason_value" - assert response.generation_failure_reason == "generation_failure_reason_value" - assert ( - response.external_destruction_failure_reason - == "external_destruction_failure_reason_value" - ) - assert response.reimport_eligible is True + assert isinstance(response, service.ExportTrustedKeyWrappedCryptoKeyVersionResponse) + assert response.wrapped_key == b"wrapped_key_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_import_crypto_key_version_rest_interceptors(null_interceptor): +def test_export_trusted_key_wrapped_crypto_key_version_rest_interceptors( + null_interceptor, +): transport = transports.KeyManagementServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -24676,22 +26065,22 @@ def test_import_crypto_key_version_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_import_crypto_key_version", + "post_export_trusted_key_wrapped_crypto_key_version", ) as post, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "post_import_crypto_key_version_with_metadata", + "post_export_trusted_key_wrapped_crypto_key_version_with_metadata", ) as post_with_metadata, mock.patch.object( transports.KeyManagementServiceRestInterceptor, - "pre_import_crypto_key_version", + "pre_export_trusted_key_wrapped_crypto_key_version", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ImportCryptoKeyVersionRequest.pb( - service.ImportCryptoKeyVersionRequest() + pb_message = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest.pb( + service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() ) transcode.return_value = { "method": "post", @@ -24703,19 +26092,24 @@ def test_import_crypto_key_version_rest_interceptors(null_interceptor): 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 = resources.CryptoKeyVersion.to_json(resources.CryptoKeyVersion()) + return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse.to_json( + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() + ) req.return_value.content = return_value - request = service.ImportCryptoKeyVersionRequest() + request = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.CryptoKeyVersion() - post_with_metadata.return_value = resources.CryptoKeyVersion(), metadata + post.return_value = service.ExportTrustedKeyWrappedCryptoKeyVersionResponse() + post_with_metadata.return_value = ( + service.ExportTrustedKeyWrappedCryptoKeyVersionResponse(), + metadata, + ) - client.import_crypto_key_version( + client.export_trusted_key_wrapped_crypto_key_version( request, metadata=[ ("key", "val"), @@ -25049,6 +26443,8 @@ def test_update_crypto_key_rest_call_success(request_type): "ekm_connection_key_path": "ekm_connection_key_path_value", }, "reimport_eligible": True, + "trusted_wrapping_enabled": True, + "hsm_trusted": True, }, "purpose": 1, "create_time": {}, @@ -25305,6 +26701,8 @@ def test_update_crypto_key_version_rest_call_success(request_type): "ekm_connection_key_path": "ekm_connection_key_path_value", }, "reimport_eligible": True, + "trusted_wrapping_enabled": True, + "hsm_trusted": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -25388,6 +26786,8 @@ def get_message_fields(field): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) # Wrap the value into a proper Response obj @@ -25422,6 +26822,8 @@ def get_message_fields(field): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -25693,6 +27095,8 @@ def test_destroy_crypto_key_version_rest_call_success(request_type): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) # Wrap the value into a proper Response obj @@ -25727,6 +27131,8 @@ def test_destroy_crypto_key_version_rest_call_success(request_type): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -25855,6 +27261,8 @@ def test_restore_crypto_key_version_rest_call_success(request_type): generation_failure_reason="generation_failure_reason_value", external_destruction_failure_reason="external_destruction_failure_reason_value", reimport_eligible=True, + trusted_wrapping_enabled=True, + hsm_trusted=True, ) # Wrap the value into a proper Response obj @@ -25889,6 +27297,8 @@ def test_restore_crypto_key_version_rest_call_success(request_type): == "external_destruction_failure_reason_value" ) assert response.reimport_eligible is True + assert response.trusted_wrapping_enabled is True + assert response.hsm_trusted is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -28073,6 +29483,48 @@ def test_import_crypto_key_version_empty_call_rest(): 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_import_trusted_key_wrapped_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.import_trusted_key_wrapped_crypto_key_version), "__call__" + ) as call: + client.import_trusted_key_wrapped_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ImportTrustedKeyWrappedCryptoKeyVersionRequest() + 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_export_trusted_key_wrapped_crypto_key_version_empty_call_rest(): + client = KeyManagementServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.export_trusted_key_wrapped_crypto_key_version), "__call__" + ) as call: + client.export_trusted_key_wrapped_crypto_key_version(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ExportTrustedKeyWrappedCryptoKeyVersionRequest() + 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_create_import_job_empty_call_rest(): @@ -28460,6 +29912,8 @@ def test_key_management_service_base_transport(): "delete_crypto_key", "delete_crypto_key_version", "import_crypto_key_version", + "import_trusted_key_wrapped_crypto_key_version", + "export_trusted_key_wrapped_crypto_key_version", "create_import_job", "update_crypto_key", "update_crypto_key_version", @@ -28817,6 +30271,12 @@ def test_key_management_service_client_transport_session_collision(transport_nam session1 = client1.transport.import_crypto_key_version._session session2 = client2.transport.import_crypto_key_version._session assert session1 != session2 + session1 = client1.transport.import_trusted_key_wrapped_crypto_key_version._session + session2 = client2.transport.import_trusted_key_wrapped_crypto_key_version._session + assert session1 != session2 + session1 = client1.transport.export_trusted_key_wrapped_crypto_key_version._session + session2 = client2.transport.export_trusted_key_wrapped_crypto_key_version._session + assert session1 != session2 session1 = client1.transport.create_import_job._session session2 = client2.transport.create_import_job._session assert session1 != session2 diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py index b299b61b2bcb..c37c376a885a 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/__init__.py @@ -25,25 +25,61 @@ from .services.memorystore import MemorystoreAsyncClient, MemorystoreClient from .types.memorystore import ( + AddAuthTokenRequest, + AddTokenAuthUserRequest, + AuthToken, + AutomatedBackupConfig, + Backup, + BackupCollection, + BackupFile, + BackupInstanceRequest, CertificateAuthority, ConnectionType, CreateInstanceRequest, + CrossInstanceReplicationConfig, + DeleteAuthTokenRequest, + DeleteBackupRequest, DeleteInstanceRequest, + DeleteTokenAuthUserRequest, DiscoveryEndpoint, + EncryptionInfo, + ExportBackupRequest, + FinishMigrationRequest, + GetAuthTokenRequest, + GetBackupCollectionRequest, + GetBackupRequest, GetCertificateAuthorityRequest, GetInstanceRequest, GetSharedRegionalCertificateAuthorityRequest, + GetTokenAuthUserRequest, Instance, + ListAuthTokensRequest, + ListAuthTokensResponse, + ListBackupCollectionsRequest, + ListBackupCollectionsResponse, + ListBackupsRequest, + ListBackupsResponse, ListInstancesRequest, ListInstancesResponse, + ListTokenAuthUsersRequest, + ListTokenAuthUsersResponse, + MaintenancePolicy, + MaintenanceSchedule, + MigrationConfig, NodeConfig, OperationMetadata, PersistenceConfig, + PscAttachmentDetail, PscAutoConnection, PscConnection, PscConnectionStatus, + RescheduleMaintenanceRequest, + SelfManagedSource, SharedRegionalCertificateAuthority, + StartMigrationRequest, + TokenAuthUser, UpdateInstanceRequest, + WeeklyMaintenanceWindow, ZoneDistributionConfig, ) @@ -132,25 +168,61 @@ def _get_version(dependency_name): __all__ = ( "MemorystoreAsyncClient", + "AddAuthTokenRequest", + "AddTokenAuthUserRequest", + "AuthToken", + "AutomatedBackupConfig", + "Backup", + "BackupCollection", + "BackupFile", + "BackupInstanceRequest", "CertificateAuthority", "ConnectionType", "CreateInstanceRequest", + "CrossInstanceReplicationConfig", + "DeleteAuthTokenRequest", + "DeleteBackupRequest", "DeleteInstanceRequest", + "DeleteTokenAuthUserRequest", "DiscoveryEndpoint", + "EncryptionInfo", + "ExportBackupRequest", + "FinishMigrationRequest", + "GetAuthTokenRequest", + "GetBackupCollectionRequest", + "GetBackupRequest", "GetCertificateAuthorityRequest", "GetInstanceRequest", "GetSharedRegionalCertificateAuthorityRequest", + "GetTokenAuthUserRequest", "Instance", + "ListAuthTokensRequest", + "ListAuthTokensResponse", + "ListBackupCollectionsRequest", + "ListBackupCollectionsResponse", + "ListBackupsRequest", + "ListBackupsResponse", "ListInstancesRequest", "ListInstancesResponse", + "ListTokenAuthUsersRequest", + "ListTokenAuthUsersResponse", + "MaintenancePolicy", + "MaintenanceSchedule", "MemorystoreClient", + "MigrationConfig", "NodeConfig", "OperationMetadata", "PersistenceConfig", + "PscAttachmentDetail", "PscAutoConnection", "PscConnection", "PscConnectionStatus", + "RescheduleMaintenanceRequest", + "SelfManagedSource", "SharedRegionalCertificateAuthority", + "StartMigrationRequest", + "TokenAuthUser", "UpdateInstanceRequest", + "WeeklyMaintenanceWindow", "ZoneDistributionConfig", ) diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json index 237dc1c73bee..35893bfeb909 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/gapic_metadata.json @@ -10,16 +10,71 @@ "grpc": { "libraryClient": "MemorystoreClient", "rpcs": { + "AddAuthToken": { + "methods": [ + "add_auth_token" + ] + }, + "AddTokenAuthUser": { + "methods": [ + "add_token_auth_user" + ] + }, + "BackupInstance": { + "methods": [ + "backup_instance" + ] + }, "CreateInstance": { "methods": [ "create_instance" ] }, + "DeleteAuthToken": { + "methods": [ + "delete_auth_token" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, "DeleteInstance": { "methods": [ "delete_instance" ] }, + "DeleteTokenAuthUser": { + "methods": [ + "delete_token_auth_user" + ] + }, + "ExportBackup": { + "methods": [ + "export_backup" + ] + }, + "FinishMigration": { + "methods": [ + "finish_migration" + ] + }, + "GetAuthToken": { + "methods": [ + "get_auth_token" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetBackupCollection": { + "methods": [ + "get_backup_collection" + ] + }, "GetCertificateAuthority": { "methods": [ "get_certificate_authority" @@ -35,11 +90,46 @@ "get_shared_regional_certificate_authority" ] }, + "GetTokenAuthUser": { + "methods": [ + "get_token_auth_user" + ] + }, + "ListAuthTokens": { + "methods": [ + "list_auth_tokens" + ] + }, + "ListBackupCollections": { + "methods": [ + "list_backup_collections" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, "ListInstances": { "methods": [ "list_instances" ] }, + "ListTokenAuthUsers": { + "methods": [ + "list_token_auth_users" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "reschedule_maintenance" + ] + }, + "StartMigration": { + "methods": [ + "start_migration" + ] + }, "UpdateInstance": { "methods": [ "update_instance" @@ -50,16 +140,71 @@ "grpc-async": { "libraryClient": "MemorystoreAsyncClient", "rpcs": { + "AddAuthToken": { + "methods": [ + "add_auth_token" + ] + }, + "AddTokenAuthUser": { + "methods": [ + "add_token_auth_user" + ] + }, + "BackupInstance": { + "methods": [ + "backup_instance" + ] + }, "CreateInstance": { "methods": [ "create_instance" ] }, + "DeleteAuthToken": { + "methods": [ + "delete_auth_token" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, "DeleteInstance": { "methods": [ "delete_instance" ] }, + "DeleteTokenAuthUser": { + "methods": [ + "delete_token_auth_user" + ] + }, + "ExportBackup": { + "methods": [ + "export_backup" + ] + }, + "FinishMigration": { + "methods": [ + "finish_migration" + ] + }, + "GetAuthToken": { + "methods": [ + "get_auth_token" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetBackupCollection": { + "methods": [ + "get_backup_collection" + ] + }, "GetCertificateAuthority": { "methods": [ "get_certificate_authority" @@ -75,11 +220,46 @@ "get_shared_regional_certificate_authority" ] }, + "GetTokenAuthUser": { + "methods": [ + "get_token_auth_user" + ] + }, + "ListAuthTokens": { + "methods": [ + "list_auth_tokens" + ] + }, + "ListBackupCollections": { + "methods": [ + "list_backup_collections" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, "ListInstances": { "methods": [ "list_instances" ] }, + "ListTokenAuthUsers": { + "methods": [ + "list_token_auth_users" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "reschedule_maintenance" + ] + }, + "StartMigration": { + "methods": [ + "start_migration" + ] + }, "UpdateInstance": { "methods": [ "update_instance" @@ -90,16 +270,71 @@ "rest": { "libraryClient": "MemorystoreClient", "rpcs": { + "AddAuthToken": { + "methods": [ + "add_auth_token" + ] + }, + "AddTokenAuthUser": { + "methods": [ + "add_token_auth_user" + ] + }, + "BackupInstance": { + "methods": [ + "backup_instance" + ] + }, "CreateInstance": { "methods": [ "create_instance" ] }, + "DeleteAuthToken": { + "methods": [ + "delete_auth_token" + ] + }, + "DeleteBackup": { + "methods": [ + "delete_backup" + ] + }, "DeleteInstance": { "methods": [ "delete_instance" ] }, + "DeleteTokenAuthUser": { + "methods": [ + "delete_token_auth_user" + ] + }, + "ExportBackup": { + "methods": [ + "export_backup" + ] + }, + "FinishMigration": { + "methods": [ + "finish_migration" + ] + }, + "GetAuthToken": { + "methods": [ + "get_auth_token" + ] + }, + "GetBackup": { + "methods": [ + "get_backup" + ] + }, + "GetBackupCollection": { + "methods": [ + "get_backup_collection" + ] + }, "GetCertificateAuthority": { "methods": [ "get_certificate_authority" @@ -115,11 +350,46 @@ "get_shared_regional_certificate_authority" ] }, + "GetTokenAuthUser": { + "methods": [ + "get_token_auth_user" + ] + }, + "ListAuthTokens": { + "methods": [ + "list_auth_tokens" + ] + }, + "ListBackupCollections": { + "methods": [ + "list_backup_collections" + ] + }, + "ListBackups": { + "methods": [ + "list_backups" + ] + }, "ListInstances": { "methods": [ "list_instances" ] }, + "ListTokenAuthUsers": { + "methods": [ + "list_token_auth_users" + ] + }, + "RescheduleMaintenance": { + "methods": [ + "reschedule_maintenance" + ] + }, + "StartMigration": { + "methods": [ + "start_migration" + ] + }, "UpdateInstance": { "methods": [ "update_instance" diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/async_client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/async_client.py index 9dab44aa0e87..34b343f03161 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/async_client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/async_client.py @@ -81,6 +81,14 @@ class MemorystoreAsyncClient: _DEFAULT_ENDPOINT_TEMPLATE = MemorystoreClient._DEFAULT_ENDPOINT_TEMPLATE _DEFAULT_UNIVERSE = MemorystoreClient._DEFAULT_UNIVERSE + auth_token_path = staticmethod(MemorystoreClient.auth_token_path) + parse_auth_token_path = staticmethod(MemorystoreClient.parse_auth_token_path) + backup_path = staticmethod(MemorystoreClient.backup_path) + parse_backup_path = staticmethod(MemorystoreClient.parse_backup_path) + backup_collection_path = staticmethod(MemorystoreClient.backup_collection_path) + parse_backup_collection_path = staticmethod( + MemorystoreClient.parse_backup_collection_path + ) ca_pool_path = staticmethod(MemorystoreClient.ca_pool_path) parse_ca_pool_path = staticmethod(MemorystoreClient.parse_ca_pool_path) certificate_authority_path = staticmethod( @@ -89,6 +97,12 @@ class MemorystoreAsyncClient: parse_certificate_authority_path = staticmethod( MemorystoreClient.parse_certificate_authority_path ) + crypto_key_path = staticmethod(MemorystoreClient.crypto_key_path) + parse_crypto_key_path = staticmethod(MemorystoreClient.parse_crypto_key_path) + crypto_key_version_path = staticmethod(MemorystoreClient.crypto_key_version_path) + parse_crypto_key_version_path = staticmethod( + MemorystoreClient.parse_crypto_key_version_path + ) forwarding_rule_path = staticmethod(MemorystoreClient.forwarding_rule_path) parse_forwarding_rule_path = staticmethod( MemorystoreClient.parse_forwarding_rule_path @@ -97,6 +111,10 @@ class MemorystoreAsyncClient: parse_instance_path = staticmethod(MemorystoreClient.parse_instance_path) network_path = staticmethod(MemorystoreClient.network_path) parse_network_path = staticmethod(MemorystoreClient.parse_network_path) + network_attachment_path = staticmethod(MemorystoreClient.network_attachment_path) + parse_network_attachment_path = staticmethod( + MemorystoreClient.parse_network_attachment_path + ) service_attachment_path = staticmethod(MemorystoreClient.service_attachment_path) parse_service_attachment_path = staticmethod( MemorystoreClient.parse_service_attachment_path @@ -107,6 +125,10 @@ class MemorystoreAsyncClient: parse_shared_regional_certificate_authority_path = staticmethod( MemorystoreClient.parse_shared_regional_certificate_authority_path ) + token_auth_user_path = staticmethod(MemorystoreClient.token_auth_user_path) + parse_token_auth_user_path = staticmethod( + MemorystoreClient.parse_token_auth_user_path + ) common_billing_account_path = staticmethod( MemorystoreClient.common_billing_account_path ) @@ -361,7 +383,7 @@ async def sample_list_instances(): Args: request (Optional[Union[google.cloud.memorystore_v1beta.types.ListInstancesRequest, dict]]): - The request object. Request message for [ListInstances][]. + The request object. Request message for ``ListInstances``. parent (:class:`str`): Required. The parent to list instances from. Format: @@ -380,7 +402,7 @@ async def sample_list_instances(): Returns: google.cloud.memorystore_v1beta.services.memorystore.pagers.ListInstancesAsyncPager: - Response message for [ListInstances][]. + Response message for ListInstances. Iterating over this object will yield results and resolve additional pages automatically. @@ -485,7 +507,7 @@ async def sample_get_instance(): Args: request (Optional[Union[google.cloud.memorystore_v1beta.types.GetInstanceRequest, dict]]): - The request object. Request message for [GetInstance][]. + The request object. Request message for ``GetInstance``. name (:class:`str`): Required. The name of the instance to retrieve. Format: @@ -585,15 +607,9 @@ async def sample_create_instance(): client = memorystore_v1beta.MemorystoreAsyncClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - request = memorystore_v1beta.CreateInstanceRequest( parent="parent_value", instance_id="instance_id_value", - instance=instance, ) # Make the request @@ -745,13 +761,7 @@ async def sample_update_instance(): client = memorystore_v1beta.MemorystoreAsyncClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - request = memorystore_v1beta.UpdateInstanceRequest( - instance=instance, ) # Make the request @@ -1033,7 +1043,7 @@ async def sample_get_certificate_authority(): Args: request (Optional[Union[google.cloud.memorystore_v1beta.types.GetCertificateAuthorityRequest, dict]]): - The request object. Request message for [GetCertificateAuthority][]. + The request object. Request message for ``GetCertificateAuthority``. name (:class:`str`): Required. The name of the certificate authority. Format: @@ -1148,8 +1158,7 @@ async def sample_get_shared_regional_certificate_authority(): Args: request (Optional[Union[google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest, dict]]): - The request object. Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. + The request object. Request for ``GetSharedRegionalCertificateAuthority``. name (:class:`str`): Required. Regional certificate authority resource name using the form: @@ -1224,6 +1233,2282 @@ async def sample_get_shared_regional_certificate_authority(): # Done; return the response. return response + async def reschedule_maintenance( + self, + request: Optional[Union[memorystore.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule_type: Optional[ + memorystore.RescheduleMaintenanceRequest.RescheduleType + ] = None, + schedule_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Reschedules upcoming maintenance event. + + .. 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 memorystore_v1beta + + async def sample_reschedule_maintenance(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.RescheduleMaintenanceRequest( + name="name_value", + reschedule_type="SPECIFIC_TIME", + ) + + # Make the request + operation = await client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest, dict]]): + The request object. Request for rescheduling instance + maintenance. + name (:class:`str`): + Required. Name of the instance to reschedule maintenance + for: + ``projects/{project}/locations/{location_id}/instances/{instance}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reschedule_type (:class:`google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest.RescheduleType`): + Required. If reschedule type is SPECIFIC_TIME, + schedule_time must be set. + + This corresponds to the ``reschedule_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schedule_time (:class:`google.protobuf.timestamp_pb2.Timestamp`): + Optional. Timestamp when the maintenance shall be + rescheduled to if reschedule_type=SPECIFIC_TIME, in RFC + 3339 format. Example: ``2012-11-15T16:19:00.094Z``. + + This corresponds to the ``schedule_time`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [name, reschedule_type, schedule_time] + 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, memorystore.RescheduleMaintenanceRequest): + request = memorystore.RescheduleMaintenanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if reschedule_type is not None: + request.reschedule_type = reschedule_type + if schedule_time is not None: + request.schedule_time = schedule_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.reschedule_maintenance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_backup_collections( + self, + request: Optional[Union[memorystore.ListBackupCollectionsRequest, dict]] = None, + *, + parent: 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.ListBackupCollectionsAsyncPager: + r"""Lists all backup collections owned by a consumer project in + either the specified location (region) or all locations. + + If ``location_id`` is specified as ``-`` (wildcard), then all + regions available to the project are queried, and the results + are aggregated. + + .. 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 memorystore_v1beta + + async def sample_list_backup_collections(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_collections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.ListBackupCollectionsRequest, dict]]): + The request object. Request for ``ListBackupCollections``. + parent (:class:`str`): + Required. The resource name of the backupCollection + location using the form: + ``projects/{project_id}/locations/{location_id}`` where + ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListBackupCollectionsAsyncPager: + Response for ListBackupCollections. + + 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 = [parent] + 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, memorystore.ListBackupCollectionsRequest): + request = memorystore.ListBackupCollectionsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backup_collections + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupCollectionsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup_collection( + self, + request: Optional[Union[memorystore.GetBackupCollectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.BackupCollection: + r"""Get a backup collection. + + .. 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 memorystore_v1beta + + async def sample_get_backup_collection(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupCollectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.GetBackupCollectionRequest, dict]]): + The request object. Request for ``GetBackupCollection``. + name (:class:`str`): + Required. Instance backupCollection resource name using + the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}`` + where ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.BackupCollection: + BackupCollection of an instance. + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetBackupCollectionRequest): + request = memorystore.GetBackupCollectionRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup_collection + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_backups( + self, + request: Optional[Union[memorystore.ListBackupsRequest, dict]] = None, + *, + parent: 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.ListBackupsAsyncPager: + r"""Lists all backups owned by a backup collection. + + .. 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 memorystore_v1beta + + async def sample_list_backups(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.ListBackupsRequest, dict]]): + The request object. Request for ``ListBackups``. + parent (:class:`str`): + Required. The resource name of the backupCollection + using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListBackupsAsyncPager: + Response for ListBackups. + + 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 = [parent] + 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, memorystore.ListBackupsRequest): + request = memorystore.ListBackupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_backups + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListBackupsAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_backup( + self, + request: Optional[Union[memorystore.GetBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.Backup: + r"""Gets the details of a specific backup. + + .. 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 memorystore_v1beta + + async def sample_get_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.GetBackupRequest, dict]]): + The request object. Request for ``GetBackup``. + name (:class:`str`): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.Backup: + Backup of an instance. + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetBackupRequest): + request = memorystore.GetBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def delete_backup( + self, + request: Optional[Union[memorystore.DeleteBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a specific backup. + + .. 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 memorystore_v1beta + + async def sample_delete_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.DeleteBackupRequest, dict]]): + The request object. Request for ``DeleteBackup``. + name (:class:`str`): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.DeleteBackupRequest): + request = memorystore.DeleteBackupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def export_backup( + self, + request: Optional[Union[memorystore.ExportBackupRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Exports a specific backup to a customer target Cloud + Storage URI. + + .. 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 memorystore_v1beta + + async def sample_export_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ExportBackupRequest( + gcs_bucket="gcs_bucket_value", + name="name_value", + ) + + # Make the request + operation = await client.export_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.ExportBackupRequest, dict]]): + The request object. Request for ``ExportBackup``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Backup` + Backup of an instance. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.ExportBackupRequest): + request = memorystore.ExportBackupRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.export_backup + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Backup, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def backup_instance( + self, + request: Optional[Union[memorystore.BackupInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Backup Instance. + If this is the first time a backup is being created, a + backup collection will be created at the backend, and + this backup belongs to this collection. Both collection + and backup will have a resource name. Backup will be + executed for each shard. A replica (primary if nonHA) + will be selected to perform the execution. Backup call + will be rejected if there is an ongoing backup or update + operation. Be aware that during preview, if the + instance's internal software version is too old, + critical update will be performed before actual backup. + Once the internal software version is updated to the + minimum version required by the backup feature, + subsequent backups will not require critical update. + After preview, there will be no critical update needed + for backup. + + .. 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 memorystore_v1beta + + async def sample_backup_instance(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.BackupInstanceRequest( + name="name_value", + ) + + # Make the request + operation = await client.backup_instance(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.BackupInstanceRequest, dict]]): + The request object. Request for ``BackupInstance``. + name (:class:`str`): + Required. Instance resource name using the form: + ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + where ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.BackupInstanceRequest): + request = memorystore.BackupInstanceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.backup_instance + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def start_migration( + self, + request: Optional[Union[memorystore.StartMigrationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + .. 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 memorystore_v1beta + + async def sample_start_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1beta.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1beta.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = await client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.StartMigrationRequest, dict]]): + The request object. Request for ``StartMigration``. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.StartMigrationRequest): + request = memorystore.StartMigrationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.start_migration + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def finish_migration( + self, + request: Optional[Union[memorystore.FinishMigrationRequest, dict]] = None, + *, + name: Optional[str] = None, + force: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + .. 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 memorystore_v1beta + + async def sample_finish_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = await client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.FinishMigrationRequest, dict]]): + The request object. Request for ``FinishMigration``. + name (:class:`str`): + Required. The resource name of the + instance to finalize migration on. + Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (:class:`bool`): + Optional. By default, the ``FinishMigration`` operation + ensures the target replication offset to catch up to the + source offset as of the time of the call. Set this field + to ``true`` to bypass this offset verification check. + + This corresponds to the ``force`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [name, force] + 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, memorystore.FinishMigrationRequest): + request = memorystore.FinishMigrationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.finish_migration + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def list_token_auth_users( + self, + request: Optional[Union[memorystore.ListTokenAuthUsersRequest, dict]] = None, + *, + parent: 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.ListTokenAuthUsersAsyncPager: + r"""Lists all the token auth users for a token based auth + enabled instance. + + .. 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 memorystore_v1beta + + async def sample_list_token_auth_users(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListTokenAuthUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_token_auth_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.ListTokenAuthUsersRequest, dict]]): + The request object. Request message for ``ListTokenAuthUsers``. + parent (:class:`str`): + Required. The parent to list token + auth users from. Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListTokenAuthUsersAsyncPager: + Response message for ListTokenAuthUsers. + + 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 = [parent] + 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, memorystore.ListTokenAuthUsersRequest): + request = memorystore.ListTokenAuthUsersRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_token_auth_users + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListTokenAuthUsersAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_token_auth_user( + self, + request: Optional[Union[memorystore.GetTokenAuthUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.TokenAuthUser: + r"""Gets a specific token auth user for a token based + auth enabled instance. + + .. 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 memorystore_v1beta + + async def sample_get_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_token_auth_user(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.GetTokenAuthUserRequest, dict]]): + The request object. Request message for ``GetTokenAuthUser``. + name (:class:`str`): + Required. The name of token auth user for a basic auth + enabled instance. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.TokenAuthUser: + Token based auth user for the + instance. + + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetTokenAuthUserRequest): + request = memorystore.GetTokenAuthUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_token_auth_user + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_auth_tokens( + self, + request: Optional[Union[memorystore.ListAuthTokensRequest, dict]] = None, + *, + parent: 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.ListAuthTokensAsyncPager: + r"""Lists all the auth tokens for a specific token auth + user. + + .. 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 memorystore_v1beta + + async def sample_list_auth_tokens(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListAuthTokensRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auth_tokens(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.ListAuthTokensRequest, dict]]): + The request object. Request message for ``ListAuthTokens``. + parent (:class:`str`): + Required. The parent to list auth tokens from. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListAuthTokensAsyncPager: + Response message for ListAuthTokens. + + 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 = [parent] + 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, memorystore.ListAuthTokensRequest): + request = memorystore.ListAuthTokensRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.list_auth_tokens + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAuthTokensAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_auth_token( + self, + request: Optional[Union[memorystore.GetAuthTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.AuthToken: + r"""Gets a token based auth enabled instance's auth token + for a given user. + + .. 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 memorystore_v1beta + + async def sample_get_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetAuthTokenRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auth_token(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.GetAuthTokenRequest, dict]]): + The request object. Request message for ``GetAuthToken``. + name (:class:`str`): + Required. The name of token auth user for a token auth + enabled instance. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{auth_token} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.AuthToken: + Auth token for the instance. + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetAuthTokenRequest): + request = memorystore.GetAuthTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.get_auth_token + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def add_token_auth_user( + self, + request: Optional[Union[memorystore.AddTokenAuthUserRequest, dict]] = None, + *, + instance: Optional[str] = None, + token_auth_user: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds a token auth user for a token based auth enabled + instance. + + .. 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 memorystore_v1beta + + async def sample_add_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddTokenAuthUserRequest( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = await client.add_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.AddTokenAuthUserRequest, dict]]): + The request object. Request message for ``AddTokenAuthUser``. + instance (:class:`str`): + Required. The instance resource that + this token auth user will be added for. + Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + token_auth_user (:class:`str`): + Required. The name of the token auth + user to add. + + This corresponds to the ``token_auth_user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [instance, token_auth_user] + 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, memorystore.AddTokenAuthUserRequest): + request = memorystore.AddTokenAuthUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + if token_auth_user is not None: + request.token_auth_user = token_auth_user + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.add_token_auth_user + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_token_auth_user( + self, + request: Optional[Union[memorystore.DeleteTokenAuthUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a token auth user for a token based auth + enabled instance. + + .. 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 memorystore_v1beta + + async def sample_delete_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.DeleteTokenAuthUserRequest, dict]]): + The request object. Request message for ``DeleteTokenAuthUser``. + name (:class:`str`): + Required. The name of the token auth user to delete. + Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.DeleteTokenAuthUserRequest): + request = memorystore.DeleteTokenAuthUserRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_token_auth_user + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def add_auth_token( + self, + request: Optional[Union[memorystore.AddAuthTokenRequest, dict]] = None, + *, + token_auth_user: Optional[str] = None, + auth_token: Optional[memorystore.AuthToken] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Adds a token for a user of a token based auth enabled + instance. + + .. 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 memorystore_v1beta + + async def sample_add_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddAuthTokenRequest( + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = await client.add_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.AddAuthTokenRequest, dict]]): + The request object. Request message for ``AddAuthToken``. + token_auth_user (:class:`str`): + Required. The name of the token auth + user resource that this token will be + added for. + + This corresponds to the ``token_auth_user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auth_token (:class:`google.cloud.memorystore_v1beta.types.AuthToken`): + Required. The auth token to add. + This corresponds to the ``auth_token`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.TokenAuthUser` + Token based auth user for the instance. + + """ + # 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 = [token_auth_user, auth_token] + 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, memorystore.AddAuthTokenRequest): + request = memorystore.AddAuthTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if token_auth_user is not None: + request.token_auth_user = token_auth_user + if auth_token is not None: + request.auth_token = auth_token + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.add_auth_token + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("token_auth_user", request.token_auth_user),) + ), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + memorystore.TokenAuthUser, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + async def delete_auth_token( + self, + request: Optional[Union[memorystore.DeleteAuthTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation_async.AsyncOperation: + r"""Deletes a token for a user of a token based auth + enabled instance. + + .. 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 memorystore_v1beta + + async def sample_delete_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteAuthTokenRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.memorystore_v1beta.types.DeleteAuthTokenRequest, dict]]): + The request object. Request message for ``DeleteAuthToken``. + name (:class:`str`): + Required. The name of the token auth user resource that + this token will be deleted from. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{name} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.DeleteAuthTokenRequest): + request = memorystore.DeleteAuthTokenRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.delete_auth_token + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty_pb2.Empty, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[Union[operations_pb2.ListOperationsRequest, dict]] = None, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py index 3b5e21519c13..65704c8b1353 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/client.py @@ -234,6 +234,78 @@ def transport(self) -> MemorystoreTransport: """ return self._transport + @staticmethod + def auth_token_path( + project: str, + location: str, + instance: str, + token_auth_user: str, + auth_token: str, + ) -> str: + """Returns a fully-qualified auth_token string.""" + return "projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{auth_token}".format( + project=project, + location=location, + instance=instance, + token_auth_user=token_auth_user, + auth_token=auth_token, + ) + + @staticmethod + def parse_auth_token_path(path: str) -> Dict[str, str]: + """Parses a auth_token path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/tokenAuthUsers/(?P.+?)/authTokens/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_path( + project: str, + location: str, + backup_collection: str, + backup: str, + ) -> str: + """Returns a fully-qualified backup string.""" + return "projects/{project}/locations/{location}/backupCollections/{backup_collection}/backups/{backup}".format( + project=project, + location=location, + backup_collection=backup_collection, + backup=backup, + ) + + @staticmethod + def parse_backup_path(path: str) -> Dict[str, str]: + """Parses a backup path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupCollections/(?P.+?)/backups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def backup_collection_path( + project: str, + location: str, + backup_collection: str, + ) -> str: + """Returns a fully-qualified backup_collection string.""" + return "projects/{project}/locations/{location}/backupCollections/{backup_collection}".format( + project=project, + location=location, + backup_collection=backup_collection, + ) + + @staticmethod + def parse_backup_collection_path(path: str) -> Dict[str, str]: + """Parses a backup_collection path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/backupCollections/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def ca_pool_path( project: str, @@ -278,6 +350,56 @@ def parse_certificate_authority_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def crypto_key_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + ) -> str: + """Returns a fully-qualified crypto_key string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + + @staticmethod + def parse_crypto_key_path(path: str) -> Dict[str, str]: + """Parses a crypto_key path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def crypto_key_version_path( + project: str, + location: str, + key_ring: str, + crypto_key: str, + crypto_key_version: str, + ) -> str: + """Returns a fully-qualified crypto_key_version string.""" + return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + + @staticmethod + def parse_crypto_key_version_path(path: str) -> Dict[str, str]: + """Parses a crypto_key_version path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/keyRings/(?P.+?)/cryptoKeys/(?P.+?)/cryptoKeyVersions/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def forwarding_rule_path( project: str, @@ -341,6 +463,28 @@ def parse_network_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def network_attachment_path( + project: str, + region: str, + network_attachment: str, + ) -> str: + """Returns a fully-qualified network_attachment string.""" + return "projects/{project}/regions/{region}/networkAttachments/{network_attachment}".format( + project=project, + region=region, + network_attachment=network_attachment, + ) + + @staticmethod + def parse_network_attachment_path(path: str) -> Dict[str, str]: + """Parses a network_attachment path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/regions/(?P.+?)/networkAttachments/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def service_attachment_path( project: str, @@ -383,6 +527,30 @@ def parse_shared_regional_certificate_authority_path(path: str) -> Dict[str, str ) return m.groupdict() if m else {} + @staticmethod + def token_auth_user_path( + project: str, + location: str, + instance: str, + token_auth_user: str, + ) -> str: + """Returns a fully-qualified token_auth_user string.""" + return "projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}".format( + project=project, + location=location, + instance=instance, + token_auth_user=token_auth_user, + ) + + @staticmethod + def parse_token_auth_user_path(path: str) -> Dict[str, str]: + """Parses a token_auth_user path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/instances/(?P.+?)/tokenAuthUsers/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def common_billing_account_path( billing_account: str, @@ -899,7 +1067,7 @@ def sample_list_instances(): Args: request (Union[google.cloud.memorystore_v1beta.types.ListInstancesRequest, dict]): - The request object. Request message for [ListInstances][]. + The request object. Request message for ``ListInstances``. parent (str): Required. The parent to list instances from. Format: @@ -918,7 +1086,7 @@ def sample_list_instances(): Returns: google.cloud.memorystore_v1beta.services.memorystore.pagers.ListInstancesPager: - Response message for [ListInstances][]. + Response message for ListInstances. Iterating over this object will yield results and resolve additional pages automatically. @@ -1020,7 +1188,7 @@ def sample_get_instance(): Args: request (Union[google.cloud.memorystore_v1beta.types.GetInstanceRequest, dict]): - The request object. Request message for [GetInstance][]. + The request object. Request message for ``GetInstance``. name (str): Required. The name of the instance to retrieve. Format: @@ -1117,15 +1285,9 @@ def sample_create_instance(): client = memorystore_v1beta.MemorystoreClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - request = memorystore_v1beta.CreateInstanceRequest( parent="parent_value", instance_id="instance_id_value", - instance=instance, ) # Make the request @@ -1274,13 +1436,7 @@ def sample_update_instance(): client = memorystore_v1beta.MemorystoreClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - request = memorystore_v1beta.UpdateInstanceRequest( - instance=instance, ) # Make the request @@ -1556,7 +1712,7 @@ def sample_get_certificate_authority(): Args: request (Union[google.cloud.memorystore_v1beta.types.GetCertificateAuthorityRequest, dict]): - The request object. Request message for [GetCertificateAuthority][]. + The request object. Request message for ``GetCertificateAuthority``. name (str): Required. The name of the certificate authority. Format: @@ -1670,8 +1826,7 @@ def sample_get_shared_regional_certificate_authority(): Args: request (Union[google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest, dict]): - The request object. Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. + The request object. Request for ``GetSharedRegionalCertificateAuthority``. name (str): Required. Regional certificate authority resource name using the form: @@ -1745,6 +1900,2230 @@ def sample_get_shared_regional_certificate_authority(): # Done; return the response. return response + def reschedule_maintenance( + self, + request: Optional[Union[memorystore.RescheduleMaintenanceRequest, dict]] = None, + *, + name: Optional[str] = None, + reschedule_type: Optional[ + memorystore.RescheduleMaintenanceRequest.RescheduleType + ] = None, + schedule_time: Optional[timestamp_pb2.Timestamp] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Reschedules upcoming maintenance event. + + .. 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 memorystore_v1beta + + def sample_reschedule_maintenance(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.RescheduleMaintenanceRequest( + name="name_value", + reschedule_type="SPECIFIC_TIME", + ) + + # Make the request + operation = client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest, dict]): + The request object. Request for rescheduling instance + maintenance. + name (str): + Required. Name of the instance to reschedule maintenance + for: + ``projects/{project}/locations/{location_id}/instances/{instance}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + reschedule_type (google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest.RescheduleType): + Required. If reschedule type is SPECIFIC_TIME, + schedule_time must be set. + + This corresponds to the ``reschedule_type`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Timestamp when the maintenance shall be + rescheduled to if reschedule_type=SPECIFIC_TIME, in RFC + 3339 format. Example: ``2012-11-15T16:19:00.094Z``. + + This corresponds to the ``schedule_time`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [name, reschedule_type, schedule_time] + 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, memorystore.RescheduleMaintenanceRequest): + request = memorystore.RescheduleMaintenanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if reschedule_type is not None: + request.reschedule_type = reschedule_type + if schedule_time is not None: + request.schedule_time = schedule_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.reschedule_maintenance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_backup_collections( + self, + request: Optional[Union[memorystore.ListBackupCollectionsRequest, dict]] = None, + *, + parent: 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.ListBackupCollectionsPager: + r"""Lists all backup collections owned by a consumer project in + either the specified location (region) or all locations. + + If ``location_id`` is specified as ``-`` (wildcard), then all + regions available to the project are queried, and the results + are aggregated. + + .. 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 memorystore_v1beta + + def sample_list_backup_collections(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_collections(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.ListBackupCollectionsRequest, dict]): + The request object. Request for ``ListBackupCollections``. + parent (str): + Required. The resource name of the backupCollection + location using the form: + ``projects/{project_id}/locations/{location_id}`` where + ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListBackupCollectionsPager: + Response for ListBackupCollections. + + 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 = [parent] + 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, memorystore.ListBackupCollectionsRequest): + request = memorystore.ListBackupCollectionsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_backup_collections] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupCollectionsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup_collection( + self, + request: Optional[Union[memorystore.GetBackupCollectionRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.BackupCollection: + r"""Get a backup collection. + + .. 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 memorystore_v1beta + + def sample_get_backup_collection(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupCollectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_collection(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.GetBackupCollectionRequest, dict]): + The request object. Request for ``GetBackupCollection``. + name (str): + Required. Instance backupCollection resource name using + the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}`` + where ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.BackupCollection: + BackupCollection of an instance. + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetBackupCollectionRequest): + request = memorystore.GetBackupCollectionRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_backup_collection] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_backups( + self, + request: Optional[Union[memorystore.ListBackupsRequest, dict]] = None, + *, + parent: 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.ListBackupsPager: + r"""Lists all backups owned by a backup collection. + + .. 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 memorystore_v1beta + + def sample_list_backups(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.ListBackupsRequest, dict]): + The request object. Request for ``ListBackups``. + parent (str): + Required. The resource name of the backupCollection + using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}`` + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListBackupsPager: + Response for ListBackups. + + 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 = [parent] + 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, memorystore.ListBackupsRequest): + request = memorystore.ListBackupsRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_backups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListBackupsPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_backup( + self, + request: Optional[Union[memorystore.GetBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.Backup: + r"""Gets the details of a specific backup. + + .. 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 memorystore_v1beta + + def sample_get_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.GetBackupRequest, dict]): + The request object. Request for ``GetBackup``. + name (str): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.Backup: + Backup of an instance. + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetBackupRequest): + request = memorystore.GetBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def delete_backup( + self, + request: Optional[Union[memorystore.DeleteBackupRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a specific backup. + + .. 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 memorystore_v1beta + + def sample_delete_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.DeleteBackupRequest, dict]): + The request object. Request for ``DeleteBackup``. + name (str): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.DeleteBackupRequest): + request = memorystore.DeleteBackupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def export_backup( + self, + request: Optional[Union[memorystore.ExportBackupRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Exports a specific backup to a customer target Cloud + Storage URI. + + .. 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 memorystore_v1beta + + def sample_export_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ExportBackupRequest( + gcs_bucket="gcs_bucket_value", + name="name_value", + ) + + # Make the request + operation = client.export_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.ExportBackupRequest, dict]): + The request object. Request for ``ExportBackup``. + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Backup` + Backup of an instance. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.ExportBackupRequest): + request = memorystore.ExportBackupRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.export_backup] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Backup, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def backup_instance( + self, + request: Optional[Union[memorystore.BackupInstanceRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Backup Instance. + If this is the first time a backup is being created, a + backup collection will be created at the backend, and + this backup belongs to this collection. Both collection + and backup will have a resource name. Backup will be + executed for each shard. A replica (primary if nonHA) + will be selected to perform the execution. Backup call + will be rejected if there is an ongoing backup or update + operation. Be aware that during preview, if the + instance's internal software version is too old, + critical update will be performed before actual backup. + Once the internal software version is updated to the + minimum version required by the backup feature, + subsequent backups will not require critical update. + After preview, there will be no critical update needed + for backup. + + .. 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 memorystore_v1beta + + def sample_backup_instance(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.BackupInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.backup_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.BackupInstanceRequest, dict]): + The request object. Request for ``BackupInstance``. + name (str): + Required. Instance resource name using the form: + ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + where ``location_id`` refers to a Google Cloud region. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.BackupInstanceRequest): + request = memorystore.BackupInstanceRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.backup_instance] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def start_migration( + self, + request: Optional[Union[memorystore.StartMigrationRequest, dict]] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + .. 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 memorystore_v1beta + + def sample_start_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1beta.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1beta.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.StartMigrationRequest, dict]): + The request object. Request for ``StartMigration``. + 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # Create or coerce a protobuf request object. + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.StartMigrationRequest): + request = memorystore.StartMigrationRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.start_migration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def finish_migration( + self, + request: Optional[Union[memorystore.FinishMigrationRequest, dict]] = None, + *, + name: Optional[str] = None, + force: Optional[bool] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + .. 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 memorystore_v1beta + + def sample_finish_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.FinishMigrationRequest, dict]): + The request object. Request for ``FinishMigration``. + name (str): + Required. The resource name of the + instance to finalize migration on. + Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + force (bool): + Optional. By default, the ``FinishMigration`` operation + ensures the target replication offset to catch up to the + source offset as of the time of the call. Set this field + to ``true`` to bypass this offset verification check. + + This corresponds to the ``force`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [name, force] + 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, memorystore.FinishMigrationRequest): + request = memorystore.FinishMigrationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if force is not None: + request.force = force + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.finish_migration] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def list_token_auth_users( + self, + request: Optional[Union[memorystore.ListTokenAuthUsersRequest, dict]] = None, + *, + parent: 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.ListTokenAuthUsersPager: + r"""Lists all the token auth users for a token based auth + enabled instance. + + .. 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 memorystore_v1beta + + def sample_list_token_auth_users(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListTokenAuthUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_token_auth_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.ListTokenAuthUsersRequest, dict]): + The request object. Request message for ``ListTokenAuthUsers``. + parent (str): + Required. The parent to list token + auth users from. Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListTokenAuthUsersPager: + Response message for ListTokenAuthUsers. + + 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 = [parent] + 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, memorystore.ListTokenAuthUsersRequest): + request = memorystore.ListTokenAuthUsersRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_token_auth_users] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListTokenAuthUsersPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_token_auth_user( + self, + request: Optional[Union[memorystore.GetTokenAuthUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.TokenAuthUser: + r"""Gets a specific token auth user for a token based + auth enabled instance. + + .. 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 memorystore_v1beta + + def sample_get_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_token_auth_user(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.GetTokenAuthUserRequest, dict]): + The request object. Request message for ``GetTokenAuthUser``. + name (str): + Required. The name of token auth user for a basic auth + enabled instance. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.TokenAuthUser: + Token based auth user for the + instance. + + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetTokenAuthUserRequest): + request = memorystore.GetTokenAuthUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_token_auth_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_auth_tokens( + self, + request: Optional[Union[memorystore.ListAuthTokensRequest, dict]] = None, + *, + parent: 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.ListAuthTokensPager: + r"""Lists all the auth tokens for a specific token auth + user. + + .. 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 memorystore_v1beta + + def sample_list_auth_tokens(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListAuthTokensRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auth_tokens(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.ListAuthTokensRequest, dict]): + The request object. Request message for ``ListAuthTokens``. + parent (str): + Required. The parent to list auth tokens from. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.services.memorystore.pagers.ListAuthTokensPager: + Response message for ListAuthTokens. + + 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 = [parent] + 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, memorystore.ListAuthTokensRequest): + request = memorystore.ListAuthTokensRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_auth_tokens] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAuthTokensPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_auth_token( + self, + request: Optional[Union[memorystore.GetAuthTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.AuthToken: + r"""Gets a token based auth enabled instance's auth token + for a given user. + + .. 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 memorystore_v1beta + + def sample_get_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetAuthTokenRequest( + name="name_value", + ) + + # Make the request + response = client.get_auth_token(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.GetAuthTokenRequest, dict]): + The request object. Request message for ``GetAuthToken``. + name (str): + Required. The name of token auth user for a token auth + enabled instance. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{auth_token} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.memorystore_v1beta.types.AuthToken: + Auth token for the instance. + """ + # 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 = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.GetAuthTokenRequest): + request = memorystore.GetAuthTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_auth_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def add_token_auth_user( + self, + request: Optional[Union[memorystore.AddTokenAuthUserRequest, dict]] = None, + *, + instance: Optional[str] = None, + token_auth_user: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Adds a token auth user for a token based auth enabled + instance. + + .. 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 memorystore_v1beta + + def sample_add_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddTokenAuthUserRequest( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = client.add_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.AddTokenAuthUserRequest, dict]): + The request object. Request message for ``AddTokenAuthUser``. + instance (str): + Required. The instance resource that + this token auth user will be added for. + Format: + projects/{project}/locations/{location}/instances/{instance} + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + token_auth_user (str): + Required. The name of the token auth + user to add. + + This corresponds to the ``token_auth_user`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.Instance` + A Memorystore instance. + + """ + # 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 = [instance, token_auth_user] + 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, memorystore.AddTokenAuthUserRequest): + request = memorystore.AddTokenAuthUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + if token_auth_user is not None: + request.token_auth_user = token_auth_user + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_token_auth_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.Instance, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_token_auth_user( + self, + request: Optional[Union[memorystore.DeleteTokenAuthUserRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a token auth user for a token based auth + enabled instance. + + .. 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 memorystore_v1beta + + def sample_delete_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.DeleteTokenAuthUserRequest, dict]): + The request object. Request message for ``DeleteTokenAuthUser``. + name (str): + Required. The name of the token auth user to delete. + Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.DeleteTokenAuthUserRequest): + request = memorystore.DeleteTokenAuthUserRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_token_auth_user] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def add_auth_token( + self, + request: Optional[Union[memorystore.AddAuthTokenRequest, dict]] = None, + *, + token_auth_user: Optional[str] = None, + auth_token: Optional[memorystore.AuthToken] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Adds a token for a user of a token based auth enabled + instance. + + .. 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 memorystore_v1beta + + def sample_add_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddAuthTokenRequest( + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = client.add_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.AddAuthTokenRequest, dict]): + The request object. Request message for ``AddAuthToken``. + token_auth_user (str): + Required. The name of the token auth + user resource that this token will be + added for. + + This corresponds to the ``token_auth_user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + auth_token (google.cloud.memorystore_v1beta.types.AuthToken): + Required. The auth token to add. + This corresponds to the ``auth_token`` 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:`google.cloud.memorystore_v1beta.types.TokenAuthUser` + Token based auth user for the instance. + + """ + # 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 = [token_auth_user, auth_token] + 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, memorystore.AddAuthTokenRequest): + request = memorystore.AddAuthTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if token_auth_user is not None: + request.token_auth_user = token_auth_user + if auth_token is not None: + request.auth_token = auth_token + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.add_auth_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("token_auth_user", request.token_auth_user),) + ), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + memorystore.TokenAuthUser, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_auth_token( + self, + request: Optional[Union[memorystore.DeleteAuthTokenRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operation.Operation: + r"""Deletes a token for a user of a token based auth + enabled instance. + + .. 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 memorystore_v1beta + + def sample_delete_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteAuthTokenRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.memorystore_v1beta.types.DeleteAuthTokenRequest, dict]): + The request object. Request message for ``DeleteAuthToken``. + name (str): + Required. The name of the token auth user resource that + this token will be deleted from. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{name} + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # Create or coerce a protobuf request object. + # - Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + flattened_params = [name] + has_flattened_params = ( + len([param for param in flattened_params if param is not None]) > 0 + ) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, memorystore.DeleteAuthTokenRequest): + request = memorystore.DeleteAuthTokenRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_auth_token] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=memorystore.OperationMetadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "MemorystoreClient": return self diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/pagers.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/pagers.py index 01ee3650d73e..40df8d92354a 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/pagers.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/pagers.py @@ -195,3 +195,627 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupCollectionsPager: + """A pager for iterating through ``list_backup_collections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListBackupCollectionsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backup_collections`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackupCollections`` requests and continue to iterate + through the ``backup_collections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListBackupCollectionsResponse` + 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[..., memorystore.ListBackupCollectionsResponse], + request: memorystore.ListBackupCollectionsRequest, + response: memorystore.ListBackupCollectionsResponse, + *, + 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.memorystore_v1beta.types.ListBackupCollectionsRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListBackupCollectionsResponse): + 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 = memorystore.ListBackupCollectionsRequest(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[memorystore.ListBackupCollectionsResponse]: + 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[memorystore.BackupCollection]: + for page in self.pages: + yield from page.backup_collections + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupCollectionsAsyncPager: + """A pager for iterating through ``list_backup_collections`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListBackupCollectionsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backup_collections`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackupCollections`` requests and continue to iterate + through the ``backup_collections`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListBackupCollectionsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[memorystore.ListBackupCollectionsResponse]], + request: memorystore.ListBackupCollectionsRequest, + response: memorystore.ListBackupCollectionsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.memorystore_v1beta.types.ListBackupCollectionsRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListBackupCollectionsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): 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 = memorystore.ListBackupCollectionsRequest(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 + async def pages(self) -> AsyncIterator[memorystore.ListBackupCollectionsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[memorystore.BackupCollection]: + async def async_generator(): + async for page in self.pages: + for response in page.backup_collections: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupsPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListBackupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListBackupsResponse` + 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[..., memorystore.ListBackupsResponse], + request: memorystore.ListBackupsRequest, + response: memorystore.ListBackupsResponse, + *, + 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.memorystore_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListBackupsResponse): + 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 = memorystore.ListBackupsRequest(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[memorystore.ListBackupsResponse]: + 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[memorystore.Backup]: + for page in self.pages: + yield from page.backups + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListBackupsAsyncPager: + """A pager for iterating through ``list_backups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListBackupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``backups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListBackups`` requests and continue to iterate + through the ``backups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListBackupsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[memorystore.ListBackupsResponse]], + request: memorystore.ListBackupsRequest, + response: memorystore.ListBackupsResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.memorystore_v1beta.types.ListBackupsRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListBackupsResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): 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 = memorystore.ListBackupsRequest(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 + async def pages(self) -> AsyncIterator[memorystore.ListBackupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[memorystore.Backup]: + async def async_generator(): + async for page in self.pages: + for response in page.backups: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTokenAuthUsersPager: + """A pager for iterating through ``list_token_auth_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListTokenAuthUsersResponse` object, and + provides an ``__iter__`` method to iterate through its + ``token_auth_users`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListTokenAuthUsers`` requests and continue to iterate + through the ``token_auth_users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListTokenAuthUsersResponse` + 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[..., memorystore.ListTokenAuthUsersResponse], + request: memorystore.ListTokenAuthUsersRequest, + response: memorystore.ListTokenAuthUsersResponse, + *, + 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.memorystore_v1beta.types.ListTokenAuthUsersRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListTokenAuthUsersResponse): + 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 = memorystore.ListTokenAuthUsersRequest(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[memorystore.ListTokenAuthUsersResponse]: + 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[memorystore.TokenAuthUser]: + for page in self.pages: + yield from page.token_auth_users + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListTokenAuthUsersAsyncPager: + """A pager for iterating through ``list_token_auth_users`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListTokenAuthUsersResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``token_auth_users`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListTokenAuthUsers`` requests and continue to iterate + through the ``token_auth_users`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListTokenAuthUsersResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[memorystore.ListTokenAuthUsersResponse]], + request: memorystore.ListTokenAuthUsersRequest, + response: memorystore.ListTokenAuthUsersResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.memorystore_v1beta.types.ListTokenAuthUsersRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListTokenAuthUsersResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): 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 = memorystore.ListTokenAuthUsersRequest(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 + async def pages(self) -> AsyncIterator[memorystore.ListTokenAuthUsersResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[memorystore.TokenAuthUser]: + async def async_generator(): + async for page in self.pages: + for response in page.token_auth_users: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAuthTokensPager: + """A pager for iterating through ``list_auth_tokens`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListAuthTokensResponse` object, and + provides an ``__iter__`` method to iterate through its + ``auth_tokens`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAuthTokens`` requests and continue to iterate + through the ``auth_tokens`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListAuthTokensResponse` + 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[..., memorystore.ListAuthTokensResponse], + request: memorystore.ListAuthTokensRequest, + response: memorystore.ListAuthTokensResponse, + *, + 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.memorystore_v1beta.types.ListAuthTokensRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListAuthTokensResponse): + 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 = memorystore.ListAuthTokensRequest(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[memorystore.ListAuthTokensResponse]: + 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[memorystore.AuthToken]: + for page in self.pages: + yield from page.auth_tokens + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAuthTokensAsyncPager: + """A pager for iterating through ``list_auth_tokens`` requests. + + This class thinly wraps an initial + :class:`google.cloud.memorystore_v1beta.types.ListAuthTokensResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``auth_tokens`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAuthTokens`` requests and continue to iterate + through the ``auth_tokens`` field on the + corresponding responses. + + All the usual :class:`google.cloud.memorystore_v1beta.types.ListAuthTokensResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[memorystore.ListAuthTokensResponse]], + request: memorystore.ListAuthTokensRequest, + response: memorystore.ListAuthTokensResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.memorystore_v1beta.types.ListAuthTokensRequest): + The initial request object. + response (google.cloud.memorystore_v1beta.types.ListAuthTokensResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): 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 = memorystore.ListAuthTokensRequest(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 + async def pages(self) -> AsyncIterator[memorystore.ListAuthTokensResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[memorystore.AuthToken]: + async def async_generator(): + async for page in self.pages: + for response in page.auth_tokens: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py index 82b6cecb8d2b..281c762c8a37 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/base.py @@ -41,7 +41,11 @@ class MemorystoreTransport(abc.ABC): """Abstract transport class for Memorystore.""" - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + AUTH_SCOPES = ( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ) DEFAULT_HOST: str = "memorystore.googleapis.com" @@ -206,6 +210,96 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.reschedule_maintenance: gapic_v1.method.wrap_method( + self.reschedule_maintenance, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_collections: gapic_v1.method.wrap_method( + self.list_backup_collections, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_collection: gapic_v1.method.wrap_method( + self.get_backup_collection, + default_timeout=None, + client_info=client_info, + ), + self.list_backups: gapic_v1.method.wrap_method( + self.list_backups, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: gapic_v1.method.wrap_method( + self.get_backup, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup: gapic_v1.method.wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.export_backup: gapic_v1.method.wrap_method( + self.export_backup, + default_timeout=None, + client_info=client_info, + ), + self.backup_instance: gapic_v1.method.wrap_method( + self.backup_instance, + default_timeout=None, + client_info=client_info, + ), + self.start_migration: gapic_v1.method.wrap_method( + self.start_migration, + default_timeout=None, + client_info=client_info, + ), + self.finish_migration: gapic_v1.method.wrap_method( + self.finish_migration, + default_timeout=None, + client_info=client_info, + ), + self.list_token_auth_users: gapic_v1.method.wrap_method( + self.list_token_auth_users, + default_timeout=None, + client_info=client_info, + ), + self.get_token_auth_user: gapic_v1.method.wrap_method( + self.get_token_auth_user, + default_timeout=None, + client_info=client_info, + ), + self.list_auth_tokens: gapic_v1.method.wrap_method( + self.list_auth_tokens, + default_timeout=None, + client_info=client_info, + ), + self.get_auth_token: gapic_v1.method.wrap_method( + self.get_auth_token, + default_timeout=None, + client_info=client_info, + ), + self.add_token_auth_user: gapic_v1.method.wrap_method( + self.add_token_auth_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_token_auth_user: gapic_v1.method.wrap_method( + self.delete_token_auth_user, + default_timeout=None, + client_info=client_info, + ), + self.add_auth_token: gapic_v1.method.wrap_method( + self.add_auth_token, + default_timeout=None, + client_info=client_info, + ), + self.delete_auth_token: gapic_v1.method.wrap_method( + self.delete_auth_token, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -324,6 +418,179 @@ def get_shared_regional_certificate_authority( ]: raise NotImplementedError() + @property + def reschedule_maintenance( + self, + ) -> Callable[ + [memorystore.RescheduleMaintenanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_backup_collections( + self, + ) -> Callable[ + [memorystore.ListBackupCollectionsRequest], + Union[ + memorystore.ListBackupCollectionsResponse, + Awaitable[memorystore.ListBackupCollectionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_backup_collection( + self, + ) -> Callable[ + [memorystore.GetBackupCollectionRequest], + Union[memorystore.BackupCollection, Awaitable[memorystore.BackupCollection]], + ]: + raise NotImplementedError() + + @property + def list_backups( + self, + ) -> Callable[ + [memorystore.ListBackupsRequest], + Union[ + memorystore.ListBackupsResponse, Awaitable[memorystore.ListBackupsResponse] + ], + ]: + raise NotImplementedError() + + @property + def get_backup( + self, + ) -> Callable[ + [memorystore.GetBackupRequest], + Union[memorystore.Backup, Awaitable[memorystore.Backup]], + ]: + raise NotImplementedError() + + @property + def delete_backup( + self, + ) -> Callable[ + [memorystore.DeleteBackupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def export_backup( + self, + ) -> Callable[ + [memorystore.ExportBackupRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def backup_instance( + self, + ) -> Callable[ + [memorystore.BackupInstanceRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def start_migration( + self, + ) -> Callable[ + [memorystore.StartMigrationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def finish_migration( + self, + ) -> Callable[ + [memorystore.FinishMigrationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def list_token_auth_users( + self, + ) -> Callable[ + [memorystore.ListTokenAuthUsersRequest], + Union[ + memorystore.ListTokenAuthUsersResponse, + Awaitable[memorystore.ListTokenAuthUsersResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_token_auth_user( + self, + ) -> Callable[ + [memorystore.GetTokenAuthUserRequest], + Union[memorystore.TokenAuthUser, Awaitable[memorystore.TokenAuthUser]], + ]: + raise NotImplementedError() + + @property + def list_auth_tokens( + self, + ) -> Callable[ + [memorystore.ListAuthTokensRequest], + Union[ + memorystore.ListAuthTokensResponse, + Awaitable[memorystore.ListAuthTokensResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_auth_token( + self, + ) -> Callable[ + [memorystore.GetAuthTokenRequest], + Union[memorystore.AuthToken, Awaitable[memorystore.AuthToken]], + ]: + raise NotImplementedError() + + @property + def add_token_auth_user( + self, + ) -> Callable[ + [memorystore.AddTokenAuthUserRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_token_auth_user( + self, + ) -> Callable[ + [memorystore.DeleteTokenAuthUserRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def add_auth_token( + self, + ) -> Callable[ + [memorystore.AddAuthTokenRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def delete_auth_token( + self, + ) -> Callable[ + [memorystore.DeleteAuthTokenRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc.py index f5210fb646d2..367e11e3afa5 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc.py @@ -539,6 +539,526 @@ def get_shared_regional_certificate_authority( ) return self._stubs["get_shared_regional_certificate_authority"] + @property + def reschedule_maintenance( + self, + ) -> Callable[[memorystore.RescheduleMaintenanceRequest], operations_pb2.Operation]: + r"""Return a callable for the reschedule maintenance method over gRPC. + + Reschedules upcoming maintenance event. + + Returns: + Callable[[~.RescheduleMaintenanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "reschedule_maintenance" not in self._stubs: + self._stubs["reschedule_maintenance"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/RescheduleMaintenance", + request_serializer=memorystore.RescheduleMaintenanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reschedule_maintenance"] + + @property + def list_backup_collections( + self, + ) -> Callable[ + [memorystore.ListBackupCollectionsRequest], + memorystore.ListBackupCollectionsResponse, + ]: + r"""Return a callable for the list backup collections method over gRPC. + + Lists all backup collections owned by a consumer project in + either the specified location (region) or all locations. + + If ``location_id`` is specified as ``-`` (wildcard), then all + regions available to the project are queried, and the results + are aggregated. + + Returns: + Callable[[~.ListBackupCollectionsRequest], + ~.ListBackupCollectionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_collections" not in self._stubs: + self._stubs["list_backup_collections"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListBackupCollections", + request_serializer=memorystore.ListBackupCollectionsRequest.serialize, + response_deserializer=memorystore.ListBackupCollectionsResponse.deserialize, + ) + return self._stubs["list_backup_collections"] + + @property + def get_backup_collection( + self, + ) -> Callable[ + [memorystore.GetBackupCollectionRequest], memorystore.BackupCollection + ]: + r"""Return a callable for the get backup collection method over gRPC. + + Get a backup collection. + + Returns: + Callable[[~.GetBackupCollectionRequest], + ~.BackupCollection]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_collection" not in self._stubs: + self._stubs["get_backup_collection"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetBackupCollection", + request_serializer=memorystore.GetBackupCollectionRequest.serialize, + response_deserializer=memorystore.BackupCollection.deserialize, + ) + return self._stubs["get_backup_collection"] + + @property + def list_backups( + self, + ) -> Callable[[memorystore.ListBackupsRequest], memorystore.ListBackupsResponse]: + r"""Return a callable for the list backups method over gRPC. + + Lists all backups owned by a backup collection. + + Returns: + Callable[[~.ListBackupsRequest], + ~.ListBackupsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backups" not in self._stubs: + self._stubs["list_backups"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListBackups", + request_serializer=memorystore.ListBackupsRequest.serialize, + response_deserializer=memorystore.ListBackupsResponse.deserialize, + ) + return self._stubs["list_backups"] + + @property + def get_backup( + self, + ) -> Callable[[memorystore.GetBackupRequest], memorystore.Backup]: + r"""Return a callable for the get backup method over gRPC. + + Gets the details of a specific backup. + + Returns: + Callable[[~.GetBackupRequest], + ~.Backup]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup" not in self._stubs: + self._stubs["get_backup"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetBackup", + request_serializer=memorystore.GetBackupRequest.serialize, + response_deserializer=memorystore.Backup.deserialize, + ) + return self._stubs["get_backup"] + + @property + def delete_backup( + self, + ) -> Callable[[memorystore.DeleteBackupRequest], operations_pb2.Operation]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a specific backup. + + Returns: + Callable[[~.DeleteBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup" not in self._stubs: + self._stubs["delete_backup"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/DeleteBackup", + request_serializer=memorystore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup"] + + @property + def export_backup( + self, + ) -> Callable[[memorystore.ExportBackupRequest], operations_pb2.Operation]: + r"""Return a callable for the export backup method over gRPC. + + Exports a specific backup to a customer target Cloud + Storage URI. + + Returns: + Callable[[~.ExportBackupRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_backup" not in self._stubs: + self._stubs["export_backup"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ExportBackup", + request_serializer=memorystore.ExportBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_backup"] + + @property + def backup_instance( + self, + ) -> Callable[[memorystore.BackupInstanceRequest], operations_pb2.Operation]: + r"""Return a callable for the backup instance method over gRPC. + + Backup Instance. + If this is the first time a backup is being created, a + backup collection will be created at the backend, and + this backup belongs to this collection. Both collection + and backup will have a resource name. Backup will be + executed for each shard. A replica (primary if nonHA) + will be selected to perform the execution. Backup call + will be rejected if there is an ongoing backup or update + operation. Be aware that during preview, if the + instance's internal software version is too old, + critical update will be performed before actual backup. + Once the internal software version is updated to the + minimum version required by the backup feature, + subsequent backups will not require critical update. + After preview, there will be no critical update needed + for backup. + + Returns: + Callable[[~.BackupInstanceRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "backup_instance" not in self._stubs: + self._stubs["backup_instance"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/BackupInstance", + request_serializer=memorystore.BackupInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["backup_instance"] + + @property + def start_migration( + self, + ) -> Callable[[memorystore.StartMigrationRequest], operations_pb2.Operation]: + r"""Return a callable for the start migration method over gRPC. + + Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + Returns: + Callable[[~.StartMigrationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "start_migration" not in self._stubs: + self._stubs["start_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/StartMigration", + request_serializer=memorystore.StartMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_migration"] + + @property + def finish_migration( + self, + ) -> Callable[[memorystore.FinishMigrationRequest], operations_pb2.Operation]: + r"""Return a callable for the finish migration method over gRPC. + + Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + Returns: + Callable[[~.FinishMigrationRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "finish_migration" not in self._stubs: + self._stubs["finish_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/FinishMigration", + request_serializer=memorystore.FinishMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["finish_migration"] + + @property + def list_token_auth_users( + self, + ) -> Callable[ + [memorystore.ListTokenAuthUsersRequest], memorystore.ListTokenAuthUsersResponse + ]: + r"""Return a callable for the list token auth users method over gRPC. + + Lists all the token auth users for a token based auth + enabled instance. + + Returns: + Callable[[~.ListTokenAuthUsersRequest], + ~.ListTokenAuthUsersResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_token_auth_users" not in self._stubs: + self._stubs["list_token_auth_users"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListTokenAuthUsers", + request_serializer=memorystore.ListTokenAuthUsersRequest.serialize, + response_deserializer=memorystore.ListTokenAuthUsersResponse.deserialize, + ) + return self._stubs["list_token_auth_users"] + + @property + def get_token_auth_user( + self, + ) -> Callable[[memorystore.GetTokenAuthUserRequest], memorystore.TokenAuthUser]: + r"""Return a callable for the get token auth user method over gRPC. + + Gets a specific token auth user for a token based + auth enabled instance. + + Returns: + Callable[[~.GetTokenAuthUserRequest], + ~.TokenAuthUser]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_token_auth_user" not in self._stubs: + self._stubs["get_token_auth_user"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetTokenAuthUser", + request_serializer=memorystore.GetTokenAuthUserRequest.serialize, + response_deserializer=memorystore.TokenAuthUser.deserialize, + ) + return self._stubs["get_token_auth_user"] + + @property + def list_auth_tokens( + self, + ) -> Callable[ + [memorystore.ListAuthTokensRequest], memorystore.ListAuthTokensResponse + ]: + r"""Return a callable for the list auth tokens method over gRPC. + + Lists all the auth tokens for a specific token auth + user. + + Returns: + Callable[[~.ListAuthTokensRequest], + ~.ListAuthTokensResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_auth_tokens" not in self._stubs: + self._stubs["list_auth_tokens"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListAuthTokens", + request_serializer=memorystore.ListAuthTokensRequest.serialize, + response_deserializer=memorystore.ListAuthTokensResponse.deserialize, + ) + return self._stubs["list_auth_tokens"] + + @property + def get_auth_token( + self, + ) -> Callable[[memorystore.GetAuthTokenRequest], memorystore.AuthToken]: + r"""Return a callable for the get auth token method over gRPC. + + Gets a token based auth enabled instance's auth token + for a given user. + + Returns: + Callable[[~.GetAuthTokenRequest], + ~.AuthToken]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_auth_token" not in self._stubs: + self._stubs["get_auth_token"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetAuthToken", + request_serializer=memorystore.GetAuthTokenRequest.serialize, + response_deserializer=memorystore.AuthToken.deserialize, + ) + return self._stubs["get_auth_token"] + + @property + def add_token_auth_user( + self, + ) -> Callable[[memorystore.AddTokenAuthUserRequest], operations_pb2.Operation]: + r"""Return a callable for the add token auth user method over gRPC. + + Adds a token auth user for a token based auth enabled + instance. + + Returns: + Callable[[~.AddTokenAuthUserRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_token_auth_user" not in self._stubs: + self._stubs["add_token_auth_user"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/AddTokenAuthUser", + request_serializer=memorystore.AddTokenAuthUserRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["add_token_auth_user"] + + @property + def delete_token_auth_user( + self, + ) -> Callable[[memorystore.DeleteTokenAuthUserRequest], operations_pb2.Operation]: + r"""Return a callable for the delete token auth user method over gRPC. + + Deletes a token auth user for a token based auth + enabled instance. + + Returns: + Callable[[~.DeleteTokenAuthUserRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_token_auth_user" not in self._stubs: + self._stubs["delete_token_auth_user"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/DeleteTokenAuthUser", + request_serializer=memorystore.DeleteTokenAuthUserRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_token_auth_user"] + + @property + def add_auth_token( + self, + ) -> Callable[[memorystore.AddAuthTokenRequest], operations_pb2.Operation]: + r"""Return a callable for the add auth token method over gRPC. + + Adds a token for a user of a token based auth enabled + instance. + + Returns: + Callable[[~.AddAuthTokenRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_auth_token" not in self._stubs: + self._stubs["add_auth_token"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/AddAuthToken", + request_serializer=memorystore.AddAuthTokenRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["add_auth_token"] + + @property + def delete_auth_token( + self, + ) -> Callable[[memorystore.DeleteAuthTokenRequest], operations_pb2.Operation]: + r"""Return a callable for the delete auth token method over gRPC. + + Deletes a token for a user of a token based auth + enabled instance. + + Returns: + Callable[[~.DeleteAuthTokenRequest], + ~.Operation]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_auth_token" not in self._stubs: + self._stubs["delete_auth_token"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/DeleteAuthToken", + request_serializer=memorystore.DeleteAuthTokenRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_auth_token"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc_asyncio.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc_asyncio.py index 1bbc08a0157a..9c920e1bf3b0 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc_asyncio.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/grpc_asyncio.py @@ -554,6 +554,553 @@ def get_shared_regional_certificate_authority( ) return self._stubs["get_shared_regional_certificate_authority"] + @property + def reschedule_maintenance( + self, + ) -> Callable[ + [memorystore.RescheduleMaintenanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the reschedule maintenance method over gRPC. + + Reschedules upcoming maintenance event. + + Returns: + Callable[[~.RescheduleMaintenanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "reschedule_maintenance" not in self._stubs: + self._stubs["reschedule_maintenance"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/RescheduleMaintenance", + request_serializer=memorystore.RescheduleMaintenanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reschedule_maintenance"] + + @property + def list_backup_collections( + self, + ) -> Callable[ + [memorystore.ListBackupCollectionsRequest], + Awaitable[memorystore.ListBackupCollectionsResponse], + ]: + r"""Return a callable for the list backup collections method over gRPC. + + Lists all backup collections owned by a consumer project in + either the specified location (region) or all locations. + + If ``location_id`` is specified as ``-`` (wildcard), then all + regions available to the project are queried, and the results + are aggregated. + + Returns: + Callable[[~.ListBackupCollectionsRequest], + Awaitable[~.ListBackupCollectionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backup_collections" not in self._stubs: + self._stubs["list_backup_collections"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListBackupCollections", + request_serializer=memorystore.ListBackupCollectionsRequest.serialize, + response_deserializer=memorystore.ListBackupCollectionsResponse.deserialize, + ) + return self._stubs["list_backup_collections"] + + @property + def get_backup_collection( + self, + ) -> Callable[ + [memorystore.GetBackupCollectionRequest], + Awaitable[memorystore.BackupCollection], + ]: + r"""Return a callable for the get backup collection method over gRPC. + + Get a backup collection. + + Returns: + Callable[[~.GetBackupCollectionRequest], + Awaitable[~.BackupCollection]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup_collection" not in self._stubs: + self._stubs["get_backup_collection"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetBackupCollection", + request_serializer=memorystore.GetBackupCollectionRequest.serialize, + response_deserializer=memorystore.BackupCollection.deserialize, + ) + return self._stubs["get_backup_collection"] + + @property + def list_backups( + self, + ) -> Callable[ + [memorystore.ListBackupsRequest], Awaitable[memorystore.ListBackupsResponse] + ]: + r"""Return a callable for the list backups method over gRPC. + + Lists all backups owned by a backup collection. + + Returns: + Callable[[~.ListBackupsRequest], + Awaitable[~.ListBackupsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_backups" not in self._stubs: + self._stubs["list_backups"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListBackups", + request_serializer=memorystore.ListBackupsRequest.serialize, + response_deserializer=memorystore.ListBackupsResponse.deserialize, + ) + return self._stubs["list_backups"] + + @property + def get_backup( + self, + ) -> Callable[[memorystore.GetBackupRequest], Awaitable[memorystore.Backup]]: + r"""Return a callable for the get backup method over gRPC. + + Gets the details of a specific backup. + + Returns: + Callable[[~.GetBackupRequest], + Awaitable[~.Backup]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_backup" not in self._stubs: + self._stubs["get_backup"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetBackup", + request_serializer=memorystore.GetBackupRequest.serialize, + response_deserializer=memorystore.Backup.deserialize, + ) + return self._stubs["get_backup"] + + @property + def delete_backup( + self, + ) -> Callable[ + [memorystore.DeleteBackupRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete backup method over gRPC. + + Deletes a specific backup. + + Returns: + Callable[[~.DeleteBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_backup" not in self._stubs: + self._stubs["delete_backup"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/DeleteBackup", + request_serializer=memorystore.DeleteBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_backup"] + + @property + def export_backup( + self, + ) -> Callable[ + [memorystore.ExportBackupRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the export backup method over gRPC. + + Exports a specific backup to a customer target Cloud + Storage URI. + + Returns: + Callable[[~.ExportBackupRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "export_backup" not in self._stubs: + self._stubs["export_backup"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ExportBackup", + request_serializer=memorystore.ExportBackupRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["export_backup"] + + @property + def backup_instance( + self, + ) -> Callable[ + [memorystore.BackupInstanceRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the backup instance method over gRPC. + + Backup Instance. + If this is the first time a backup is being created, a + backup collection will be created at the backend, and + this backup belongs to this collection. Both collection + and backup will have a resource name. Backup will be + executed for each shard. A replica (primary if nonHA) + will be selected to perform the execution. Backup call + will be rejected if there is an ongoing backup or update + operation. Be aware that during preview, if the + instance's internal software version is too old, + critical update will be performed before actual backup. + Once the internal software version is updated to the + minimum version required by the backup feature, + subsequent backups will not require critical update. + After preview, there will be no critical update needed + for backup. + + Returns: + Callable[[~.BackupInstanceRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "backup_instance" not in self._stubs: + self._stubs["backup_instance"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/BackupInstance", + request_serializer=memorystore.BackupInstanceRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["backup_instance"] + + @property + def start_migration( + self, + ) -> Callable[ + [memorystore.StartMigrationRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the start migration method over gRPC. + + Initiates the migration of a source instance to the + target Memorystore instance. + + After the successful completion of this operation, the + target instance will: + + 1. Set up replication with the source instance and + replicate any writes to the source instance. + 2. Only allow reads. + + Returns: + Callable[[~.StartMigrationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "start_migration" not in self._stubs: + self._stubs["start_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/StartMigration", + request_serializer=memorystore.StartMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["start_migration"] + + @property + def finish_migration( + self, + ) -> Callable[ + [memorystore.FinishMigrationRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the finish migration method over gRPC. + + Finalizes the migration process. + + After the successful completion of this operation, the + target instance will: + + 1. Stop replicating from the source instance. + 2. Allow both reads and writes. + + Returns: + Callable[[~.FinishMigrationRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "finish_migration" not in self._stubs: + self._stubs["finish_migration"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/FinishMigration", + request_serializer=memorystore.FinishMigrationRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["finish_migration"] + + @property + def list_token_auth_users( + self, + ) -> Callable[ + [memorystore.ListTokenAuthUsersRequest], + Awaitable[memorystore.ListTokenAuthUsersResponse], + ]: + r"""Return a callable for the list token auth users method over gRPC. + + Lists all the token auth users for a token based auth + enabled instance. + + Returns: + Callable[[~.ListTokenAuthUsersRequest], + Awaitable[~.ListTokenAuthUsersResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_token_auth_users" not in self._stubs: + self._stubs["list_token_auth_users"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListTokenAuthUsers", + request_serializer=memorystore.ListTokenAuthUsersRequest.serialize, + response_deserializer=memorystore.ListTokenAuthUsersResponse.deserialize, + ) + return self._stubs["list_token_auth_users"] + + @property + def get_token_auth_user( + self, + ) -> Callable[ + [memorystore.GetTokenAuthUserRequest], Awaitable[memorystore.TokenAuthUser] + ]: + r"""Return a callable for the get token auth user method over gRPC. + + Gets a specific token auth user for a token based + auth enabled instance. + + Returns: + Callable[[~.GetTokenAuthUserRequest], + Awaitable[~.TokenAuthUser]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_token_auth_user" not in self._stubs: + self._stubs["get_token_auth_user"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetTokenAuthUser", + request_serializer=memorystore.GetTokenAuthUserRequest.serialize, + response_deserializer=memorystore.TokenAuthUser.deserialize, + ) + return self._stubs["get_token_auth_user"] + + @property + def list_auth_tokens( + self, + ) -> Callable[ + [memorystore.ListAuthTokensRequest], + Awaitable[memorystore.ListAuthTokensResponse], + ]: + r"""Return a callable for the list auth tokens method over gRPC. + + Lists all the auth tokens for a specific token auth + user. + + Returns: + Callable[[~.ListAuthTokensRequest], + Awaitable[~.ListAuthTokensResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_auth_tokens" not in self._stubs: + self._stubs["list_auth_tokens"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/ListAuthTokens", + request_serializer=memorystore.ListAuthTokensRequest.serialize, + response_deserializer=memorystore.ListAuthTokensResponse.deserialize, + ) + return self._stubs["list_auth_tokens"] + + @property + def get_auth_token( + self, + ) -> Callable[[memorystore.GetAuthTokenRequest], Awaitable[memorystore.AuthToken]]: + r"""Return a callable for the get auth token method over gRPC. + + Gets a token based auth enabled instance's auth token + for a given user. + + Returns: + Callable[[~.GetAuthTokenRequest], + Awaitable[~.AuthToken]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_auth_token" not in self._stubs: + self._stubs["get_auth_token"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/GetAuthToken", + request_serializer=memorystore.GetAuthTokenRequest.serialize, + response_deserializer=memorystore.AuthToken.deserialize, + ) + return self._stubs["get_auth_token"] + + @property + def add_token_auth_user( + self, + ) -> Callable[ + [memorystore.AddTokenAuthUserRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the add token auth user method over gRPC. + + Adds a token auth user for a token based auth enabled + instance. + + Returns: + Callable[[~.AddTokenAuthUserRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_token_auth_user" not in self._stubs: + self._stubs["add_token_auth_user"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/AddTokenAuthUser", + request_serializer=memorystore.AddTokenAuthUserRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["add_token_auth_user"] + + @property + def delete_token_auth_user( + self, + ) -> Callable[ + [memorystore.DeleteTokenAuthUserRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete token auth user method over gRPC. + + Deletes a token auth user for a token based auth + enabled instance. + + Returns: + Callable[[~.DeleteTokenAuthUserRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_token_auth_user" not in self._stubs: + self._stubs["delete_token_auth_user"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/DeleteTokenAuthUser", + request_serializer=memorystore.DeleteTokenAuthUserRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_token_auth_user"] + + @property + def add_auth_token( + self, + ) -> Callable[ + [memorystore.AddAuthTokenRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the add auth token method over gRPC. + + Adds a token for a user of a token based auth enabled + instance. + + Returns: + Callable[[~.AddAuthTokenRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "add_auth_token" not in self._stubs: + self._stubs["add_auth_token"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/AddAuthToken", + request_serializer=memorystore.AddAuthTokenRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["add_auth_token"] + + @property + def delete_auth_token( + self, + ) -> Callable[ + [memorystore.DeleteAuthTokenRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the delete auth token method over gRPC. + + Deletes a token for a user of a token based auth + enabled instance. + + Returns: + Callable[[~.DeleteAuthTokenRequest], + Awaitable[~.Operation]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_auth_token" not in self._stubs: + self._stubs["delete_auth_token"] = self._logged_channel.unary_unary( + "/google.cloud.memorystore.v1beta.Memorystore/DeleteAuthToken", + request_serializer=memorystore.DeleteAuthTokenRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["delete_auth_token"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -619,6 +1166,96 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.reschedule_maintenance: self._wrap_method( + self.reschedule_maintenance, + default_timeout=None, + client_info=client_info, + ), + self.list_backup_collections: self._wrap_method( + self.list_backup_collections, + default_timeout=None, + client_info=client_info, + ), + self.get_backup_collection: self._wrap_method( + self.get_backup_collection, + default_timeout=None, + client_info=client_info, + ), + self.list_backups: self._wrap_method( + self.list_backups, + default_timeout=None, + client_info=client_info, + ), + self.get_backup: self._wrap_method( + self.get_backup, + default_timeout=None, + client_info=client_info, + ), + self.delete_backup: self._wrap_method( + self.delete_backup, + default_timeout=None, + client_info=client_info, + ), + self.export_backup: self._wrap_method( + self.export_backup, + default_timeout=None, + client_info=client_info, + ), + self.backup_instance: self._wrap_method( + self.backup_instance, + default_timeout=None, + client_info=client_info, + ), + self.start_migration: self._wrap_method( + self.start_migration, + default_timeout=None, + client_info=client_info, + ), + self.finish_migration: self._wrap_method( + self.finish_migration, + default_timeout=None, + client_info=client_info, + ), + self.list_token_auth_users: self._wrap_method( + self.list_token_auth_users, + default_timeout=None, + client_info=client_info, + ), + self.get_token_auth_user: self._wrap_method( + self.get_token_auth_user, + default_timeout=None, + client_info=client_info, + ), + self.list_auth_tokens: self._wrap_method( + self.list_auth_tokens, + default_timeout=None, + client_info=client_info, + ), + self.get_auth_token: self._wrap_method( + self.get_auth_token, + default_timeout=None, + client_info=client_info, + ), + self.add_token_auth_user: self._wrap_method( + self.add_token_auth_user, + default_timeout=None, + client_info=client_info, + ), + self.delete_token_auth_user: self._wrap_method( + self.delete_token_auth_user, + default_timeout=None, + client_info=client_info, + ), + self.add_auth_token: self._wrap_method( + self.add_auth_token, + default_timeout=None, + client_info=client_info, + ), + self.delete_auth_token: self._wrap_method( + self.delete_auth_token, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py index 2140815672a0..875600ad06ec 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest.py @@ -74,6 +74,30 @@ class MemorystoreRestInterceptor: .. code-block:: python class MyCustomMemorystoreInterceptor(MemorystoreRestInterceptor): + def pre_add_auth_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_auth_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_add_token_auth_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_add_token_auth_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_backup_instance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_backup_instance(self, response): + logging.log(f"Received response: {response}") + return response + def pre_create_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -82,6 +106,22 @@ def post_create_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_auth_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_auth_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_delete_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_backup(self, response): + logging.log(f"Received response: {response}") + return response + def pre_delete_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -90,6 +130,54 @@ def post_delete_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_delete_token_auth_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_delete_token_auth_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_export_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_export_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_finish_migration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_finish_migration(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_auth_token(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_auth_token(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_get_backup_collection(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_backup_collection(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_certificate_authority(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -114,6 +202,38 @@ def post_get_shared_regional_certificate_authority(self, response): logging.log(f"Received response: {response}") return response + def pre_get_token_auth_user(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_token_auth_user(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_auth_tokens(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_auth_tokens(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backup_collections(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backup_collections(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_list_backups(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_backups(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -122,6 +242,30 @@ def post_list_instances(self, response): logging.log(f"Received response: {response}") return response + def pre_list_token_auth_users(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_token_auth_users(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_reschedule_maintenance(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_reschedule_maintenance(self, response): + logging.log(f"Received response: {response}") + return response + + def pre_start_migration(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_start_migration(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -136,645 +280,4210 @@ def post_update_instance(self, response): """ - def pre_create_instance( + def pre_add_auth_token( self, - request: memorystore.CreateInstanceRequest, + request: memorystore.AddAuthTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - memorystore.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.AddAuthTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for create_instance + """Pre-rpc interceptor for add_auth_token Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_create_instance( + def post_add_auth_token( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for create_instance + """Post-rpc interceptor for add_auth_token - DEPRECATED. Please use the `post_create_instance_with_metadata` + DEPRECATED. Please use the `post_add_auth_token_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_create_instance` interceptor runs - before the `post_create_instance_with_metadata` interceptor. + it is returned to user code. This `post_add_auth_token` interceptor runs + before the `post_add_auth_token_with_metadata` interceptor. """ return response - def post_create_instance_with_metadata( + def post_add_auth_token_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for create_instance + """Post-rpc interceptor for add_auth_token Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_create_instance_with_metadata` - interceptor in new development instead of the `post_create_instance` interceptor. - When both interceptors are used, this `post_create_instance_with_metadata` interceptor runs after the - `post_create_instance` interceptor. The (possibly modified) response returned by - `post_create_instance` will be passed to - `post_create_instance_with_metadata`. + We recommend only using this `post_add_auth_token_with_metadata` + interceptor in new development instead of the `post_add_auth_token` interceptor. + When both interceptors are used, this `post_add_auth_token_with_metadata` interceptor runs after the + `post_add_auth_token` interceptor. The (possibly modified) response returned by + `post_add_auth_token` will be passed to + `post_add_auth_token_with_metadata`. """ return response, metadata - def pre_delete_instance( + def pre_add_token_auth_user( self, - request: memorystore.DeleteInstanceRequest, + request: memorystore.AddTokenAuthUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - memorystore.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.AddTokenAuthUserRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for delete_instance + """Pre-rpc interceptor for add_token_auth_user Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_delete_instance( + def post_add_token_auth_user( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for delete_instance + """Post-rpc interceptor for add_token_auth_user - DEPRECATED. Please use the `post_delete_instance_with_metadata` + DEPRECATED. Please use the `post_add_token_auth_user_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_delete_instance` interceptor runs - before the `post_delete_instance_with_metadata` interceptor. + it is returned to user code. This `post_add_token_auth_user` interceptor runs + before the `post_add_token_auth_user_with_metadata` interceptor. """ return response - def post_delete_instance_with_metadata( + def post_add_token_auth_user_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for delete_instance + """Post-rpc interceptor for add_token_auth_user Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_delete_instance_with_metadata` - interceptor in new development instead of the `post_delete_instance` interceptor. - When both interceptors are used, this `post_delete_instance_with_metadata` interceptor runs after the - `post_delete_instance` interceptor. The (possibly modified) response returned by - `post_delete_instance` will be passed to - `post_delete_instance_with_metadata`. + We recommend only using this `post_add_token_auth_user_with_metadata` + interceptor in new development instead of the `post_add_token_auth_user` interceptor. + When both interceptors are used, this `post_add_token_auth_user_with_metadata` interceptor runs after the + `post_add_token_auth_user` interceptor. The (possibly modified) response returned by + `post_add_token_auth_user` will be passed to + `post_add_token_auth_user_with_metadata`. """ return response, metadata - def pre_get_certificate_authority( + def pre_backup_instance( self, - request: memorystore.GetCertificateAuthorityRequest, + request: memorystore.BackupInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - memorystore.GetCertificateAuthorityRequest, - Sequence[Tuple[str, Union[str, bytes]]], + memorystore.BackupInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for get_certificate_authority + """Pre-rpc interceptor for backup_instance Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_get_certificate_authority( - self, response: memorystore.CertificateAuthority - ) -> memorystore.CertificateAuthority: - """Post-rpc interceptor for get_certificate_authority + def post_backup_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for backup_instance - DEPRECATED. Please use the `post_get_certificate_authority_with_metadata` + DEPRECATED. Please use the `post_backup_instance_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_get_certificate_authority` interceptor runs - before the `post_get_certificate_authority_with_metadata` interceptor. + it is returned to user code. This `post_backup_instance` interceptor runs + before the `post_backup_instance_with_metadata` interceptor. """ return response - def post_get_certificate_authority_with_metadata( + def post_backup_instance_with_metadata( self, - response: memorystore.CertificateAuthority, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - memorystore.CertificateAuthority, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for get_certificate_authority + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for backup_instance Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_get_certificate_authority_with_metadata` - interceptor in new development instead of the `post_get_certificate_authority` interceptor. - When both interceptors are used, this `post_get_certificate_authority_with_metadata` interceptor runs after the - `post_get_certificate_authority` interceptor. The (possibly modified) response returned by - `post_get_certificate_authority` will be passed to - `post_get_certificate_authority_with_metadata`. + We recommend only using this `post_backup_instance_with_metadata` + interceptor in new development instead of the `post_backup_instance` interceptor. + When both interceptors are used, this `post_backup_instance_with_metadata` interceptor runs after the + `post_backup_instance` interceptor. The (possibly modified) response returned by + `post_backup_instance` will be passed to + `post_backup_instance_with_metadata`. """ return response, metadata - def pre_get_instance( + def pre_create_instance( self, - request: memorystore.GetInstanceRequest, + request: memorystore.CreateInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[memorystore.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: - """Pre-rpc interceptor for get_instance + ) -> Tuple[ + memorystore.CreateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for create_instance Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_get_instance(self, response: memorystore.Instance) -> memorystore.Instance: - """Post-rpc interceptor for get_instance + def post_create_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for create_instance - DEPRECATED. Please use the `post_get_instance_with_metadata` + DEPRECATED. Please use the `post_create_instance_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_get_instance` interceptor runs - before the `post_get_instance_with_metadata` interceptor. + it is returned to user code. This `post_create_instance` interceptor runs + before the `post_create_instance_with_metadata` interceptor. """ return response - def post_get_instance_with_metadata( + def post_create_instance_with_metadata( self, - response: memorystore.Instance, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[memorystore.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for get_instance + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for create_instance Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_get_instance_with_metadata` - interceptor in new development instead of the `post_get_instance` interceptor. - When both interceptors are used, this `post_get_instance_with_metadata` interceptor runs after the - `post_get_instance` interceptor. The (possibly modified) response returned by - `post_get_instance` will be passed to - `post_get_instance_with_metadata`. + We recommend only using this `post_create_instance_with_metadata` + interceptor in new development instead of the `post_create_instance` interceptor. + When both interceptors are used, this `post_create_instance_with_metadata` interceptor runs after the + `post_create_instance` interceptor. The (possibly modified) response returned by + `post_create_instance` will be passed to + `post_create_instance_with_metadata`. """ return response, metadata - def pre_get_shared_regional_certificate_authority( + def pre_delete_auth_token( self, - request: memorystore.GetSharedRegionalCertificateAuthorityRequest, + request: memorystore.DeleteAuthTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - memorystore.GetSharedRegionalCertificateAuthorityRequest, - Sequence[Tuple[str, Union[str, bytes]]], + memorystore.DeleteAuthTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for get_shared_regional_certificate_authority + """Pre-rpc interceptor for delete_auth_token Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_get_shared_regional_certificate_authority( - self, response: memorystore.SharedRegionalCertificateAuthority - ) -> memorystore.SharedRegionalCertificateAuthority: - """Post-rpc interceptor for get_shared_regional_certificate_authority + def post_delete_auth_token( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_auth_token - DEPRECATED. Please use the `post_get_shared_regional_certificate_authority_with_metadata` + DEPRECATED. Please use the `post_delete_auth_token_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_get_shared_regional_certificate_authority` interceptor runs - before the `post_get_shared_regional_certificate_authority_with_metadata` interceptor. + it is returned to user code. This `post_delete_auth_token` interceptor runs + before the `post_delete_auth_token_with_metadata` interceptor. """ return response - def post_get_shared_regional_certificate_authority_with_metadata( + def post_delete_auth_token_with_metadata( self, - response: memorystore.SharedRegionalCertificateAuthority, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - memorystore.SharedRegionalCertificateAuthority, - Sequence[Tuple[str, Union[str, bytes]]], - ]: - """Post-rpc interceptor for get_shared_regional_certificate_authority + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_auth_token Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_get_shared_regional_certificate_authority_with_metadata` - interceptor in new development instead of the `post_get_shared_regional_certificate_authority` interceptor. - When both interceptors are used, this `post_get_shared_regional_certificate_authority_with_metadata` interceptor runs after the - `post_get_shared_regional_certificate_authority` interceptor. The (possibly modified) response returned by - `post_get_shared_regional_certificate_authority` will be passed to - `post_get_shared_regional_certificate_authority_with_metadata`. + We recommend only using this `post_delete_auth_token_with_metadata` + interceptor in new development instead of the `post_delete_auth_token` interceptor. + When both interceptors are used, this `post_delete_auth_token_with_metadata` interceptor runs after the + `post_delete_auth_token` interceptor. The (possibly modified) response returned by + `post_delete_auth_token` will be passed to + `post_delete_auth_token_with_metadata`. """ return response, metadata - def pre_list_instances( + def pre_delete_backup( self, - request: memorystore.ListInstancesRequest, + request: memorystore.DeleteBackupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - memorystore.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.DeleteBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for list_instances + """Pre-rpc interceptor for delete_backup Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_list_instances( - self, response: memorystore.ListInstancesResponse - ) -> memorystore.ListInstancesResponse: - """Post-rpc interceptor for list_instances + def post_delete_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_backup - DEPRECATED. Please use the `post_list_instances_with_metadata` + DEPRECATED. Please use the `post_delete_backup_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_list_instances` interceptor runs - before the `post_list_instances_with_metadata` interceptor. + it is returned to user code. This `post_delete_backup` interceptor runs + before the `post_delete_backup_with_metadata` interceptor. """ return response - def post_list_instances_with_metadata( + def post_delete_backup_with_metadata( self, - response: memorystore.ListInstancesResponse, + response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - memorystore.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Post-rpc interceptor for list_instances + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_backup Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_list_instances_with_metadata` - interceptor in new development instead of the `post_list_instances` interceptor. - When both interceptors are used, this `post_list_instances_with_metadata` interceptor runs after the - `post_list_instances` interceptor. The (possibly modified) response returned by - `post_list_instances` will be passed to - `post_list_instances_with_metadata`. + We recommend only using this `post_delete_backup_with_metadata` + interceptor in new development instead of the `post_delete_backup` interceptor. + When both interceptors are used, this `post_delete_backup_with_metadata` interceptor runs after the + `post_delete_backup` interceptor. The (possibly modified) response returned by + `post_delete_backup` will be passed to + `post_delete_backup_with_metadata`. """ return response, metadata - def pre_update_instance( + def pre_delete_instance( self, - request: memorystore.UpdateInstanceRequest, + request: memorystore.DeleteInstanceRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - memorystore.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.DeleteInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for update_instance + """Pre-rpc interceptor for delete_instance Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_update_instance( + def post_delete_instance( self, response: operations_pb2.Operation ) -> operations_pb2.Operation: - """Post-rpc interceptor for update_instance + """Post-rpc interceptor for delete_instance - DEPRECATED. Please use the `post_update_instance_with_metadata` + DEPRECATED. Please use the `post_delete_instance_with_metadata` interceptor instead. Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. This `post_update_instance` interceptor runs - before the `post_update_instance_with_metadata` interceptor. + it is returned to user code. This `post_delete_instance` interceptor runs + before the `post_delete_instance_with_metadata` interceptor. """ return response - def post_update_instance_with_metadata( + def post_delete_instance_with_metadata( self, response: operations_pb2.Operation, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: - """Post-rpc interceptor for update_instance + """Post-rpc interceptor for delete_instance Override in a subclass to read or manipulate the response or metadata after it is returned by the Memorystore server but before it is returned to user code. - We recommend only using this `post_update_instance_with_metadata` - interceptor in new development instead of the `post_update_instance` interceptor. - When both interceptors are used, this `post_update_instance_with_metadata` interceptor runs after the - `post_update_instance` interceptor. The (possibly modified) response returned by - `post_update_instance` will be passed to - `post_update_instance_with_metadata`. + We recommend only using this `post_delete_instance_with_metadata` + interceptor in new development instead of the `post_delete_instance` interceptor. + When both interceptors are used, this `post_delete_instance_with_metadata` interceptor runs after the + `post_delete_instance` interceptor. The (possibly modified) response returned by + `post_delete_instance` will be passed to + `post_delete_instance_with_metadata`. """ return response, metadata - def pre_get_location( + def pre_delete_token_auth_user( self, - request: locations_pb2.GetLocationRequest, + request: memorystore.DeleteTokenAuthUserRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.DeleteTokenAuthUserRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for get_location + """Pre-rpc interceptor for delete_token_auth_user Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_get_location( - self, response: locations_pb2.Location - ) -> locations_pb2.Location: - """Post-rpc interceptor for get_location + def post_delete_token_auth_user( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for delete_token_auth_user - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_delete_token_auth_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. + it is returned to user code. This `post_delete_token_auth_user` interceptor runs + before the `post_delete_token_auth_user_with_metadata` interceptor. """ return response - def pre_list_locations( + def post_delete_token_auth_user_with_metadata( self, - request: locations_pb2.ListLocationsRequest, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for delete_token_auth_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_delete_token_auth_user_with_metadata` + interceptor in new development instead of the `post_delete_token_auth_user` interceptor. + When both interceptors are used, this `post_delete_token_auth_user_with_metadata` interceptor runs after the + `post_delete_token_auth_user` interceptor. The (possibly modified) response returned by + `post_delete_token_auth_user` will be passed to + `post_delete_token_auth_user_with_metadata`. + """ + return response, metadata + + def pre_export_backup( + self, + request: memorystore.ExportBackupRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.ExportBackupRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for list_locations + """Pre-rpc interceptor for export_backup Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_list_locations( - self, response: locations_pb2.ListLocationsResponse - ) -> locations_pb2.ListLocationsResponse: - """Post-rpc interceptor for list_locations + def post_export_backup( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for export_backup - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_export_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. + it is returned to user code. This `post_export_backup` interceptor runs + before the `post_export_backup_with_metadata` interceptor. """ return response - def pre_cancel_operation( + def post_export_backup_with_metadata( self, - request: operations_pb2.CancelOperationRequest, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for export_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_export_backup_with_metadata` + interceptor in new development instead of the `post_export_backup` interceptor. + When both interceptors are used, this `post_export_backup_with_metadata` interceptor runs after the + `post_export_backup` interceptor. The (possibly modified) response returned by + `post_export_backup` will be passed to + `post_export_backup_with_metadata`. + """ + return response, metadata + + def pre_finish_migration( + self, + request: memorystore.FinishMigrationRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.FinishMigrationRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for cancel_operation + """Pre-rpc interceptor for finish_migration Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_cancel_operation(self, response: None) -> None: - """Post-rpc interceptor for cancel_operation + def post_finish_migration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for finish_migration - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_finish_migration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. + it is returned to user code. This `post_finish_migration` interceptor runs + before the `post_finish_migration_with_metadata` interceptor. """ return response - def pre_delete_operation( + def post_finish_migration_with_metadata( self, - request: operations_pb2.DeleteOperationRequest, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for finish_migration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_finish_migration_with_metadata` + interceptor in new development instead of the `post_finish_migration` interceptor. + When both interceptors are used, this `post_finish_migration_with_metadata` interceptor runs after the + `post_finish_migration` interceptor. The (possibly modified) response returned by + `post_finish_migration` will be passed to + `post_finish_migration_with_metadata`. + """ + return response, metadata + + def pre_get_auth_token( + self, + request: memorystore.GetAuthTokenRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.GetAuthTokenRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for delete_operation + """Pre-rpc interceptor for get_auth_token Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_delete_operation(self, response: None) -> None: - """Post-rpc interceptor for delete_operation + def post_get_auth_token( + self, response: memorystore.AuthToken + ) -> memorystore.AuthToken: + """Post-rpc interceptor for get_auth_token - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_auth_token_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. + it is returned to user code. This `post_get_auth_token` interceptor runs + before the `post_get_auth_token_with_metadata` interceptor. """ return response - def pre_get_operation( + def post_get_auth_token_with_metadata( self, - request: operations_pb2.GetOperationRequest, + response: memorystore.AuthToken, metadata: Sequence[Tuple[str, Union[str, bytes]]], - ) -> Tuple[ - operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] - ]: - """Pre-rpc interceptor for get_operation + ) -> Tuple[memorystore.AuthToken, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_auth_token + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_get_auth_token_with_metadata` + interceptor in new development instead of the `post_get_auth_token` interceptor. + When both interceptors are used, this `post_get_auth_token_with_metadata` interceptor runs after the + `post_get_auth_token` interceptor. The (possibly modified) response returned by + `post_get_auth_token` will be passed to + `post_get_auth_token_with_metadata`. + """ + return response, metadata + + def pre_get_backup( + self, + request: memorystore.GetBackupRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.GetBackupRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_backup Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_get_operation( - self, response: operations_pb2.Operation - ) -> operations_pb2.Operation: - """Post-rpc interceptor for get_operation + def post_get_backup(self, response: memorystore.Backup) -> memorystore.Backup: + """Post-rpc interceptor for get_backup - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_backup_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. + it is returned to user code. This `post_get_backup` interceptor runs + before the `post_get_backup_with_metadata` interceptor. """ return response - def pre_list_operations( + def post_get_backup_with_metadata( self, - request: operations_pb2.ListOperationsRequest, + response: memorystore.Backup, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.Backup, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_get_backup_with_metadata` + interceptor in new development instead of the `post_get_backup` interceptor. + When both interceptors are used, this `post_get_backup_with_metadata` interceptor runs after the + `post_get_backup` interceptor. The (possibly modified) response returned by + `post_get_backup` will be passed to + `post_get_backup_with_metadata`. + """ + return response, metadata + + def pre_get_backup_collection( + self, + request: memorystore.GetBackupCollectionRequest, metadata: Sequence[Tuple[str, Union[str, bytes]]], ) -> Tuple[ - operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + memorystore.GetBackupCollectionRequest, Sequence[Tuple[str, Union[str, bytes]]] ]: - """Pre-rpc interceptor for list_operations + """Pre-rpc interceptor for get_backup_collection Override in a subclass to manipulate the request or metadata before they are sent to the Memorystore server. """ return request, metadata - def post_list_operations( - self, response: operations_pb2.ListOperationsResponse - ) -> operations_pb2.ListOperationsResponse: - """Post-rpc interceptor for list_operations + def post_get_backup_collection( + self, response: memorystore.BackupCollection + ) -> memorystore.BackupCollection: + """Post-rpc interceptor for get_backup_collection - Override in a subclass to manipulate the response + DEPRECATED. Please use the `post_get_backup_collection_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response after it is returned by the Memorystore server but before - it is returned to user code. + it is returned to user code. This `post_get_backup_collection` interceptor runs + before the `post_get_backup_collection_with_metadata` interceptor. """ return response + def post_get_backup_collection_with_metadata( + self, + response: memorystore.BackupCollection, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.BackupCollection, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_backup_collection -@dataclasses.dataclass -class MemorystoreRestStub: - _session: AuthorizedSession - _host: str - _interceptor: MemorystoreRestInterceptor + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + We recommend only using this `post_get_backup_collection_with_metadata` + interceptor in new development instead of the `post_get_backup_collection` interceptor. + When both interceptors are used, this `post_get_backup_collection_with_metadata` interceptor runs after the + `post_get_backup_collection` interceptor. The (possibly modified) response returned by + `post_get_backup_collection` will be passed to + `post_get_backup_collection_with_metadata`. + """ + return response, metadata -class MemorystoreRestTransport(_BaseMemorystoreRestTransport): - """REST backend synchronous transport for Memorystore. + def pre_get_certificate_authority( + self, + request: memorystore.GetCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.GetCertificateAuthorityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_certificate_authority - Service describing handlers for resources + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata - This class defines the same methods as the primary client, so the - primary client can load the underlying transport implementation - and call it. + def post_get_certificate_authority( + self, response: memorystore.CertificateAuthority + ) -> memorystore.CertificateAuthority: + """Post-rpc interceptor for get_certificate_authority - It sends JSON representations of protocol buffers over HTTP/1.1 - """ + DEPRECATED. Please use the `post_get_certificate_authority_with_metadata` + interceptor instead. - def __init__( + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_get_certificate_authority` interceptor runs + before the `post_get_certificate_authority_with_metadata` interceptor. + """ + return response + + def post_get_certificate_authority_with_metadata( self, - *, - host: str = "memorystore.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[MemorystoreRestInterceptor] = None, - api_audience: Optional[str] = None, - ) -> None: - """Instantiate the transport. + response: memorystore.CertificateAuthority, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.CertificateAuthority, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for get_certificate_authority - Args: - host (Optional[str]): - The hostname to connect to (default: 'memorystore.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. + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. - 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. - interceptor (Optional[MemorystoreRestInterceptor]): Interceptor used - to manipulate requests, request metadata, and responses. - api_audience (Optional[str]): The intended audience for the API calls - to the service that will be set when using certain 3rd party - authentication flows. Audience is typically a resource identifier. - If not set, the host value will be used as a default. + We recommend only using this `post_get_certificate_authority_with_metadata` + interceptor in new development instead of the `post_get_certificate_authority` interceptor. + When both interceptors are used, this `post_get_certificate_authority_with_metadata` interceptor runs after the + `post_get_certificate_authority` interceptor. The (possibly modified) response returned by + `post_get_certificate_authority` will be passed to + `post_get_certificate_authority_with_metadata`. """ - # 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 - ) - self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None - if client_cert_source_for_mtls: - self._session.configure_mtls_channel(client_cert_source_for_mtls) - self._interceptor = interceptor or MemorystoreRestInterceptor() - self._prep_wrapped_messages(client_info) + return response, metadata + + def pre_get_instance( + self, + request: memorystore.GetInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.GetInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for get_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_get_instance(self, response: memorystore.Instance) -> memorystore.Instance: + """Post-rpc interceptor for get_instance + + DEPRECATED. Please use the `post_get_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_get_instance` interceptor runs + before the `post_get_instance_with_metadata` interceptor. + """ + return response + + def post_get_instance_with_metadata( + self, + response: memorystore.Instance, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.Instance, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_get_instance_with_metadata` + interceptor in new development instead of the `post_get_instance` interceptor. + When both interceptors are used, this `post_get_instance_with_metadata` interceptor runs after the + `post_get_instance` interceptor. The (possibly modified) response returned by + `post_get_instance` will be passed to + `post_get_instance_with_metadata`. + """ + return response, metadata + + def pre_get_shared_regional_certificate_authority( + self, + request: memorystore.GetSharedRegionalCertificateAuthorityRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.GetSharedRegionalCertificateAuthorityRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for get_shared_regional_certificate_authority + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_get_shared_regional_certificate_authority( + self, response: memorystore.SharedRegionalCertificateAuthority + ) -> memorystore.SharedRegionalCertificateAuthority: + """Post-rpc interceptor for get_shared_regional_certificate_authority + + DEPRECATED. Please use the `post_get_shared_regional_certificate_authority_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_get_shared_regional_certificate_authority` interceptor runs + before the `post_get_shared_regional_certificate_authority_with_metadata` interceptor. + """ + return response + + def post_get_shared_regional_certificate_authority_with_metadata( + self, + response: memorystore.SharedRegionalCertificateAuthority, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.SharedRegionalCertificateAuthority, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for get_shared_regional_certificate_authority + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_get_shared_regional_certificate_authority_with_metadata` + interceptor in new development instead of the `post_get_shared_regional_certificate_authority` interceptor. + When both interceptors are used, this `post_get_shared_regional_certificate_authority_with_metadata` interceptor runs after the + `post_get_shared_regional_certificate_authority` interceptor. The (possibly modified) response returned by + `post_get_shared_regional_certificate_authority` will be passed to + `post_get_shared_regional_certificate_authority_with_metadata`. + """ + return response, metadata + + def pre_get_token_auth_user( + self, + request: memorystore.GetTokenAuthUserRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.GetTokenAuthUserRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_token_auth_user + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_get_token_auth_user( + self, response: memorystore.TokenAuthUser + ) -> memorystore.TokenAuthUser: + """Post-rpc interceptor for get_token_auth_user + + DEPRECATED. Please use the `post_get_token_auth_user_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_get_token_auth_user` interceptor runs + before the `post_get_token_auth_user_with_metadata` interceptor. + """ + return response + + def post_get_token_auth_user_with_metadata( + self, + response: memorystore.TokenAuthUser, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.TokenAuthUser, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for get_token_auth_user + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_get_token_auth_user_with_metadata` + interceptor in new development instead of the `post_get_token_auth_user` interceptor. + When both interceptors are used, this `post_get_token_auth_user_with_metadata` interceptor runs after the + `post_get_token_auth_user` interceptor. The (possibly modified) response returned by + `post_get_token_auth_user` will be passed to + `post_get_token_auth_user_with_metadata`. + """ + return response, metadata + + def pre_list_auth_tokens( + self, + request: memorystore.ListAuthTokensRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListAuthTokensRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_auth_tokens + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_auth_tokens( + self, response: memorystore.ListAuthTokensResponse + ) -> memorystore.ListAuthTokensResponse: + """Post-rpc interceptor for list_auth_tokens + + DEPRECATED. Please use the `post_list_auth_tokens_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_list_auth_tokens` interceptor runs + before the `post_list_auth_tokens_with_metadata` interceptor. + """ + return response + + def post_list_auth_tokens_with_metadata( + self, + response: memorystore.ListAuthTokensResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListAuthTokensResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_auth_tokens + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_list_auth_tokens_with_metadata` + interceptor in new development instead of the `post_list_auth_tokens` interceptor. + When both interceptors are used, this `post_list_auth_tokens_with_metadata` interceptor runs after the + `post_list_auth_tokens` interceptor. The (possibly modified) response returned by + `post_list_auth_tokens` will be passed to + `post_list_auth_tokens_with_metadata`. + """ + return response, metadata + + def pre_list_backup_collections( + self, + request: memorystore.ListBackupCollectionsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListBackupCollectionsRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for list_backup_collections + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_backup_collections( + self, response: memorystore.ListBackupCollectionsResponse + ) -> memorystore.ListBackupCollectionsResponse: + """Post-rpc interceptor for list_backup_collections + + DEPRECATED. Please use the `post_list_backup_collections_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_list_backup_collections` interceptor runs + before the `post_list_backup_collections_with_metadata` interceptor. + """ + return response + + def post_list_backup_collections_with_metadata( + self, + response: memorystore.ListBackupCollectionsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListBackupCollectionsResponse, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Post-rpc interceptor for list_backup_collections + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_list_backup_collections_with_metadata` + interceptor in new development instead of the `post_list_backup_collections` interceptor. + When both interceptors are used, this `post_list_backup_collections_with_metadata` interceptor runs after the + `post_list_backup_collections` interceptor. The (possibly modified) response returned by + `post_list_backup_collections` will be passed to + `post_list_backup_collections_with_metadata`. + """ + return response, metadata + + def pre_list_backups( + self, + request: memorystore.ListBackupsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[memorystore.ListBackupsRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for list_backups + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_backups( + self, response: memorystore.ListBackupsResponse + ) -> memorystore.ListBackupsResponse: + """Post-rpc interceptor for list_backups + + DEPRECATED. Please use the `post_list_backups_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_list_backups` interceptor runs + before the `post_list_backups_with_metadata` interceptor. + """ + return response + + def post_list_backups_with_metadata( + self, + response: memorystore.ListBackupsResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListBackupsResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_backups + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_list_backups_with_metadata` + interceptor in new development instead of the `post_list_backups` interceptor. + When both interceptors are used, this `post_list_backups_with_metadata` interceptor runs after the + `post_list_backups` interceptor. The (possibly modified) response returned by + `post_list_backups` will be passed to + `post_list_backups_with_metadata`. + """ + return response, metadata + + def pre_list_instances( + self, + request: memorystore.ListInstancesRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListInstancesRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_instances + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_instances( + self, response: memorystore.ListInstancesResponse + ) -> memorystore.ListInstancesResponse: + """Post-rpc interceptor for list_instances + + DEPRECATED. Please use the `post_list_instances_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_list_instances` interceptor runs + before the `post_list_instances_with_metadata` interceptor. + """ + return response + + def post_list_instances_with_metadata( + self, + response: memorystore.ListInstancesResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListInstancesResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_instances + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_list_instances_with_metadata` + interceptor in new development instead of the `post_list_instances` interceptor. + When both interceptors are used, this `post_list_instances_with_metadata` interceptor runs after the + `post_list_instances` interceptor. The (possibly modified) response returned by + `post_list_instances` will be passed to + `post_list_instances_with_metadata`. + """ + return response, metadata + + def pre_list_token_auth_users( + self, + request: memorystore.ListTokenAuthUsersRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListTokenAuthUsersRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_token_auth_users + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_token_auth_users( + self, response: memorystore.ListTokenAuthUsersResponse + ) -> memorystore.ListTokenAuthUsersResponse: + """Post-rpc interceptor for list_token_auth_users + + DEPRECATED. Please use the `post_list_token_auth_users_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_list_token_auth_users` interceptor runs + before the `post_list_token_auth_users_with_metadata` interceptor. + """ + return response + + def post_list_token_auth_users_with_metadata( + self, + response: memorystore.ListTokenAuthUsersResponse, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.ListTokenAuthUsersResponse, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Post-rpc interceptor for list_token_auth_users + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_list_token_auth_users_with_metadata` + interceptor in new development instead of the `post_list_token_auth_users` interceptor. + When both interceptors are used, this `post_list_token_auth_users_with_metadata` interceptor runs after the + `post_list_token_auth_users` interceptor. The (possibly modified) response returned by + `post_list_token_auth_users` will be passed to + `post_list_token_auth_users_with_metadata`. + """ + return response, metadata + + def pre_reschedule_maintenance( + self, + request: memorystore.RescheduleMaintenanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.RescheduleMaintenanceRequest, + Sequence[Tuple[str, Union[str, bytes]]], + ]: + """Pre-rpc interceptor for reschedule_maintenance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_reschedule_maintenance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for reschedule_maintenance + + DEPRECATED. Please use the `post_reschedule_maintenance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_reschedule_maintenance` interceptor runs + before the `post_reschedule_maintenance_with_metadata` interceptor. + """ + return response + + def post_reschedule_maintenance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for reschedule_maintenance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_reschedule_maintenance_with_metadata` + interceptor in new development instead of the `post_reschedule_maintenance` interceptor. + When both interceptors are used, this `post_reschedule_maintenance_with_metadata` interceptor runs after the + `post_reschedule_maintenance` interceptor. The (possibly modified) response returned by + `post_reschedule_maintenance` will be passed to + `post_reschedule_maintenance_with_metadata`. + """ + return response, metadata + + def pre_start_migration( + self, + request: memorystore.StartMigrationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.StartMigrationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for start_migration + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_start_migration( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for start_migration + + DEPRECATED. Please use the `post_start_migration_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_start_migration` interceptor runs + before the `post_start_migration_with_metadata` interceptor. + """ + return response + + def post_start_migration_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for start_migration + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_start_migration_with_metadata` + interceptor in new development instead of the `post_start_migration` interceptor. + When both interceptors are used, this `post_start_migration_with_metadata` interceptor runs after the + `post_start_migration` interceptor. The (possibly modified) response returned by + `post_start_migration` will be passed to + `post_start_migration_with_metadata`. + """ + return response, metadata + + def pre_update_instance( + self, + request: memorystore.UpdateInstanceRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + memorystore.UpdateInstanceRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for update_instance + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_update_instance( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for update_instance + + DEPRECATED. Please use the `post_update_instance_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. This `post_update_instance` interceptor runs + before the `post_update_instance_with_metadata` interceptor. + """ + return response + + def post_update_instance_with_metadata( + self, + response: operations_pb2.Operation, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[operations_pb2.Operation, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for update_instance + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the Memorystore server but before it is returned to user code. + + We recommend only using this `post_update_instance_with_metadata` + interceptor in new development instead of the `post_update_instance` interceptor. + When both interceptors are used, this `post_update_instance_with_metadata` interceptor runs after the + `post_update_instance` interceptor. The (possibly modified) response returned by + `post_update_instance` will be passed to + `post_update_instance_with_metadata`. + """ + return response, metadata + + def pre_get_location( + self, + request: locations_pb2.GetLocationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.GetLocationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_location + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_get_location( + self, response: locations_pb2.Location + ) -> locations_pb2.Location: + """Post-rpc interceptor for get_location + + Override in a subclass to manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. + """ + return response + + def pre_list_locations( + self, + request: locations_pb2.ListLocationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + locations_pb2.ListLocationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_locations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_locations( + self, response: locations_pb2.ListLocationsResponse + ) -> locations_pb2.ListLocationsResponse: + """Post-rpc interceptor for list_locations + + Override in a subclass to manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. + """ + return response + + def pre_cancel_operation( + self, + request: operations_pb2.CancelOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.CancelOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_cancel_operation(self, response: None) -> None: + """Post-rpc interceptor for cancel_operation + + Override in a subclass to manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. + """ + return response + + def pre_delete_operation( + self, + request: operations_pb2.DeleteOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.DeleteOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for delete_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_delete_operation(self, response: None) -> None: + """Post-rpc interceptor for delete_operation + + Override in a subclass to manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. + """ + return response + + def pre_get_operation( + self, + request: operations_pb2.GetOperationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.GetOperationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for get_operation + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_get_operation( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for get_operation + + Override in a subclass to manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. + """ + return response + + def pre_list_operations( + self, + request: operations_pb2.ListOperationsRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + operations_pb2.ListOperationsRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for list_operations + + Override in a subclass to manipulate the request or metadata + before they are sent to the Memorystore server. + """ + return request, metadata + + def post_list_operations( + self, response: operations_pb2.ListOperationsResponse + ) -> operations_pb2.ListOperationsResponse: + """Post-rpc interceptor for list_operations + + Override in a subclass to manipulate the response + after it is returned by the Memorystore server but before + it is returned to user code. + """ + return response + + +@dataclasses.dataclass +class MemorystoreRestStub: + _session: AuthorizedSession + _host: str + _interceptor: MemorystoreRestInterceptor + + +class MemorystoreRestTransport(_BaseMemorystoreRestTransport): + """REST backend synchronous transport for Memorystore. + + Service describing handlers for resources + + 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 = "memorystore.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[MemorystoreRestInterceptor] = None, + api_audience: Optional[str] = None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): + The hostname to connect to (default: 'memorystore.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. + interceptor (Optional[MemorystoreRestInterceptor]): Interceptor used + to manipulate requests, request metadata, and responses. + api_audience (Optional[str]): The intended audience for the API calls + to the service that will be set when using certain 3rd party + authentication flows. Audience is typically a resource identifier. + If not set, the host value will be used as a default. + """ + # 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 + ) + self._operations_client: Optional[operations_v1.AbstractOperationsClient] = None + if client_cert_source_for_mtls: + self._session.configure_mtls_channel(client_cert_source_for_mtls) + self._interceptor = interceptor or MemorystoreRestInterceptor() + self._prep_wrapped_messages(client_info) + + @property + def operations_client(self) -> operations_v1.AbstractOperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Only create a new client if we do not already have one. + if self._operations_client is None: + http_options: Dict[str, List[Dict[str, str]]] = { + "google.longrunning.Operations.CancelOperation": [ + { + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", + }, + ], + "google.longrunning.Operations.DeleteOperation": [ + { + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.GetOperation": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", + }, + ], + "google.longrunning.Operations.ListOperations": [ + { + "method": "get", + "uri": "/v1beta/{name=projects/*/locations/*}/operations", + }, + ], + } + + rest_transport = operations_v1.OperationsRestTransport( + host=self._host, + # use the credentials which are saved + credentials=self._credentials, + scopes=self._scopes, + http_options=http_options, + path_prefix="v1beta", + ) + + self._operations_client = operations_v1.AbstractOperationsClient( + transport=rest_transport + ) + + # Return the client from cache. + return self._operations_client + + class _AddAuthToken( + _BaseMemorystoreRestTransport._BaseAddAuthToken, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.AddAuthToken") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.AddAuthTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the add auth token method over HTTP. + + Args: + request (~.memorystore.AddAuthTokenRequest): + The request object. Request message for ``AddAuthToken``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseAddAuthToken._get_http_options() + ) + + request, metadata = self._interceptor.pre_add_auth_token(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseAddAuthToken._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseMemorystoreRestTransport._BaseAddAuthToken._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseMemorystoreRestTransport._BaseAddAuthToken._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.memorystore_v1beta.MemorystoreClient.AddAuthToken", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "AddAuthToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._AddAuthToken._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_add_auth_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_auth_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.add_auth_token", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "AddAuthToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _AddTokenAuthUser( + _BaseMemorystoreRestTransport._BaseAddTokenAuthUser, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.AddTokenAuthUser") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.AddTokenAuthUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the add token auth user method over HTTP. + + Args: + request (~.memorystore.AddTokenAuthUserRequest): + The request object. Request message for ``AddTokenAuthUser``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseAddTokenAuthUser._get_http_options() + ) + + request, metadata = self._interceptor.pre_add_token_auth_user( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseAddTokenAuthUser._get_transcoded_request( + http_options, request + ) + + body = _BaseMemorystoreRestTransport._BaseAddTokenAuthUser._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseAddTokenAuthUser._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.memorystore_v1beta.MemorystoreClient.AddTokenAuthUser", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "AddTokenAuthUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._AddTokenAuthUser._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_add_token_auth_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_add_token_auth_user_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.add_token_auth_user", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "AddTokenAuthUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _BackupInstance( + _BaseMemorystoreRestTransport._BaseBackupInstance, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.BackupInstance") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.BackupInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the backup instance method over HTTP. + + Args: + request (~.memorystore.BackupInstanceRequest): + The request object. Request for ``BackupInstance``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseBackupInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_backup_instance(request, metadata) + transcoded_request = _BaseMemorystoreRestTransport._BaseBackupInstance._get_transcoded_request( + http_options, request + ) + + body = _BaseMemorystoreRestTransport._BaseBackupInstance._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseBackupInstance._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.memorystore_v1beta.MemorystoreClient.BackupInstance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "BackupInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._BackupInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_backup_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_backup_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.backup_instance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "BackupInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _CreateInstance( + _BaseMemorystoreRestTransport._BaseCreateInstance, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.CreateInstance") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.CreateInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the create instance method over HTTP. + + Args: + request (~.memorystore.CreateInstanceRequest): + The request object. Request message for [CreateInstance][]. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseCreateInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_create_instance(request, metadata) + transcoded_request = _BaseMemorystoreRestTransport._BaseCreateInstance._get_transcoded_request( + http_options, request + ) + + body = _BaseMemorystoreRestTransport._BaseCreateInstance._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseCreateInstance._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.memorystore_v1beta.MemorystoreClient.CreateInstance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "CreateInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._CreateInstance._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_create_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.create_instance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "CreateInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteAuthToken( + _BaseMemorystoreRestTransport._BaseDeleteAuthToken, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.DeleteAuthToken") + + @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: memorystore.DeleteAuthTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete auth token method over HTTP. + + Args: + request (~.memorystore.DeleteAuthTokenRequest): + The request object. Request message for ``DeleteAuthToken``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseDeleteAuthToken._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_auth_token( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseDeleteAuthToken._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseDeleteAuthToken._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.memorystore_v1beta.MemorystoreClient.DeleteAuthToken", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteAuthToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._DeleteAuthToken._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_auth_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_auth_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.delete_auth_token", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteAuthToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteBackup( + _BaseMemorystoreRestTransport._BaseDeleteBackup, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.DeleteBackup") + + @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: memorystore.DeleteBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete backup method over HTTP. + + Args: + request (~.memorystore.DeleteBackupRequest): + The request object. Request for ``DeleteBackup``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseDeleteBackup._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_backup(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseDeleteBackup._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseMemorystoreRestTransport._BaseDeleteBackup._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.memorystore_v1beta.MemorystoreClient.DeleteBackup", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._DeleteBackup._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.delete_backup", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteInstance( + _BaseMemorystoreRestTransport._BaseDeleteInstance, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.DeleteInstance") + + @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: memorystore.DeleteInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete instance method over HTTP. + + Args: + request (~.memorystore.DeleteInstanceRequest): + The request object. Request message for [DeleteInstance][]. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseDeleteInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_delete_instance(request, metadata) + transcoded_request = _BaseMemorystoreRestTransport._BaseDeleteInstance._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseDeleteInstance._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.memorystore_v1beta.MemorystoreClient.DeleteInstance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._DeleteInstance._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.delete_instance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _DeleteTokenAuthUser( + _BaseMemorystoreRestTransport._BaseDeleteTokenAuthUser, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.DeleteTokenAuthUser") + + @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: memorystore.DeleteTokenAuthUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the delete token auth user method over HTTP. + + Args: + request (~.memorystore.DeleteTokenAuthUserRequest): + The request object. Request message for ``DeleteTokenAuthUser``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = _BaseMemorystoreRestTransport._BaseDeleteTokenAuthUser._get_http_options() + + request, metadata = self._interceptor.pre_delete_token_auth_user( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseDeleteTokenAuthUser._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseDeleteTokenAuthUser._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.memorystore_v1beta.MemorystoreClient.DeleteTokenAuthUser", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteTokenAuthUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._DeleteTokenAuthUser._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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_delete_token_auth_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_delete_token_auth_user_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.delete_token_auth_user", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "DeleteTokenAuthUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ExportBackup( + _BaseMemorystoreRestTransport._BaseExportBackup, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.ExportBackup") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.ExportBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the export backup method over HTTP. + + Args: + request (~.memorystore.ExportBackupRequest): + The request object. Request for ``ExportBackup``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseExportBackup._get_http_options() + ) + + request, metadata = self._interceptor.pre_export_backup(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseExportBackup._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseMemorystoreRestTransport._BaseExportBackup._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseMemorystoreRestTransport._BaseExportBackup._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.memorystore_v1beta.MemorystoreClient.ExportBackup", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "ExportBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._ExportBackup._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_export_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_export_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.export_backup", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "ExportBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _FinishMigration( + _BaseMemorystoreRestTransport._BaseFinishMigration, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.FinishMigration") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: memorystore.FinishMigrationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> operations_pb2.Operation: + r"""Call the finish migration method over HTTP. + + Args: + request (~.memorystore.FinishMigrationRequest): + The request object. Request for ``FinishMigration``. + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseFinishMigration._get_http_options() + ) + + request, metadata = self._interceptor.pre_finish_migration( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseFinishMigration._get_transcoded_request( + http_options, request + ) + + body = _BaseMemorystoreRestTransport._BaseFinishMigration._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseFinishMigration._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.memorystore_v1beta.MemorystoreClient.FinishMigration", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "FinishMigration", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._FinishMigration._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_finish_migration(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_finish_migration_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = json_format.MessageToJson(resp) + except: + response_payload = None + http_response = { + "payload": response_payload, + "headers": dict(response.headers), + "status": response.status_code, + } + _LOGGER.debug( + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.finish_migration", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "FinishMigration", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetAuthToken( + _BaseMemorystoreRestTransport._BaseGetAuthToken, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.GetAuthToken") + + @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: memorystore.GetAuthTokenRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.AuthToken: + r"""Call the get auth token method over HTTP. + + Args: + request (~.memorystore.GetAuthTokenRequest): + The request object. Request message for ``GetAuthToken``. + 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: + ~.memorystore.AuthToken: + Auth token for the instance. + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseGetAuthToken._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_auth_token(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseGetAuthToken._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseMemorystoreRestTransport._BaseGetAuthToken._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.memorystore_v1beta.MemorystoreClient.GetAuthToken", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetAuthToken", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetAuthToken._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 = memorystore.AuthToken() + pb_resp = memorystore.AuthToken.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_auth_token(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_auth_token_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.AuthToken.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.memorystore_v1beta.MemorystoreClient.get_auth_token", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetAuthToken", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackup(_BaseMemorystoreRestTransport._BaseGetBackup, MemorystoreRestStub): + def __hash__(self): + return hash("MemorystoreRestTransport.GetBackup") + + @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: memorystore.GetBackupRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.Backup: + r"""Call the get backup method over HTTP. + + Args: + request (~.memorystore.GetBackupRequest): + The request object. Request for ``GetBackup``. + 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: + ~.memorystore.Backup: + Backup of an instance. + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseGetBackup._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_backup(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseGetBackup._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseMemorystoreRestTransport._BaseGetBackup._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.memorystore_v1beta.MemorystoreClient.GetBackup", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetBackup", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetBackup._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 = memorystore.Backup() + pb_resp = memorystore.Backup.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.Backup.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.memorystore_v1beta.MemorystoreClient.get_backup", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetBackup", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetBackupCollection( + _BaseMemorystoreRestTransport._BaseGetBackupCollection, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.GetBackupCollection") + + @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: memorystore.GetBackupCollectionRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.BackupCollection: + r"""Call the get backup collection method over HTTP. + + Args: + request (~.memorystore.GetBackupCollectionRequest): + The request object. Request for ``GetBackupCollection``. + 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: + ~.memorystore.BackupCollection: + BackupCollection of an instance. + """ + + http_options = _BaseMemorystoreRestTransport._BaseGetBackupCollection._get_http_options() + + request, metadata = self._interceptor.pre_get_backup_collection( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseGetBackupCollection._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseGetBackupCollection._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.memorystore_v1beta.MemorystoreClient.GetBackupCollection", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetBackupCollection", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetBackupCollection._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 = memorystore.BackupCollection() + pb_resp = memorystore.BackupCollection.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_backup_collection(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_backup_collection_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.BackupCollection.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.memorystore_v1beta.MemorystoreClient.get_backup_collection", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetBackupCollection", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetCertificateAuthority( + _BaseMemorystoreRestTransport._BaseGetCertificateAuthority, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.GetCertificateAuthority") + + @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: memorystore.GetCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.CertificateAuthority: + r"""Call the get certificate authority method over HTTP. + + Args: + request (~.memorystore.GetCertificateAuthorityRequest): + The request object. Request message for ``GetCertificateAuthority``. + 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: + ~.memorystore.CertificateAuthority: + A certificate authority for an + instance. + + """ + + http_options = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_http_options() + + request, metadata = self._interceptor.pre_get_certificate_authority( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._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.memorystore_v1beta.MemorystoreClient.GetCertificateAuthority", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetCertificateAuthority", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetCertificateAuthority._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 = memorystore.CertificateAuthority() + pb_resp = memorystore.CertificateAuthority.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_certificate_authority(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_certificate_authority_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.CertificateAuthority.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.memorystore_v1beta.MemorystoreClient.get_certificate_authority", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetCertificateAuthority", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetInstance( + _BaseMemorystoreRestTransport._BaseGetInstance, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.GetInstance") + + @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: memorystore.GetInstanceRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.Instance: + r"""Call the get instance method over HTTP. + + Args: + request (~.memorystore.GetInstanceRequest): + The request object. Request message for ``GetInstance``. + 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: + ~.memorystore.Instance: + A Memorystore instance. + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseGetInstance._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_instance(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseGetInstance._get_transcoded_request( + http_options, request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseMemorystoreRestTransport._BaseGetInstance._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.memorystore_v1beta.MemorystoreClient.GetInstance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetInstance", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetInstance._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 = memorystore.Instance() + pb_resp = memorystore.Instance.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_instance(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.Instance.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.memorystore_v1beta.MemorystoreClient.get_instance", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetInstance", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetSharedRegionalCertificateAuthority( + _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority, + MemorystoreRestStub, + ): + def __hash__(self): + return hash( + "MemorystoreRestTransport.GetSharedRegionalCertificateAuthority" + ) + + @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: memorystore.GetSharedRegionalCertificateAuthorityRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.SharedRegionalCertificateAuthority: + r"""Call the get shared regional + certificate authority method over HTTP. + + Args: + request (~.memorystore.GetSharedRegionalCertificateAuthorityRequest): + The request object. Request for ``GetSharedRegionalCertificateAuthority``. + 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: + ~.memorystore.SharedRegionalCertificateAuthority: + Shared regional certificate authority + for an instance. + + """ + + http_options = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_http_options() + + request, metadata = ( + self._interceptor.pre_get_shared_regional_certificate_authority( + request, metadata + ) + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._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.memorystore_v1beta.MemorystoreClient.GetSharedRegionalCertificateAuthority", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetSharedRegionalCertificateAuthority", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetSharedRegionalCertificateAuthority._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 = memorystore.SharedRegionalCertificateAuthority() + pb_resp = memorystore.SharedRegionalCertificateAuthority.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_shared_regional_certificate_authority( + resp + ) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = ( + self._interceptor.post_get_shared_regional_certificate_authority_with_metadata( + resp, response_metadata + ) + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = ( + memorystore.SharedRegionalCertificateAuthority.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.memorystore_v1beta.MemorystoreClient.get_shared_regional_certificate_authority", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetSharedRegionalCertificateAuthority", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _GetTokenAuthUser( + _BaseMemorystoreRestTransport._BaseGetTokenAuthUser, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.GetTokenAuthUser") + + @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: memorystore.GetTokenAuthUserRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.TokenAuthUser: + r"""Call the get token auth user method over HTTP. + + Args: + request (~.memorystore.GetTokenAuthUserRequest): + The request object. Request message for ``GetTokenAuthUser``. + 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: + ~.memorystore.TokenAuthUser: + Token based auth user for the + instance. + + """ + + http_options = ( + _BaseMemorystoreRestTransport._BaseGetTokenAuthUser._get_http_options() + ) + + request, metadata = self._interceptor.pre_get_token_auth_user( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseGetTokenAuthUser._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseGetTokenAuthUser._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.memorystore_v1beta.MemorystoreClient.GetTokenAuthUser", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetTokenAuthUser", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = MemorystoreRestTransport._GetTokenAuthUser._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 = memorystore.TokenAuthUser() + pb_resp = memorystore.TokenAuthUser.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_get_token_auth_user(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_get_token_auth_user_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.TokenAuthUser.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.memorystore_v1beta.MemorystoreClient.get_token_auth_user", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "GetTokenAuthUser", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListAuthTokens( + _BaseMemorystoreRestTransport._BaseListAuthTokens, MemorystoreRestStub + ): + def __hash__(self): + return hash("MemorystoreRestTransport.ListAuthTokens") + + @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: memorystore.ListAuthTokensRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> memorystore.ListAuthTokensResponse: + r"""Call the list auth tokens method over HTTP. + + Args: + request (~.memorystore.ListAuthTokensRequest): + The request object. Request message for ``ListAuthTokens``. + 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`. - @property - def operations_client(self) -> operations_v1.AbstractOperationsClient: - """Create the client designed to process long-running operations. + Returns: + ~.memorystore.ListAuthTokensResponse: + Response message for ``ListAuthTokens``. + """ - This property caches on the instance; repeated calls return the same - client. - """ - # Only create a new client if we do not already have one. - if self._operations_client is None: - http_options: Dict[str, List[Dict[str, str]]] = { - "google.longrunning.Operations.CancelOperation": [ - { - "method": "post", - "uri": "/v1beta/{name=projects/*/locations/*/operations/*}:cancel", - }, - ], - "google.longrunning.Operations.DeleteOperation": [ - { - "method": "delete", - "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.GetOperation": [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*/operations/*}", - }, - ], - "google.longrunning.Operations.ListOperations": [ - { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*}/operations", - }, - ], - } + http_options = ( + _BaseMemorystoreRestTransport._BaseListAuthTokens._get_http_options() + ) - rest_transport = operations_v1.OperationsRestTransport( - host=self._host, - # use the credentials which are saved - credentials=self._credentials, - scopes=self._scopes, - http_options=http_options, - path_prefix="v1beta", + request, metadata = self._interceptor.pre_list_auth_tokens( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseListAuthTokens._get_transcoded_request( + http_options, request ) - self._operations_client = operations_v1.AbstractOperationsClient( - transport=rest_transport + # Jsonify the query params + query_params = _BaseMemorystoreRestTransport._BaseListAuthTokens._get_query_params_json( + transcoded_request ) - # Return the client from cache. - return self._operations_client + 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.memorystore_v1beta.MemorystoreClient.ListAuthTokens", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "ListAuthTokens", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) - class _CreateInstance( - _BaseMemorystoreRestTransport._BaseCreateInstance, MemorystoreRestStub + # Send the request + response = MemorystoreRestTransport._ListAuthTokens._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 = memorystore.ListAuthTokensResponse() + pb_resp = memorystore.ListAuthTokensResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_auth_tokens(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_list_auth_tokens_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = memorystore.ListAuthTokensResponse.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.memorystore_v1beta.MemorystoreClient.list_auth_tokens", + extra={ + "serviceName": "google.cloud.memorystore.v1beta.Memorystore", + "rpcName": "ListAuthTokens", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + + class _ListBackupCollections( + _BaseMemorystoreRestTransport._BaseListBackupCollections, MemorystoreRestStub ): def __hash__(self): - return hash("MemorystoreRestTransport.CreateInstance") + return hash("MemorystoreRestTransport.ListBackupCollections") @staticmethod def _get_response( @@ -795,23 +4504,22 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), - data=body, ) return response def __call__( self, - request: memorystore.CreateInstanceRequest, + request: memorystore.ListBackupCollectionsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the create instance method over HTTP. + ) -> memorystore.ListBackupCollectionsResponse: + r"""Call the list backup collections method over HTTP. Args: - request (~.memorystore.CreateInstanceRequest): - The request object. Request message for [CreateInstance][]. + request (~.memorystore.ListBackupCollectionsRequest): + The request object. Request for ``ListBackupCollections``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -821,28 +4529,21 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.memorystore.ListBackupCollectionsResponse: + Response for ``ListBackupCollections``. """ - http_options = ( - _BaseMemorystoreRestTransport._BaseCreateInstance._get_http_options() - ) + http_options = _BaseMemorystoreRestTransport._BaseListBackupCollections._get_http_options() - request, metadata = self._interceptor.pre_create_instance(request, metadata) - transcoded_request = _BaseMemorystoreRestTransport._BaseCreateInstance._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_list_backup_collections( + request, metadata ) - - body = _BaseMemorystoreRestTransport._BaseCreateInstance._get_request_body_json( - transcoded_request + transcoded_request = _BaseMemorystoreRestTransport._BaseListBackupCollections._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = _BaseMemorystoreRestTransport._BaseCreateInstance._get_query_params_json( + query_params = _BaseMemorystoreRestTransport._BaseListBackupCollections._get_query_params_json( transcoded_request ) @@ -864,24 +4565,23 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.CreateInstance", + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.ListBackupCollections", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "CreateInstance", + "rpcName": "ListBackupCollections", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MemorystoreRestTransport._CreateInstance._get_response( + response = MemorystoreRestTransport._ListBackupCollections._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, - body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -890,19 +4590,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = memorystore.ListBackupCollectionsResponse() + pb_resp = memorystore.ListBackupCollectionsResponse.pb(resp) - resp = self._interceptor.post_create_instance(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backup_collections(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_create_instance_with_metadata( + resp, _ = self._interceptor.post_list_backup_collections_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = ( + memorystore.ListBackupCollectionsResponse.to_json(response) + ) except: response_payload = None http_response = { @@ -911,21 +4615,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.create_instance", + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.list_backup_collections", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "CreateInstance", + "rpcName": "ListBackupCollections", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _DeleteInstance( - _BaseMemorystoreRestTransport._BaseDeleteInstance, MemorystoreRestStub + class _ListBackups( + _BaseMemorystoreRestTransport._BaseListBackups, MemorystoreRestStub ): def __hash__(self): - return hash("MemorystoreRestTransport.DeleteInstance") + return hash("MemorystoreRestTransport.ListBackups") @staticmethod def _get_response( @@ -951,17 +4655,17 @@ def _get_response( def __call__( self, - request: memorystore.DeleteInstanceRequest, + request: memorystore.ListBackupsRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> operations_pb2.Operation: - r"""Call the delete instance method over HTTP. + ) -> memorystore.ListBackupsResponse: + r"""Call the list backups method over HTTP. Args: - request (~.memorystore.DeleteInstanceRequest): - The request object. Request message for [DeleteInstance][]. + request (~.memorystore.ListBackupsRequest): + The request object. Request for ``ListBackups``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -971,25 +4675,26 @@ def __call__( be of type `bytes`. Returns: - ~.operations_pb2.Operation: - This resource represents a - long-running operation that is the - result of a network API call. - + ~.memorystore.ListBackupsResponse: + Response for ``ListBackups``. """ http_options = ( - _BaseMemorystoreRestTransport._BaseDeleteInstance._get_http_options() + _BaseMemorystoreRestTransport._BaseListBackups._get_http_options() ) - request, metadata = self._interceptor.pre_delete_instance(request, metadata) - transcoded_request = _BaseMemorystoreRestTransport._BaseDeleteInstance._get_transcoded_request( - http_options, request + request, metadata = self._interceptor.pre_list_backups(request, metadata) + transcoded_request = ( + _BaseMemorystoreRestTransport._BaseListBackups._get_transcoded_request( + http_options, request + ) ) # Jsonify the query params - query_params = _BaseMemorystoreRestTransport._BaseDeleteInstance._get_query_params_json( - transcoded_request + query_params = ( + _BaseMemorystoreRestTransport._BaseListBackups._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1010,17 +4715,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.DeleteInstance", + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.ListBackups", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "DeleteInstance", + "rpcName": "ListBackups", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MemorystoreRestTransport._DeleteInstance._get_response( + response = MemorystoreRestTransport._ListBackups._get_response( self._host, metadata, query_params, @@ -1035,19 +4740,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = operations_pb2.Operation() - json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = memorystore.ListBackupsResponse() + pb_resp = memorystore.ListBackupsResponse.pb(resp) - resp = self._interceptor.post_delete_instance(resp) + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_list_backups(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_delete_instance_with_metadata( + resp, _ = self._interceptor.post_list_backups_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = json_format.MessageToJson(resp) + response_payload = memorystore.ListBackupsResponse.to_json(response) except: response_payload = None http_response = { @@ -1056,21 +4763,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.delete_instance", + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.list_backups", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "DeleteInstance", + "rpcName": "ListBackups", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetCertificateAuthority( - _BaseMemorystoreRestTransport._BaseGetCertificateAuthority, MemorystoreRestStub + class _ListInstances( + _BaseMemorystoreRestTransport._BaseListInstances, MemorystoreRestStub ): def __hash__(self): - return hash("MemorystoreRestTransport.GetCertificateAuthority") + return hash("MemorystoreRestTransport.ListInstances") @staticmethod def _get_response( @@ -1096,17 +4803,17 @@ def _get_response( def __call__( self, - request: memorystore.GetCertificateAuthorityRequest, + request: memorystore.ListInstancesRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> memorystore.CertificateAuthority: - r"""Call the get certificate authority method over HTTP. + ) -> memorystore.ListInstancesResponse: + r"""Call the list instances method over HTTP. Args: - request (~.memorystore.GetCertificateAuthorityRequest): - The request object. Request message for [GetCertificateAuthority][]. + request (~.memorystore.ListInstancesRequest): + The request object. Request message for ``ListInstances``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1116,24 +4823,24 @@ def __call__( be of type `bytes`. Returns: - ~.memorystore.CertificateAuthority: - A certificate authority for an - instance. - + ~.memorystore.ListInstancesResponse: + Response message for ``ListInstances``. """ - http_options = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_http_options() - - request, metadata = self._interceptor.pre_get_certificate_authority( - request, metadata + http_options = ( + _BaseMemorystoreRestTransport._BaseListInstances._get_http_options() ) - transcoded_request = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_transcoded_request( + + request, metadata = self._interceptor.pre_list_instances(request, metadata) + transcoded_request = _BaseMemorystoreRestTransport._BaseListInstances._get_transcoded_request( http_options, request ) # Jsonify the query params - query_params = _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_query_params_json( - transcoded_request + query_params = ( + _BaseMemorystoreRestTransport._BaseListInstances._get_query_params_json( + transcoded_request + ) ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1154,17 +4861,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.GetCertificateAuthority", + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.ListInstances", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "GetCertificateAuthority", + "rpcName": "ListInstances", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MemorystoreRestTransport._GetCertificateAuthority._get_response( + response = MemorystoreRestTransport._ListInstances._get_response( self._host, metadata, query_params, @@ -1179,21 +4886,21 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = memorystore.CertificateAuthority() - pb_resp = memorystore.CertificateAuthority.pb(resp) + resp = memorystore.ListInstancesResponse() + pb_resp = memorystore.ListInstancesResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_certificate_authority(resp) + resp = self._interceptor.post_list_instances(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_certificate_authority_with_metadata( + resp, _ = self._interceptor.post_list_instances_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = memorystore.CertificateAuthority.to_json( + response_payload = memorystore.ListInstancesResponse.to_json( response ) except: @@ -1204,21 +4911,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.get_certificate_authority", + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.list_instances", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "GetCertificateAuthority", + "rpcName": "ListInstances", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetInstance( - _BaseMemorystoreRestTransport._BaseGetInstance, MemorystoreRestStub + class _ListTokenAuthUsers( + _BaseMemorystoreRestTransport._BaseListTokenAuthUsers, MemorystoreRestStub ): def __hash__(self): - return hash("MemorystoreRestTransport.GetInstance") + return hash("MemorystoreRestTransport.ListTokenAuthUsers") @staticmethod def _get_response( @@ -1244,17 +4951,17 @@ def _get_response( def __call__( self, - request: memorystore.GetInstanceRequest, + request: memorystore.ListTokenAuthUsersRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> memorystore.Instance: - r"""Call the get instance method over HTTP. + ) -> memorystore.ListTokenAuthUsersResponse: + r"""Call the list token auth users method over HTTP. Args: - request (~.memorystore.GetInstanceRequest): - The request object. Request message for [GetInstance][]. + request (~.memorystore.ListTokenAuthUsersRequest): + The request object. Request message for ``ListTokenAuthUsers``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1264,26 +4971,22 @@ def __call__( be of type `bytes`. Returns: - ~.memorystore.Instance: - A Memorystore instance. + ~.memorystore.ListTokenAuthUsersResponse: + Response message for ``ListTokenAuthUsers``. """ - http_options = ( - _BaseMemorystoreRestTransport._BaseGetInstance._get_http_options() - ) + http_options = _BaseMemorystoreRestTransport._BaseListTokenAuthUsers._get_http_options() - request, metadata = self._interceptor.pre_get_instance(request, metadata) - transcoded_request = ( - _BaseMemorystoreRestTransport._BaseGetInstance._get_transcoded_request( - http_options, request - ) + request, metadata = self._interceptor.pre_list_token_auth_users( + request, metadata + ) + transcoded_request = _BaseMemorystoreRestTransport._BaseListTokenAuthUsers._get_transcoded_request( + http_options, request ) # Jsonify the query params - query_params = ( - _BaseMemorystoreRestTransport._BaseGetInstance._get_query_params_json( - transcoded_request - ) + query_params = _BaseMemorystoreRestTransport._BaseListTokenAuthUsers._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1304,17 +5007,17 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.GetInstance", + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.ListTokenAuthUsers", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "GetInstance", + "rpcName": "ListTokenAuthUsers", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MemorystoreRestTransport._GetInstance._get_response( + response = MemorystoreRestTransport._ListTokenAuthUsers._get_response( self._host, metadata, query_params, @@ -1329,21 +5032,23 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = memorystore.Instance() - pb_resp = memorystore.Instance.pb(resp) + resp = memorystore.ListTokenAuthUsersResponse() + pb_resp = memorystore.ListTokenAuthUsersResponse.pb(resp) json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_instance(resp) + resp = self._interceptor.post_list_token_auth_users(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_get_instance_with_metadata( + resp, _ = self._interceptor.post_list_token_auth_users_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = memorystore.Instance.to_json(response) + response_payload = memorystore.ListTokenAuthUsersResponse.to_json( + response + ) except: response_payload = None http_response = { @@ -1352,24 +5057,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.get_instance", + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.list_token_auth_users", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "GetInstance", + "rpcName": "ListTokenAuthUsers", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _GetSharedRegionalCertificateAuthority( - _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority, - MemorystoreRestStub, + class _RescheduleMaintenance( + _BaseMemorystoreRestTransport._BaseRescheduleMaintenance, MemorystoreRestStub ): def __hash__(self): - return hash( - "MemorystoreRestTransport.GetSharedRegionalCertificateAuthority" - ) + return hash("MemorystoreRestTransport.RescheduleMaintenance") @staticmethod def _get_response( @@ -1390,52 +5092,55 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: memorystore.GetSharedRegionalCertificateAuthorityRequest, + request: memorystore.RescheduleMaintenanceRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> memorystore.SharedRegionalCertificateAuthority: - r"""Call the get shared regional - certificate authority method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the reschedule maintenance method over HTTP. - Args: - request (~.memorystore.GetSharedRegionalCertificateAuthorityRequest): - The request object. Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. - 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`. + Args: + request (~.memorystore.RescheduleMaintenanceRequest): + The request object. Request for rescheduling instance + maintenance. + 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: - ~.memorystore.SharedRegionalCertificateAuthority: - Shared regional certificate authority - for an instance. + Returns: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. """ - http_options = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_http_options() + http_options = _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_http_options() - request, metadata = ( - self._interceptor.pre_get_shared_regional_certificate_authority( - request, metadata - ) + request, metadata = self._interceptor.pre_reschedule_maintenance( + request, metadata ) - transcoded_request = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_transcoded_request( + transcoded_request = _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_transcoded_request( http_options, request ) + body = _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_query_params_json( + query_params = _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_query_params_json( transcoded_request ) @@ -1457,23 +5162,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.GetSharedRegionalCertificateAuthority", + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.RescheduleMaintenance", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "GetSharedRegionalCertificateAuthority", + "rpcName": "RescheduleMaintenance", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MemorystoreRestTransport._GetSharedRegionalCertificateAuthority._get_response( + response = MemorystoreRestTransport._RescheduleMaintenance._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1482,27 +5188,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = memorystore.SharedRegionalCertificateAuthority() - pb_resp = memorystore.SharedRegionalCertificateAuthority.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_get_shared_regional_certificate_authority( - resp - ) + resp = self._interceptor.post_reschedule_maintenance(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = ( - self._interceptor.post_get_shared_regional_certificate_authority_with_metadata( - resp, response_metadata - ) + resp, _ = self._interceptor.post_reschedule_maintenance_with_metadata( + resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = ( - memorystore.SharedRegionalCertificateAuthority.to_json(response) - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1511,21 +5209,21 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.get_shared_regional_certificate_authority", + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.reschedule_maintenance", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "GetSharedRegionalCertificateAuthority", + "rpcName": "RescheduleMaintenance", "metadata": http_response["headers"], "httpResponse": http_response, }, ) return resp - class _ListInstances( - _BaseMemorystoreRestTransport._BaseListInstances, MemorystoreRestStub + class _StartMigration( + _BaseMemorystoreRestTransport._BaseStartMigration, MemorystoreRestStub ): def __hash__(self): - return hash("MemorystoreRestTransport.ListInstances") + return hash("MemorystoreRestTransport.StartMigration") @staticmethod def _get_response( @@ -1546,22 +5244,23 @@ def _get_response( timeout=timeout, headers=headers, params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, ) return response def __call__( self, - request: memorystore.ListInstancesRequest, + request: memorystore.StartMigrationRequest, *, retry: OptionalRetry = gapic_v1.method.DEFAULT, timeout: Optional[float] = None, metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), - ) -> memorystore.ListInstancesResponse: - r"""Call the list instances method over HTTP. + ) -> operations_pb2.Operation: + r"""Call the start migration method over HTTP. Args: - request (~.memorystore.ListInstancesRequest): - The request object. Request message for [ListInstances][]. + request (~.memorystore.StartMigrationRequest): + The request object. Request for ``StartMigration``. retry (google.api_core.retry.Retry): Designation of what errors, if any, should be retried. timeout (float): The timeout for this request. @@ -1571,24 +5270,29 @@ def __call__( be of type `bytes`. Returns: - ~.memorystore.ListInstancesResponse: - Response message for [ListInstances][]. + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + """ http_options = ( - _BaseMemorystoreRestTransport._BaseListInstances._get_http_options() + _BaseMemorystoreRestTransport._BaseStartMigration._get_http_options() ) - request, metadata = self._interceptor.pre_list_instances(request, metadata) - transcoded_request = _BaseMemorystoreRestTransport._BaseListInstances._get_transcoded_request( + request, metadata = self._interceptor.pre_start_migration(request, metadata) + transcoded_request = _BaseMemorystoreRestTransport._BaseStartMigration._get_transcoded_request( http_options, request ) + body = _BaseMemorystoreRestTransport._BaseStartMigration._get_request_body_json( + transcoded_request + ) + # Jsonify the query params - query_params = ( - _BaseMemorystoreRestTransport._BaseListInstances._get_query_params_json( - transcoded_request - ) + query_params = _BaseMemorystoreRestTransport._BaseStartMigration._get_query_params_json( + transcoded_request ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( @@ -1609,23 +5313,24 @@ def __call__( "headers": dict(metadata), } _LOGGER.debug( - f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.ListInstances", + f"Sending request for google.cloud.memorystore_v1beta.MemorystoreClient.StartMigration", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "ListInstances", + "rpcName": "StartMigration", "httpRequest": http_request, "metadata": http_request["headers"], }, ) # Send the request - response = MemorystoreRestTransport._ListInstances._get_response( + response = MemorystoreRestTransport._StartMigration._get_response( self._host, metadata, query_params, self._session, timeout, transcoded_request, + body, ) # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception @@ -1634,23 +5339,19 @@ def __call__( raise core_exceptions.from_http_response(response) # Return the response - resp = memorystore.ListInstancesResponse() - pb_resp = memorystore.ListInstancesResponse.pb(resp) - - json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) - resp = self._interceptor.post_list_instances(resp) + resp = self._interceptor.post_start_migration(resp) response_metadata = [(k, str(v)) for k, v in response.headers.items()] - resp, _ = self._interceptor.post_list_instances_with_metadata( + resp, _ = self._interceptor.post_start_migration_with_metadata( resp, response_metadata ) if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( logging.DEBUG ): # pragma: NO COVER try: - response_payload = memorystore.ListInstancesResponse.to_json( - response - ) + response_payload = json_format.MessageToJson(resp) except: response_payload = None http_response = { @@ -1659,10 +5360,10 @@ def __call__( "status": response.status_code, } _LOGGER.debug( - "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.list_instances", + "Received response for google.cloud.memorystore_v1beta.MemorystoreClient.start_migration", extra={ "serviceName": "google.cloud.memorystore.v1beta.Memorystore", - "rpcName": "ListInstances", + "rpcName": "StartMigration", "metadata": http_response["headers"], "httpResponse": http_response, }, @@ -1820,6 +5521,30 @@ def __call__( ) return resp + @property + def add_auth_token( + self, + ) -> Callable[[memorystore.AddAuthTokenRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddAuthToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def add_token_auth_user( + self, + ) -> Callable[[memorystore.AddTokenAuthUserRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._AddTokenAuthUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def backup_instance( + self, + ) -> Callable[[memorystore.BackupInstanceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._BackupInstance(self._session, self._host, self._interceptor) # type: ignore + @property def create_instance( self, @@ -1828,6 +5553,22 @@ def create_instance( # In C++ this would require a dynamic_cast return self._CreateInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_auth_token( + self, + ) -> Callable[[memorystore.DeleteAuthTokenRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteAuthToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def delete_backup( + self, + ) -> Callable[[memorystore.DeleteBackupRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteBackup(self._session, self._host, self._interceptor) # type: ignore + @property def delete_instance( self, @@ -1836,6 +5577,56 @@ def delete_instance( # In C++ this would require a dynamic_cast return self._DeleteInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def delete_token_auth_user( + self, + ) -> Callable[[memorystore.DeleteTokenAuthUserRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._DeleteTokenAuthUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def export_backup( + self, + ) -> Callable[[memorystore.ExportBackupRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._ExportBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def finish_migration( + self, + ) -> Callable[[memorystore.FinishMigrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._FinishMigration(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_auth_token( + self, + ) -> Callable[[memorystore.GetAuthTokenRequest], memorystore.AuthToken]: + # 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._GetAuthToken(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup( + self, + ) -> Callable[[memorystore.GetBackupRequest], memorystore.Backup]: + # 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._GetBackup(self._session, self._host, self._interceptor) # type: ignore + + @property + def get_backup_collection( + self, + ) -> Callable[ + [memorystore.GetBackupCollectionRequest], memorystore.BackupCollection + ]: + # 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._GetBackupCollection(self._session, self._host, self._interceptor) # type: ignore + @property def get_certificate_authority( self, @@ -1869,6 +5660,43 @@ def get_shared_regional_certificate_authority( self._session, self._host, self._interceptor ) # type: ignore + @property + def get_token_auth_user( + self, + ) -> Callable[[memorystore.GetTokenAuthUserRequest], memorystore.TokenAuthUser]: + # 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._GetTokenAuthUser(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_auth_tokens( + self, + ) -> Callable[ + [memorystore.ListAuthTokensRequest], memorystore.ListAuthTokensResponse + ]: + # 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._ListAuthTokens(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backup_collections( + self, + ) -> Callable[ + [memorystore.ListBackupCollectionsRequest], + memorystore.ListBackupCollectionsResponse, + ]: + # 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._ListBackupCollections(self._session, self._host, self._interceptor) # type: ignore + + @property + def list_backups( + self, + ) -> Callable[[memorystore.ListBackupsRequest], memorystore.ListBackupsResponse]: + # 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._ListBackups(self._session, self._host, self._interceptor) # type: ignore + @property def list_instances( self, @@ -1879,6 +5707,32 @@ def list_instances( # In C++ this would require a dynamic_cast return self._ListInstances(self._session, self._host, self._interceptor) # type: ignore + @property + def list_token_auth_users( + self, + ) -> Callable[ + [memorystore.ListTokenAuthUsersRequest], memorystore.ListTokenAuthUsersResponse + ]: + # 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._ListTokenAuthUsers(self._session, self._host, self._interceptor) # type: ignore + + @property + def reschedule_maintenance( + self, + ) -> Callable[[memorystore.RescheduleMaintenanceRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._RescheduleMaintenance(self._session, self._host, self._interceptor) # type: ignore + + @property + def start_migration( + self, + ) -> Callable[[memorystore.StartMigrationRequest], operations_pb2.Operation]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._StartMigration(self._session, self._host, self._interceptor) # type: ignore + @property def update_instance( self, diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py index 95f2c6a2e7bf..bf5014ef6ab6 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/services/memorystore/transports/rest_base.py @@ -89,6 +89,177 @@ def __init__( api_audience=api_audience, ) + class _BaseAddAuthToken: + 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": "post", + "uri": "/v1beta/{token_auth_user=projects/*/locations/*/instances/*/tokenAuthUsers/*}:addAuthToken", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.AddAuthTokenRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseAddAuthToken._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseAddTokenAuthUser: + 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": "post", + "uri": "/v1beta/{instance=projects/*/locations/*/instances/*}:addTokenAuthUser", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.AddTokenAuthUserRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseAddTokenAuthUser._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseBackupInstance: + 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": "post", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:backup", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.BackupInstanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseBackupInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseCreateInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -148,7 +319,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseDeleteInstance: + class _BaseDeleteAuthToken: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -167,14 +338,14 @@ def _get_http_options(): http_options: List[Dict[str, str]] = [ { "method": "delete", - "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*/authTokens/*}", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = memorystore.DeleteInstanceRequest.pb(request) + pb_request = memorystore.DeleteAuthTokenRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -187,7 +358,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseMemorystoreRestTransport._BaseDeleteInstance._get_unset_required_fields( + _BaseMemorystoreRestTransport._BaseDeleteAuthToken._get_unset_required_fields( query_params ) ) @@ -195,7 +366,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetCertificateAuthority: + class _BaseDeleteBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -213,15 +384,15 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*/instances/*}/certificateAuthority", + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/backupCollections/*/backups/*}", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = memorystore.GetCertificateAuthorityRequest.pb(request) + pb_request = memorystore.DeleteBackupRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -234,7 +405,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_unset_required_fields( + _BaseMemorystoreRestTransport._BaseDeleteBackup._get_unset_required_fields( query_params ) ) @@ -242,7 +413,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetInstance: + class _BaseDeleteInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -260,7 +431,7 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", + "method": "delete", "uri": "/v1beta/{name=projects/*/locations/*/instances/*}", }, ] @@ -268,7 +439,7 @@ def _get_http_options(): @staticmethod def _get_transcoded_request(http_options, request): - pb_request = memorystore.GetInstanceRequest.pb(request) + pb_request = memorystore.DeleteInstanceRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request @@ -281,7 +452,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseMemorystoreRestTransport._BaseGetInstance._get_unset_required_fields( + _BaseMemorystoreRestTransport._BaseDeleteInstance._get_unset_required_fields( query_params ) ) @@ -289,7 +460,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseGetSharedRegionalCertificateAuthority: + class _BaseDeleteTokenAuthUser: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -307,20 +478,75 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1beta/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}", + "method": "delete", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*}", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( - request + pb_request = memorystore.DeleteTokenAuthUserRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseDeleteTokenAuthUser._get_unset_required_fields( + query_params + ) ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseExportBackup: + 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": "post", + "uri": "/v1beta/{name=projects/*/locations/*/backupCollections/*/backups/*}:export", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.ExportBackupRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -330,7 +556,7 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_unset_required_fields( + _BaseMemorystoreRestTransport._BaseExportBackup._get_unset_required_fields( query_params ) ) @@ -338,7 +564,7 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params - class _BaseListInstances: + class _BaseFinishMigration: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -356,18 +582,28 @@ def _get_unset_required_fields(cls, message_dict): def _get_http_options(): http_options: List[Dict[str, str]] = [ { - "method": "get", - "uri": "/v1beta/{parent=projects/*/locations/*}/instances", + "method": "post", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:finishMigration", + "body": "*", }, ] return http_options @staticmethod def _get_transcoded_request(http_options, request): - pb_request = memorystore.ListInstancesRequest.pb(request) + pb_request = memorystore.FinishMigrationRequest.pb(request) transcoded_request = path_template.transcode(http_options, pb_request) return transcoded_request + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + @staticmethod def _get_query_params_json(transcoded_request): query_params = json.loads( @@ -377,7 +613,687 @@ def _get_query_params_json(transcoded_request): ) ) query_params.update( - _BaseMemorystoreRestTransport._BaseListInstances._get_unset_required_fields( + _BaseMemorystoreRestTransport._BaseFinishMigration._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetAuthToken: + 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": "/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*/authTokens/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetAuthTokenRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetAuthToken._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetBackup: + 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": "/v1beta/{name=projects/*/locations/*/backupCollections/*/backups/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetBackupRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetBackup._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetBackupCollection: + 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": "/v1beta/{name=projects/*/locations/*/backupCollections/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetBackupCollectionRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetBackupCollection._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetCertificateAuthority: + 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": "/v1beta/{name=projects/*/locations/*/instances/*}/certificateAuthority", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetCertificateAuthorityRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetInstance: + 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": "/v1beta/{name=projects/*/locations/*/instances/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetInstanceRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetInstance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetSharedRegionalCertificateAuthority: + 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": "/v1beta/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetSharedRegionalCertificateAuthorityRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetSharedRegionalCertificateAuthority._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseGetTokenAuthUser: + 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": "/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*}", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.GetTokenAuthUserRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseGetTokenAuthUser._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListAuthTokens: + 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": "/v1beta/{parent=projects/*/locations/*/instances/*/tokenAuthUsers/*}/authTokens", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.ListAuthTokensRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseListAuthTokens._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListBackupCollections: + 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": "/v1beta/{parent=projects/*/locations/*}/backupCollections", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.ListBackupCollectionsRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseListBackupCollections._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListBackups: + 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": "/v1beta/{parent=projects/*/locations/*/backupCollections/*}/backups", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.ListBackupsRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseListBackups._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListInstances: + 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": "/v1beta/{parent=projects/*/locations/*}/instances", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.ListInstancesRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseListInstances._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseListTokenAuthUsers: + 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": "/v1beta/{parent=projects/*/locations/*/instances/*}/tokenAuthUsers", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.ListTokenAuthUsersRequest.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=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseListTokenAuthUsers._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseRescheduleMaintenance: + 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": "post", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.RescheduleMaintenanceRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseRescheduleMaintenance._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + + class _BaseStartMigration: + 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": "post", + "uri": "/v1beta/{name=projects/*/locations/*/instances/*}:startMigration", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = memorystore.StartMigrationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseMemorystoreRestTransport._BaseStartMigration._get_unset_required_fields( query_params ) ) diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py index 06b17dda695c..8d49cd84fd47 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/__init__.py @@ -14,46 +14,118 @@ # limitations under the License. # from .memorystore import ( + AddAuthTokenRequest, + AddTokenAuthUserRequest, + AuthToken, + AutomatedBackupConfig, + Backup, + BackupCollection, + BackupFile, + BackupInstanceRequest, CertificateAuthority, ConnectionType, CreateInstanceRequest, + CrossInstanceReplicationConfig, + DeleteAuthTokenRequest, + DeleteBackupRequest, DeleteInstanceRequest, + DeleteTokenAuthUserRequest, DiscoveryEndpoint, + EncryptionInfo, + ExportBackupRequest, + FinishMigrationRequest, + GetAuthTokenRequest, + GetBackupCollectionRequest, + GetBackupRequest, GetCertificateAuthorityRequest, GetInstanceRequest, GetSharedRegionalCertificateAuthorityRequest, + GetTokenAuthUserRequest, Instance, + ListAuthTokensRequest, + ListAuthTokensResponse, + ListBackupCollectionsRequest, + ListBackupCollectionsResponse, + ListBackupsRequest, + ListBackupsResponse, ListInstancesRequest, ListInstancesResponse, + ListTokenAuthUsersRequest, + ListTokenAuthUsersResponse, + MaintenancePolicy, + MaintenanceSchedule, + MigrationConfig, NodeConfig, OperationMetadata, PersistenceConfig, + PscAttachmentDetail, PscAutoConnection, PscConnection, PscConnectionStatus, + RescheduleMaintenanceRequest, + SelfManagedSource, SharedRegionalCertificateAuthority, + StartMigrationRequest, + TokenAuthUser, UpdateInstanceRequest, + WeeklyMaintenanceWindow, ZoneDistributionConfig, ) __all__ = ( + "AddAuthTokenRequest", + "AddTokenAuthUserRequest", + "AuthToken", + "AutomatedBackupConfig", + "Backup", + "BackupCollection", + "BackupFile", + "BackupInstanceRequest", "CertificateAuthority", "CreateInstanceRequest", + "CrossInstanceReplicationConfig", + "DeleteAuthTokenRequest", + "DeleteBackupRequest", "DeleteInstanceRequest", + "DeleteTokenAuthUserRequest", "DiscoveryEndpoint", + "EncryptionInfo", + "ExportBackupRequest", + "FinishMigrationRequest", + "GetAuthTokenRequest", + "GetBackupCollectionRequest", + "GetBackupRequest", "GetCertificateAuthorityRequest", "GetInstanceRequest", "GetSharedRegionalCertificateAuthorityRequest", + "GetTokenAuthUserRequest", "Instance", + "ListAuthTokensRequest", + "ListAuthTokensResponse", + "ListBackupCollectionsRequest", + "ListBackupCollectionsResponse", + "ListBackupsRequest", + "ListBackupsResponse", "ListInstancesRequest", "ListInstancesResponse", + "ListTokenAuthUsersRequest", + "ListTokenAuthUsersResponse", + "MaintenancePolicy", + "MaintenanceSchedule", + "MigrationConfig", "NodeConfig", "OperationMetadata", "PersistenceConfig", + "PscAttachmentDetail", "PscAutoConnection", "PscConnection", + "RescheduleMaintenanceRequest", + "SelfManagedSource", "SharedRegionalCertificateAuthority", + "StartMigrationRequest", + "TokenAuthUser", "UpdateInstanceRequest", + "WeeklyMaintenanceWindow", "ZoneDistributionConfig", "ConnectionType", "PscConnectionStatus", diff --git a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py index d4aa56f321f5..074c9497083f 100644 --- a/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py +++ b/packages/google-cloud-memorystore/google/cloud/memorystore_v1beta/types/memorystore.py @@ -17,8 +17,11 @@ from typing import MutableMapping, MutableSequence +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.dayofweek_pb2 as dayofweek_pb2 # type: ignore +import google.type.timeofday_pb2 as timeofday_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -27,23 +30,59 @@ "PscConnectionStatus", "ConnectionType", "Instance", + "StartMigrationRequest", + "FinishMigrationRequest", + "SelfManagedSource", + "MigrationConfig", + "AutomatedBackupConfig", + "BackupCollection", + "Backup", + "BackupFile", + "CrossInstanceReplicationConfig", + "TokenAuthUser", + "AuthToken", + "MaintenancePolicy", + "WeeklyMaintenanceWindow", + "MaintenanceSchedule", + "PscAttachmentDetail", "PscAutoConnection", "PscConnection", "DiscoveryEndpoint", "PersistenceConfig", "NodeConfig", "ZoneDistributionConfig", + "RescheduleMaintenanceRequest", "ListInstancesRequest", "ListInstancesResponse", "GetInstanceRequest", "CreateInstanceRequest", "UpdateInstanceRequest", "DeleteInstanceRequest", + "ListBackupCollectionsRequest", + "ListBackupCollectionsResponse", + "GetBackupCollectionRequest", + "ListBackupsRequest", + "ListBackupsResponse", + "GetBackupRequest", + "DeleteBackupRequest", + "ExportBackupRequest", + "BackupInstanceRequest", "GetCertificateAuthorityRequest", + "ListTokenAuthUsersRequest", + "ListTokenAuthUsersResponse", + "GetTokenAuthUserRequest", + "ListAuthTokensRequest", + "ListAuthTokensResponse", + "GetAuthTokenRequest", + "AddTokenAuthUserRequest", + "DeleteTokenAuthUserRequest", + "AddAuthTokenRequest", + "DeleteAuthTokenRequest", "CertificateAuthority", "SharedRegionalCertificateAuthority", "GetSharedRegionalCertificateAuthorityRequest", "OperationMetadata", + "EncryptionInfo", }, ) @@ -91,9 +130,27 @@ class ConnectionType(proto.Enum): class Instance(proto.Message): r"""A Memorystore instance. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: + gcs_source (google.cloud.memorystore_v1beta.types.Instance.GcsBackupSource): + Optional. Immutable. Backups that stored in + Cloud Storage buckets. The Cloud Storage buckets + need to be the same region as the instances. + Read permission is required to import from the + provided Cloud Storage Objects. + + This field is a member of `oneof`_ ``import_sources``. + managed_backup_source (google.cloud.memorystore_v1beta.types.Instance.ManagedBackupSource): + Optional. Immutable. Backups that generated + and managed by memorystore service. + + This field is a member of `oneof`_ ``import_sources``. name (str): Identifier. Unique name of the instance. Format: @@ -129,18 +186,21 @@ class Instance(proto.Message): shard_count (int): Optional. Number of shards for the instance. discovery_endpoints (MutableSequence[google.cloud.memorystore_v1beta.types.DiscoveryEndpoint]): - Output only. Endpoints clients can connect to - the instance through. Currently only one - discovery endpoint is supported. + Output only. Deprecated: The discovery_endpoints parameter + is deprecated. As a result, it will not be populated if the + connections are created using endpoints parameter. Instead + of this parameter, for discovery, use + endpoints.connections.pscConnection and + endpoints.connections.pscAutoConnection with connectionType + CONNECTION_TYPE_DISCOVERY. node_type (google.cloud.memorystore_v1beta.types.Instance.NodeType): - Optional. Immutable. Machine type for - individual nodes of the instance. + Optional. Machine type for individual nodes + of the instance. persistence_config (google.cloud.memorystore_v1beta.types.PersistenceConfig): Optional. Persistence configuration of the instance. engine_version (str): - Optional. Immutable. Engine version of the - instance. + Optional. Engine version of the instance. engine_configs (MutableMapping[str, str]): Optional. User-provided engine configurations for the instance. @@ -157,12 +217,90 @@ class Instance(proto.Message): This field is a member of `oneof`_ ``_deletion_protection_enabled``. psc_auto_connections (MutableSequence[google.cloud.memorystore_v1beta.types.PscAutoConnection]): - Required. Immutable. User inputs and resource - details of the auto-created PSC connections. + Optional. Immutable. Deprecated: Use the + endpoints.connections.psc_auto_connection value instead. + psc_attachment_details (MutableSequence[google.cloud.memorystore_v1beta.types.PscAttachmentDetail]): + Output only. Service attachment details to + configure PSC connections. endpoints (MutableSequence[google.cloud.memorystore_v1beta.types.Instance.InstanceEndpoint]): Optional. Endpoints for the instance. mode (google.cloud.memorystore_v1beta.types.Instance.Mode): - Optional. The mode config for the instance. + Optional. Immutable. The mode config for the + instance. + simulate_maintenance_event (bool): + Optional. Input only. Simulate a maintenance + event. + + This field is a member of `oneof`_ ``_simulate_maintenance_event``. + ondemand_maintenance (bool): + Optional. Input only. Ondemand maintenance + for the instance. + + This field is a member of `oneof`_ ``_ondemand_maintenance``. + satisfies_pzs (bool): + Optional. Output only. Reserved for future + use. + + This field is a member of `oneof`_ ``_satisfies_pzs``. + satisfies_pzi (bool): + Optional. Output only. Reserved for future + use. + + This field is a member of `oneof`_ ``_satisfies_pzi``. + maintenance_policy (google.cloud.memorystore_v1beta.types.MaintenancePolicy): + Optional. The maintenance policy for the + instance. If not provided, the maintenance event + will be performed based on Memorystore internal + rollout schedule. + maintenance_schedule (google.cloud.memorystore_v1beta.types.MaintenanceSchedule): + Output only. Published maintenance schedule. + cross_instance_replication_config (google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig): + Optional. The config for cross instance + replication. + async_instance_endpoints_deletion_enabled (bool): + Optional. If true, instance endpoints that + are created and registered by customers can be + deleted asynchronously. That is, such an + instance endpoint can be de-registered before + the forwarding rules in the instance endpoint + are deleted. + + This field is a member of `oneof`_ ``_async_instance_endpoints_deletion_enabled``. + kms_key (str): + Optional. The KMS key used to encrypt the + at-rest data of the cluster. + + This field is a member of `oneof`_ ``_kms_key``. + encryption_info (google.cloud.memorystore_v1beta.types.EncryptionInfo): + Output only. Encryption information of the + data at rest of the cluster. + backup_collection (str): + Output only. The backup collection full + resource name. Example: + projects/{project}/locations/{location}/backupCollections/{collection} + + This field is a member of `oneof`_ ``_backup_collection``. + automated_backup_config (google.cloud.memorystore_v1beta.types.AutomatedBackupConfig): + Optional. The automated backup config for the + instance. + maintenance_version (str): + Optional. This field can be used to trigger self service + update to indicate the desired maintenance version. The + input to this field can be determined by the + available_maintenance_versions field. + + This field is a member of `oneof`_ ``_maintenance_version``. + effective_maintenance_version (str): + Output only. This field represents the actual + maintenance version of the instance. + + This field is a member of `oneof`_ ``_effective_maintenance_version``. + available_maintenance_versions (MutableSequence[str]): + Output only. This field is used to determine + the available maintenance versions for the self + service update. + allow_fewer_zones_deployment (bool): + Optional. Immutable. Deprecated, do not use. server_ca_mode (google.cloud.memorystore_v1beta.types.Instance.ServerCaMode): Optional. Immutable. The Server CA mode for the instance. @@ -180,6 +318,9 @@ class Instance(proto.Message): certificates. This field is a member of `oneof`_ ``_rotate_server_certificate``. + migration_config (google.cloud.memorystore_v1beta.types.MigrationConfig): + Output only. Migration config for the + instance. """ class State(proto.Enum): @@ -196,6 +337,8 @@ class State(proto.Enum): Instance is being updated. DELETING (4): Instance is being deleted. + MIGRATING (6): + Instance is being migrated. """ STATE_UNSPECIFIED = 0 @@ -203,6 +346,7 @@ class State(proto.Enum): ACTIVE = 2 UPDATING = 3 DELETING = 4 + MIGRATING = 6 class AuthorizationMode(proto.Enum): r"""Possible authorization modes of the instance. @@ -214,11 +358,14 @@ class AuthorizationMode(proto.Enum): Authorization disabled. IAM_AUTH (2): IAM basic authorization. + TOKEN_AUTH (3): + Token based authorization. """ AUTHORIZATION_MODE_UNSPECIFIED = 0 AUTH_DISABLED = 1 IAM_AUTH = 2 + TOKEN_AUTH = 3 class TransitEncryptionMode(proto.Enum): r"""Possible in-transit encryption modes of the instance. @@ -359,6 +506,16 @@ class UpdateInfo(proto.Message): per shard for the instance. This field is a member of `oneof`_ ``_target_replica_count``. + target_engine_version (str): + Output only. Target engine version for the + instance. + + This field is a member of `oneof`_ ``_target_engine_version``. + target_node_type (google.cloud.memorystore_v1beta.types.Instance.NodeType): + Output only. Target node type for the + instance. + + This field is a member of `oneof`_ ``_target_node_type``. """ target_shard_count: int = proto.Field( @@ -371,6 +528,17 @@ class UpdateInfo(proto.Message): number=2, optional=True, ) + target_engine_version: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) + target_node_type: "Instance.NodeType" = proto.Field( + proto.ENUM, + number=4, + optional=True, + enum="Instance.NodeType", + ) update_info: "Instance.StateInfo.UpdateInfo" = proto.Field( proto.MESSAGE, @@ -379,6 +547,41 @@ class UpdateInfo(proto.Message): message="Instance.StateInfo.UpdateInfo", ) + class GcsBackupSource(proto.Message): + r"""Backups that stored in Cloud Storage buckets. + The Cloud Storage buckets need to be the same region as the + instances. + + Attributes: + uris (MutableSequence[str]): + Optional. Example: gs://bucket1/object1, + gs://bucket2/folder2/object2 + """ + + uris: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=1, + ) + + class ManagedBackupSource(proto.Message): + r"""Backups that generated and managed by memorystore. + + Attributes: + backup (str): + Optional. Example: + //memorystore.googleapis.com/projects/{project}/locations/{location}/backupCollections/{collection}/backups/{backup} + A shorter version (without the prefix) of the backup name is + also supported, like + projects/{project}/locations/{location}/backupCollections/{collection}/backups/{backup_id} + In this case, it assumes the backup is under + memorystore.googleapis.com. + """ + + backup: str = proto.Field( + proto.STRING, + number=1, + ) + class InstanceEndpoint(proto.Message): r"""InstanceEndpoint consists of PSC connections that are created as a group in each VPC network for accessing the instance. In @@ -410,9 +613,9 @@ class ConnectionDetail(proto.Message): Attributes: psc_auto_connection (google.cloud.memorystore_v1beta.types.PscAutoConnection): - Detailed information of a PSC connection that - is created through service connectivity - automation. + Immutable. Detailed information of a PSC + connection that is created through service + connectivity automation. This field is a member of `oneof`_ ``connection``. psc_connection (google.cloud.memorystore_v1beta.types.PscConnection): @@ -435,6 +638,18 @@ class ConnectionDetail(proto.Message): message="PscConnection", ) + gcs_source: GcsBackupSource = proto.Field( + proto.MESSAGE, + number=23, + oneof="import_sources", + message=GcsBackupSource, + ) + managed_backup_source: ManagedBackupSource = proto.Field( + proto.MESSAGE, + number=24, + oneof="import_sources", + message=ManagedBackupSource, + ) name: str = proto.Field( proto.STRING, number=1, @@ -531,6 +746,13 @@ class ConnectionDetail(proto.Message): number=20, message="PscAutoConnection", ) + psc_attachment_details: MutableSequence["PscAttachmentDetail"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=21, + message="PscAttachmentDetail", + ) + ) endpoints: MutableSequence[InstanceEndpoint] = proto.RepeatedField( proto.MESSAGE, number=25, @@ -541,6 +763,84 @@ class ConnectionDetail(proto.Message): number=26, enum=Mode, ) + simulate_maintenance_event: bool = proto.Field( + proto.BOOL, + number=27, + optional=True, + ) + ondemand_maintenance: bool = proto.Field( + proto.BOOL, + number=28, + optional=True, + ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=29, + optional=True, + ) + satisfies_pzi: bool = proto.Field( + proto.BOOL, + number=30, + optional=True, + ) + maintenance_policy: "MaintenancePolicy" = proto.Field( + proto.MESSAGE, + number=31, + message="MaintenancePolicy", + ) + maintenance_schedule: "MaintenanceSchedule" = proto.Field( + proto.MESSAGE, + number=32, + message="MaintenanceSchedule", + ) + cross_instance_replication_config: "CrossInstanceReplicationConfig" = proto.Field( + proto.MESSAGE, + number=33, + message="CrossInstanceReplicationConfig", + ) + async_instance_endpoints_deletion_enabled: bool = proto.Field( + proto.BOOL, + number=44, + optional=True, + ) + kms_key: str = proto.Field( + proto.STRING, + number=45, + optional=True, + ) + encryption_info: "EncryptionInfo" = proto.Field( + proto.MESSAGE, + number=46, + message="EncryptionInfo", + ) + backup_collection: str = proto.Field( + proto.STRING, + number=47, + optional=True, + ) + automated_backup_config: "AutomatedBackupConfig" = proto.Field( + proto.MESSAGE, + number=48, + message="AutomatedBackupConfig", + ) + maintenance_version: str = proto.Field( + proto.STRING, + number=49, + optional=True, + ) + effective_maintenance_version: str = proto.Field( + proto.STRING, + number=50, + optional=True, + ) + available_maintenance_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=51, + ) + allow_fewer_zones_deployment: bool = proto.Field( + proto.BOOL, + number=54, + ) server_ca_mode: ServerCaMode = proto.Field( proto.ENUM, number=56, @@ -557,185 +857,99 @@ class ConnectionDetail(proto.Message): number=58, optional=True, ) + migration_config: "MigrationConfig" = proto.Field( + proto.MESSAGE, + number=59, + message="MigrationConfig", + ) -class PscAutoConnection(proto.Message): - r"""Details of consumer resources in a PSC connection. +class StartMigrationRequest(proto.Message): + r"""Request for ``StartMigration``. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - port (int): - Optional. Output only. port will only be set - for Primary/Reader or Discovery endpoint. + self_managed_source (google.cloud.memorystore_v1beta.types.SelfManagedSource): + Required. Configuration for migrating from a + self-managed Valkey/Redis instance - This field is a member of `oneof`_ ``ports``. - psc_connection_id (str): - Output only. The PSC connection id of the - forwarding rule connected to the service - attachment. - ip_address (str): - Output only. The IP allocated on the consumer - network for the PSC forwarding rule. - forwarding_rule (str): - Output only. The URI of the consumer side forwarding rule. - Format: - projects/{project}/regions/{region}/forwardingRules/{forwarding_rule} - project_id (str): - Required. The consumer project_id where PSC connections are - established. This should be the same project_id that the - instance is being created in. - network (str): - Required. The network where the PSC endpoints are created, - in the form of - projects/{project_id}/global/networks/{network_id}. - service_attachment (str): - Output only. The service attachment which is - the target of the PSC connection, in the form of - projects/{project-id}/regions/{region}/serviceAttachments/{service-attachment-id}. - psc_connection_status (google.cloud.memorystore_v1beta.types.PscConnectionStatus): - Output only. The status of the PSC - connection: whether a connection exists and - ACTIVE or it no longer exists. Please note that - this value is updated periodically. Please use - Private Service Connect APIs for the latest - status. - connection_type (google.cloud.memorystore_v1beta.types.ConnectionType): - Output only. Type of the PSC connection. + This field is a member of `oneof`_ ``source``. + name (str): + Required. The resource name of the instance + to start migration on. Format: + projects/{project}/locations/{location}/instances/{instance} """ - port: int = proto.Field( - proto.INT32, - number=9, - oneof="ports", - ) - psc_connection_id: str = proto.Field( - proto.STRING, - number=1, - ) - ip_address: str = proto.Field( - proto.STRING, + self_managed_source: "SelfManagedSource" = proto.Field( + proto.MESSAGE, number=2, + oneof="source", + message="SelfManagedSource", ) - forwarding_rule: str = proto.Field( - proto.STRING, - number=3, - ) - project_id: str = proto.Field( - proto.STRING, - number=4, - ) - network: str = proto.Field( - proto.STRING, - number=5, - ) - service_attachment: str = proto.Field( + name: str = proto.Field( proto.STRING, - number=6, - ) - psc_connection_status: "PscConnectionStatus" = proto.Field( - proto.ENUM, - number=7, - enum="PscConnectionStatus", - ) - connection_type: "ConnectionType" = proto.Field( - proto.ENUM, - number=8, - enum="ConnectionType", + number=1, ) -class PscConnection(proto.Message): - r"""User created Psc connection configuration. +class FinishMigrationRequest(proto.Message): + r"""Request for ``FinishMigration``. Attributes: - psc_connection_id (str): - Output only. The PSC connection id of the - forwarding rule connected to the service - attachment. - ip_address (str): - Required. The IP allocated on the consumer - network for the PSC forwarding rule. - forwarding_rule (str): - Required. The URI of the consumer side forwarding rule. - Format: - projects/{project}/regions/{region}/forwardingRules/{forwarding_rule} - project_id (str): - Output only. The consumer project_id where the forwarding - rule is created from. - network (str): - Required. The consumer network where the IP address resides, - in the form of - projects/{project_id}/global/networks/{network_id}. - service_attachment (str): - Required. The service attachment which is the - target of the PSC connection, in the form of - projects/{project-id}/regions/{region}/serviceAttachments/{service-attachment-id}. - psc_connection_status (google.cloud.memorystore_v1beta.types.PscConnectionStatus): - Output only. The status of the PSC - connection: whether a connection exists and - ACTIVE or it no longer exists. Please note that - this value is updated periodically. Please use - Private Service Connect APIs for the latest - status. - connection_type (google.cloud.memorystore_v1beta.types.ConnectionType): - Output only. Type of the PSC connection. + name (str): + Required. The resource name of the instance + to finalize migration on. Format: + projects/{project}/locations/{location}/instances/{instance} + force (bool): + Optional. By default, the ``FinishMigration`` operation + ensures the target replication offset to catch up to the + source offset as of the time of the call. Set this field to + ``true`` to bypass this offset verification check. """ - psc_connection_id: str = proto.Field( + name: str = proto.Field( proto.STRING, number=1, ) - ip_address: str = proto.Field( - proto.STRING, + force: bool = proto.Field( + proto.BOOL, number=2, ) - forwarding_rule: str = proto.Field( - proto.STRING, - number=3, - ) - project_id: str = proto.Field( - proto.STRING, - number=4, - ) - network: str = proto.Field( - proto.STRING, - number=5, - ) - service_attachment: str = proto.Field( - proto.STRING, - number=6, - ) - psc_connection_status: "PscConnectionStatus" = proto.Field( - proto.ENUM, - number=7, - enum="PscConnectionStatus", - ) - connection_type: "ConnectionType" = proto.Field( - proto.ENUM, - number=8, - enum="ConnectionType", - ) -class DiscoveryEndpoint(proto.Message): - r"""Represents an endpoint for clients to connect to the - instance. +class SelfManagedSource(proto.Message): + r"""Details of the self-managed source instance. Attributes: - address (str): - Output only. IP address of the exposed - endpoint clients connect to. + ip_address (str): + Required. The IP address of the source + instance. This IP address should be a stable IP + address that can be accessed by the Memorystore + instance throughout the migration process. port (int): - Output only. The port number of the exposed - endpoint. - network (str): - Output only. The network where the IP address of the - discovery endpoint will be reserved, in the form of - projects/{network_project}/global/networks/{network_id}. + Required. The port of the source instance. + This port should be a stable port that can be + accessed by the Memorystore instance throughout + the migration process. + network_attachment (str): + Required. The resource name of the Private Service Connect + Network Attachment used to establish connectivity to the + source instance. This network attachment has the following + requirements: + + 1. It must be in the same project as the Memorystore + instance. + 2. It must be in the same region as the Memorystore + instance. + 3. The subnet attached to the network attachment must be in + the same VPC network as the source instance nodes. + + Format: + projects/{project}/regions/{region}/networkAttachments/{network_attachment} """ - address: str = proto.Field( + ip_address: str = proto.Field( proto.STRING, number=1, ) @@ -743,223 +957,1765 @@ class DiscoveryEndpoint(proto.Message): proto.INT32, number=2, ) - network: str = proto.Field( + network_attachment: str = proto.Field( proto.STRING, - number=4, + number=3, ) -class PersistenceConfig(proto.Message): - r"""Represents persistence configuration for a instance. +class MigrationConfig(proto.Message): + r"""Configuration for the migration of an instance. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields Attributes: - mode (google.cloud.memorystore_v1beta.types.PersistenceConfig.PersistenceMode): - Optional. Current persistence mode. - rdb_config (google.cloud.memorystore_v1beta.types.PersistenceConfig.RDBConfig): - Optional. RDB configuration. This field will - be ignored if mode is not RDB. - aof_config (google.cloud.memorystore_v1beta.types.PersistenceConfig.AOFConfig): - Optional. AOF configuration. This field will - be ignored if mode is not AOF. + self_managed_source (google.cloud.memorystore_v1beta.types.SelfManagedSource): + Output only. Configuration for migrating from + a self-managed Valkey/Redis instance + + This field is a member of `oneof`_ ``source``. + state (google.cloud.memorystore_v1beta.types.MigrationConfig.State): + Output only. Migration state of the instance. + force_finish_migration (bool): + Output only. Represents a boolean flag to + force migration finalization without offset + catch up validation between source and target + before stopping replication. """ - class PersistenceMode(proto.Enum): - r"""Possible persistence modes. + class State(proto.Enum): + r"""Migration state of the instance. + New values may be added in the future. Values: - PERSISTENCE_MODE_UNSPECIFIED (0): - Not set. - DISABLED (1): - Persistence is disabled, and any snapshot - data is deleted. - RDB (2): - RDB based persistence is enabled. - AOF (3): - AOF based persistence is enabled. + STATE_UNSPECIFIED (0): + Instance has no migration related activity. + This is the initial state. + ROLLED_BACK (1): + Instance is not currently migrating. The + instance underwent a migration attempt that + failed, and the subsequent rollback was + successful. The instance is now ready for a new + migration attempt if desired. + ROLLING_BACK (5): + Indicates a previous migration attempt failed. The + high-level instance state will be ``MIGRATING``. The + instance is not ready for a new migration attempt. Rollback + is in progress to restore the instance to its original + state. The instance will remain in this state until rollback + is successful. + REPLICATION_ESTABLISHED (6): + Instance is in the process of migration. + Instance has established successful replication + and is ready for cutover. + MIGRATED (4): + Instance is successfully migrated. """ - PERSISTENCE_MODE_UNSPECIFIED = 0 - DISABLED = 1 - RDB = 2 - AOF = 3 + STATE_UNSPECIFIED = 0 + ROLLED_BACK = 1 + ROLLING_BACK = 5 + REPLICATION_ESTABLISHED = 6 + MIGRATED = 4 - class RDBConfig(proto.Message): - r"""Configuration for RDB based persistence. + self_managed_source: "SelfManagedSource" = proto.Field( + proto.MESSAGE, + number=2, + oneof="source", + message="SelfManagedSource", + ) + state: State = proto.Field( + proto.ENUM, + number=1, + enum=State, + ) + force_finish_migration: bool = proto.Field( + proto.BOOL, + number=4, + ) - Attributes: - rdb_snapshot_period (google.cloud.memorystore_v1beta.types.PersistenceConfig.RDBConfig.SnapshotPeriod): - Optional. Period between RDB snapshots. - rdb_snapshot_start_time (google.protobuf.timestamp_pb2.Timestamp): - Optional. Time that the first snapshot - was/will be attempted, and to which future - snapshots will be aligned. If not provided, the - current time will be used. + +class AutomatedBackupConfig(proto.Message): + r"""The automated backup config for an instance. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + fixed_frequency_schedule (google.cloud.memorystore_v1beta.types.AutomatedBackupConfig.FixedFrequencySchedule): + Optional. Trigger automated backups at a + fixed frequency. + + This field is a member of `oneof`_ ``schedule``. + automated_backup_mode (google.cloud.memorystore_v1beta.types.AutomatedBackupConfig.AutomatedBackupMode): + Optional. The automated backup mode. If the + mode is disabled, the other fields will be + ignored. + retention (google.protobuf.duration_pb2.Duration): + Optional. How long to keep automated backups + before the backups are deleted. The value should + be between 1 day and 365 days. If not specified, + the default value is 35 days. + """ + + class AutomatedBackupMode(proto.Enum): + r"""The automated backup mode. + + Values: + AUTOMATED_BACKUP_MODE_UNSPECIFIED (0): + Default value. Automated backup config is not + specified. + DISABLED (1): + Automated backup config disabled. + ENABLED (2): + Automated backup config enabled. """ - class SnapshotPeriod(proto.Enum): - r"""Possible snapshot periods. + AUTOMATED_BACKUP_MODE_UNSPECIFIED = 0 + DISABLED = 1 + ENABLED = 2 - Values: - SNAPSHOT_PERIOD_UNSPECIFIED (0): - Not set. - ONE_HOUR (1): - One hour. - SIX_HOURS (2): - Six hours. - TWELVE_HOURS (3): - Twelve hours. - TWENTY_FOUR_HOURS (4): - Twenty four hours. - """ + class FixedFrequencySchedule(proto.Message): + r"""This schedule allows the backup to be triggered at a fixed + frequency (currently only daily is supported). - SNAPSHOT_PERIOD_UNSPECIFIED = 0 - ONE_HOUR = 1 - SIX_HOURS = 2 - TWELVE_HOURS = 3 - TWENTY_FOUR_HOURS = 4 + Attributes: + start_time (google.type.timeofday_pb2.TimeOfDay): + Required. The start time of every automated + backup in UTC. It must be set to the start of an + hour. This field is required. + """ - rdb_snapshot_period: "PersistenceConfig.RDBConfig.SnapshotPeriod" = proto.Field( - proto.ENUM, - number=1, - enum="PersistenceConfig.RDBConfig.SnapshotPeriod", - ) - rdb_snapshot_start_time: timestamp_pb2.Timestamp = proto.Field( + start_time: timeofday_pb2.TimeOfDay = proto.Field( proto.MESSAGE, number=2, - message=timestamp_pb2.Timestamp, + message=timeofday_pb2.TimeOfDay, ) - class AOFConfig(proto.Message): - r"""Configuration for AOF based persistence. + fixed_frequency_schedule: FixedFrequencySchedule = proto.Field( + proto.MESSAGE, + number=2, + oneof="schedule", + message=FixedFrequencySchedule, + ) + automated_backup_mode: AutomatedBackupMode = proto.Field( + proto.ENUM, + number=1, + enum=AutomatedBackupMode, + ) + retention: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) - Attributes: - append_fsync (google.cloud.memorystore_v1beta.types.PersistenceConfig.AOFConfig.AppendFsync): - Optional. The fsync mode. + +class BackupCollection(proto.Message): + r"""BackupCollection of an instance. + + Attributes: + name (str): + Identifier. Full resource path of the backup + collection. + instance_uid (str): + Output only. The instance uid of the backup + collection. + instance (str): + Output only. The full resource path of the + instance the backup collection belongs to. + Example: + + projects/{project}/locations/{location}/instances/{instance} + kms_key (str): + Output only. The KMS key used to encrypt the + backups under this backup collection. + uid (str): + Output only. System assigned unique + identifier of the backup collection. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup + collection was created. + total_backup_size_bytes (int): + Output only. Total size of all backups in the + backup collection. + total_backup_count (int): + Output only. Total number of backups in the + backup collection. + last_backup_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time a backup was + created in the backup collection. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + instance_uid: str = proto.Field( + proto.STRING, + number=3, + ) + instance: str = proto.Field( + proto.STRING, + number=4, + ) + kms_key: str = proto.Field( + proto.STRING, + number=5, + ) + uid: str = proto.Field( + proto.STRING, + number=6, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=7, + message=timestamp_pb2.Timestamp, + ) + total_backup_size_bytes: int = proto.Field( + proto.INT64, + number=8, + ) + total_backup_count: int = proto.Field( + proto.INT64, + number=10, + ) + last_backup_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=11, + message=timestamp_pb2.Timestamp, + ) + + +class Backup(proto.Message): + r"""Backup of an instance. + + Attributes: + name (str): + Identifier. Full resource path of the backup. the last part + of the name is the backup id with the following format: + [YYYYMMDDHHMMSS]\_[Shorted Instance UID] OR customer + specified while backup instance. Example: + 20240515123000_1234 + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup was + created. + instance (str): + Output only. Instance resource path of this + backup. + instance_uid (str): + Output only. Instance uid of this backup. + total_size_bytes (int): + Output only. Total size of the backup in + bytes. + expire_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup will + expire. + engine_version (str): + Output only. valkey-7.5/valkey-8.0, etc. + backup_files (MutableSequence[google.cloud.memorystore_v1beta.types.BackupFile]): + Output only. List of backup files of the + backup. + node_type (google.cloud.memorystore_v1beta.types.Instance.NodeType): + Output only. Node type of the instance. + replica_count (int): + Output only. Number of replicas for the + instance. + shard_count (int): + Output only. Number of shards for the + instance. + backup_type (google.cloud.memorystore_v1beta.types.Backup.BackupType): + Output only. Type of the backup. + state (google.cloud.memorystore_v1beta.types.Backup.State): + Output only. State of the backup. + encryption_info (google.cloud.memorystore_v1beta.types.EncryptionInfo): + Output only. Encryption information of the + backup. + uid (str): + Output only. System assigned unique + identifier of the backup. + """ + + class BackupType(proto.Enum): + r"""Type of the backup. + + Values: + BACKUP_TYPE_UNSPECIFIED (0): + The default value, not set. + ON_DEMAND (1): + On-demand backup. + AUTOMATED (2): + Automated backup. """ - class AppendFsync(proto.Enum): - r"""Possible fsync modes. + BACKUP_TYPE_UNSPECIFIED = 0 + ON_DEMAND = 1 + AUTOMATED = 2 - Values: - APPEND_FSYNC_UNSPECIFIED (0): - Not set. Default: EVERY_SEC - NEVER (1): - Never fsync. Normally Linux will flush data - every 30 seconds with this configuration, but - it's up to the kernel's exact tuning. - EVERY_SEC (2): - Fsync every second. You may lose 1 second of - data if there is a disaster. - ALWAYS (3): - Fsync every time new write commands are - appended to the AOF. The best data loss - protection at the cost of performance. - """ + class State(proto.Enum): + r"""State of the backup. - APPEND_FSYNC_UNSPECIFIED = 0 - NEVER = 1 - EVERY_SEC = 2 - ALWAYS = 3 + Values: + STATE_UNSPECIFIED (0): + The default value, not set. + CREATING (1): + The backup is being created. + ACTIVE (2): + The backup is active to be used. + DELETING (3): + The backup is being deleted. + SUSPENDED (4): + The backup is currently suspended due to + reasons like project deletion, billing account + closure, etc. + """ - append_fsync: "PersistenceConfig.AOFConfig.AppendFsync" = proto.Field( - proto.ENUM, - number=1, - enum="PersistenceConfig.AOFConfig.AppendFsync", - ) + STATE_UNSPECIFIED = 0 + CREATING = 1 + ACTIVE = 2 + DELETING = 3 + SUSPENDED = 4 - mode: PersistenceMode = proto.Field( - proto.ENUM, + name: str = proto.Field( + proto.STRING, number=1, - enum=PersistenceMode, ) - rdb_config: RDBConfig = proto.Field( + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, - message=RDBConfig, + message=timestamp_pb2.Timestamp, ) - aof_config: AOFConfig = proto.Field( + instance: str = proto.Field( + proto.STRING, + number=3, + ) + instance_uid: str = proto.Field( + proto.STRING, + number=4, + ) + total_size_bytes: int = proto.Field( + proto.INT64, + number=5, + ) + expire_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + engine_version: str = proto.Field( + proto.STRING, + number=7, + ) + backup_files: MutableSequence["BackupFile"] = proto.RepeatedField( + proto.MESSAGE, + number=8, + message="BackupFile", + ) + node_type: "Instance.NodeType" = proto.Field( + proto.ENUM, + number=9, + enum="Instance.NodeType", + ) + replica_count: int = proto.Field( + proto.INT32, + number=10, + ) + shard_count: int = proto.Field( + proto.INT32, + number=11, + ) + backup_type: BackupType = proto.Field( + proto.ENUM, + number=12, + enum=BackupType, + ) + state: State = proto.Field( + proto.ENUM, + number=13, + enum=State, + ) + encryption_info: "EncryptionInfo" = proto.Field( + proto.MESSAGE, + number=14, + message="EncryptionInfo", + ) + uid: str = proto.Field( + proto.STRING, + number=15, + ) + + +class BackupFile(proto.Message): + r"""Backup is consisted of multiple backup files. + + Attributes: + file_name (str): + Output only. e.g: .rdb + size_bytes (int): + Output only. Size of the backup file in + bytes. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the backup file + was created. + """ + + file_name: str = proto.Field( + proto.STRING, + number=1, + ) + size_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=3, - message=AOFConfig, + message=timestamp_pb2.Timestamp, ) -class NodeConfig(proto.Message): - r"""Represents configuration for nodes of the instance. +class CrossInstanceReplicationConfig(proto.Message): + r"""Cross instance replication config. Attributes: - size_gb (float): - Output only. Memory size in GB of the node. + instance_role (google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig.InstanceRole): + Required. The role of the instance in cross + instance replication. + primary_instance (google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig.RemoteInstance): + Optional. Details of the primary instance + that is used as the replication source for this + secondary instance. + + This field is only set for a secondary instance. + secondary_instances (MutableSequence[google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig.RemoteInstance]): + Optional. List of secondary instances that + are replicating from this primary instance. + + This field is only set for a primary instance. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The last time cross instance + replication config was updated. + membership (google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig.Membership): + Output only. An output only view of all the + member instances participating in the cross + instance replication. This view will be provided + by every member instance irrespective of its + instance role(primary or secondary). + + A primary instance can provide information about + all the secondary instances replicating from it. + However, a secondary instance only knows about + the primary instance from which it is + replicating. However, for scenarios, where the + primary instance is unavailable(e.g. regional + outage), a Getinstance request can be sent to + any other member instance and this field will + list all the member instances participating in + cross instance replication. + """ + + class InstanceRole(proto.Enum): + r"""The role of the instance in cross instance replication. + + Values: + INSTANCE_ROLE_UNSPECIFIED (0): + instance role is not set. + The behavior is equivalent to NONE. + NONE (1): + This instance does not participate in cross + instance replication. It is an independent + instance and does not replicate to or from any + other instances. + PRIMARY (2): + A instance that allows both reads and writes. + Any data written to this instance is also + replicated to the attached secondary instances. + SECONDARY (3): + A instance that allows only reads and + replicates data from a primary instance. + """ + + INSTANCE_ROLE_UNSPECIFIED = 0 + NONE = 1 + PRIMARY = 2 + SECONDARY = 3 + + class RemoteInstance(proto.Message): + r"""Details of the remote instance associated with this instance + in a cross instance replication setup. + + Attributes: + instance (str): + Optional. The full resource path of the + remote instance in the format: + projects//locations//instances/ + uid (str): + Output only. The unique identifier of the + remote instance. + """ + + instance: str = proto.Field( + proto.STRING, + number=1, + ) + uid: str = proto.Field( + proto.STRING, + number=2, + ) + + class Membership(proto.Message): + r"""An output only view of all the member instances participating + in the cross instance replication. + + Attributes: + primary_instance (google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig.RemoteInstance): + Output only. The primary instance that acts + as the source of replication for the secondary + instances. + secondary_instances (MutableSequence[google.cloud.memorystore_v1beta.types.CrossInstanceReplicationConfig.RemoteInstance]): + Output only. The list of secondary instances + replicating from the primary instance. + """ + + primary_instance: "CrossInstanceReplicationConfig.RemoteInstance" = proto.Field( + proto.MESSAGE, + number=1, + message="CrossInstanceReplicationConfig.RemoteInstance", + ) + secondary_instances: MutableSequence[ + "CrossInstanceReplicationConfig.RemoteInstance" + ] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="CrossInstanceReplicationConfig.RemoteInstance", + ) + + instance_role: InstanceRole = proto.Field( + proto.ENUM, + number=1, + enum=InstanceRole, + ) + primary_instance: RemoteInstance = proto.Field( + proto.MESSAGE, + number=2, + message=RemoteInstance, + ) + secondary_instances: MutableSequence[RemoteInstance] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=RemoteInstance, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + membership: Membership = proto.Field( + proto.MESSAGE, + number=5, + message=Membership, + ) + + +class TokenAuthUser(proto.Message): + r"""Token based auth user for the instance. + + Attributes: + name (str): + Identifier. Token based auth user name. + state (google.cloud.memorystore_v1beta.types.TokenAuthUser.State): + Output only. The state of the token based + auth user. + """ + + class State(proto.Enum): + r"""Represents the different states of a token based auth user. + New values may be added in the future. + + Values: + STATE_UNSPECIFIED (0): + Not set. + ACTIVE (1): + The auth user is active. + CREATING (2): + The auth user is being created. + UPDATING (3): + The auth user is being updated. + DELETING (4): + The auth user is being deleted. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + CREATING = 2 + UPDATING = 3 + DELETING = 4 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + state: State = proto.Field( + proto.ENUM, + number=2, + enum=State, + ) + + +class AuthToken(proto.Message): + r"""Auth token for the instance. + + Attributes: + name (str): + Identifier. Name of the auth token. + token (str): + Output only. The auth token. + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. Create time of the auth token. + state (google.cloud.memorystore_v1beta.types.AuthToken.State): + Output only. The state of the auth token. + """ + + class State(proto.Enum): + r"""Represents the different states of an auth token. + New values may be added in the future. + + Values: + STATE_UNSPECIFIED (0): + Not set. + ACTIVE (1): + The auth token is active. + CREATING (2): + The auth token is being created. + DELETING (3): + The auth token is being deleted. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + CREATING = 2 + DELETING = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + token: str = proto.Field( + proto.STRING, + number=2, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + + +class MaintenancePolicy(proto.Message): + r"""Maintenance policy per instance. + + Attributes: + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the policy was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time when the policy was + updated. + weekly_maintenance_window (MutableSequence[google.cloud.memorystore_v1beta.types.WeeklyMaintenanceWindow]): + Optional. Maintenance window that is applied to resources + covered by this policy. Minimum 1. For the current version, + the maximum number of weekly_window is expected to be one. + """ + + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + weekly_maintenance_window: MutableSequence["WeeklyMaintenanceWindow"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=3, + message="WeeklyMaintenanceWindow", + ) + ) + + +class WeeklyMaintenanceWindow(proto.Message): + r"""Time window specified for weekly operations. + + Attributes: + day (google.type.dayofweek_pb2.DayOfWeek): + Optional. Allows to define schedule that runs + specified day of the week. + start_time (google.type.timeofday_pb2.TimeOfDay): + Optional. Start time of the window in UTC. + """ + + day: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=1, + enum=dayofweek_pb2.DayOfWeek, + ) + start_time: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=2, + message=timeofday_pb2.TimeOfDay, + ) + + +class MaintenanceSchedule(proto.Message): + r"""Upcoming maintenance schedule. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The start time of any upcoming + scheduled maintenance for this instance. + end_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The end time of any upcoming + scheduled maintenance for this instance. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class PscAttachmentDetail(proto.Message): + r"""Configuration of a service attachment of the cluster, for + creating PSC connections. + + Attributes: + service_attachment (str): + Output only. Service attachment URI which + your self-created PscConnection should use as + target. + connection_type (google.cloud.memorystore_v1beta.types.ConnectionType): + Output only. Type of Psc endpoint. + """ + + service_attachment: str = proto.Field( + proto.STRING, + number=1, + ) + connection_type: "ConnectionType" = proto.Field( + proto.ENUM, + number=4, + enum="ConnectionType", + ) + + +class PscAutoConnection(proto.Message): + r"""Details of consumer resources in a PSC connection. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + port (int): + Optional. port will only be set for + Primary/Reader or Discovery endpoint. + + This field is a member of `oneof`_ ``ports``. + psc_connection_id (str): + Output only. The PSC connection id of the + forwarding rule connected to the service + attachment. + ip_address (str): + Output only. The IP allocated on the consumer + network for the PSC forwarding rule. + forwarding_rule (str): + Output only. The URI of the consumer side forwarding rule. + Format: + projects/{project}/regions/{region}/forwardingRules/{forwarding_rule} + project_id (str): + Required. The consumer project_id where PSC connections are + established. This should be the same project_id that the + instance is being created in. + network (str): + Required. The network where the PSC endpoints are created, + in the form of + projects/{project_id}/global/networks/{network_name}. + service_attachment (str): + Output only. The service attachment which is + the target of the PSC connection, in the form of + projects/{project-id}/regions/{region}/serviceAttachments/{service-attachment-id}. + psc_connection_status (google.cloud.memorystore_v1beta.types.PscConnectionStatus): + Output only. The status of the PSC + connection: whether a connection exists and + ACTIVE or it no longer exists. Please note that + this value is updated periodically. Please use + Private Service Connect APIs for the latest + status. + connection_type (google.cloud.memorystore_v1beta.types.ConnectionType): + Output only. Type of the PSC connection. + """ + + port: int = proto.Field( + proto.INT32, + number=9, + oneof="ports", + ) + psc_connection_id: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address: str = proto.Field( + proto.STRING, + number=2, + ) + forwarding_rule: str = proto.Field( + proto.STRING, + number=3, + ) + project_id: str = proto.Field( + proto.STRING, + number=4, + ) + network: str = proto.Field( + proto.STRING, + number=5, + ) + service_attachment: str = proto.Field( + proto.STRING, + number=6, + ) + psc_connection_status: "PscConnectionStatus" = proto.Field( + proto.ENUM, + number=7, + enum="PscConnectionStatus", + ) + connection_type: "ConnectionType" = proto.Field( + proto.ENUM, + number=8, + enum="ConnectionType", + ) + + +class PscConnection(proto.Message): + r"""User created Psc connection configuration. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + port (int): + Optional. port will only be set for + Primary/Reader or Discovery endpoint. + + This field is a member of `oneof`_ ``ports``. + psc_connection_id (str): + Required. The PSC connection id of the + forwarding rule connected to the service + attachment. + ip_address (str): + Required. The IP allocated on the consumer + network for the PSC forwarding rule. + forwarding_rule (str): + Required. The URI of the consumer side forwarding rule. + Format: + projects/{project}/regions/{region}/forwardingRules/{forwarding_rule} + project_id (str): + Output only. The consumer project_id where the forwarding + rule is created from. + network (str): + Required. The consumer network where the IP address resides, + in the form of + projects/{project_id}/global/networks/{network_name}. + service_attachment (str): + Required. The service attachment which is the + target of the PSC connection, in the form of + projects/{project-id}/regions/{region}/serviceAttachments/{service-attachment-id}. + psc_connection_status (google.cloud.memorystore_v1beta.types.PscConnectionStatus): + Output only. The status of the PSC + connection: whether a connection exists and + ACTIVE or it no longer exists. Please note that + this value is updated periodically. Please use + Private Service Connect APIs for the latest + status. + connection_type (google.cloud.memorystore_v1beta.types.ConnectionType): + Output only. Type of the PSC connection. + """ + + port: int = proto.Field( + proto.INT32, + number=9, + oneof="ports", + ) + psc_connection_id: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address: str = proto.Field( + proto.STRING, + number=2, + ) + forwarding_rule: str = proto.Field( + proto.STRING, + number=3, + ) + project_id: str = proto.Field( + proto.STRING, + number=4, + ) + network: str = proto.Field( + proto.STRING, + number=5, + ) + service_attachment: str = proto.Field( + proto.STRING, + number=6, + ) + psc_connection_status: "PscConnectionStatus" = proto.Field( + proto.ENUM, + number=7, + enum="PscConnectionStatus", + ) + connection_type: "ConnectionType" = proto.Field( + proto.ENUM, + number=8, + enum="ConnectionType", + ) + + +class DiscoveryEndpoint(proto.Message): + r"""Represents an endpoint for clients to connect to the + instance. + + Attributes: + address (str): + Output only. IP address of the exposed + endpoint clients connect to. + port (int): + Output only. The port number of the exposed + endpoint. + network (str): + Output only. The network where the IP address of the + discovery endpoint will be reserved, in the form of + projects/{network_project}/global/networks/{network_name}. + """ + + address: str = proto.Field( + proto.STRING, + number=1, + ) + port: int = proto.Field( + proto.INT32, + number=2, + ) + network: str = proto.Field( + proto.STRING, + number=4, + ) + + +class PersistenceConfig(proto.Message): + r"""Represents persistence configuration for a instance. + + Attributes: + mode (google.cloud.memorystore_v1beta.types.PersistenceConfig.PersistenceMode): + Optional. Current persistence mode. + rdb_config (google.cloud.memorystore_v1beta.types.PersistenceConfig.RDBConfig): + Optional. RDB configuration. This field will + be ignored if mode is not RDB. + aof_config (google.cloud.memorystore_v1beta.types.PersistenceConfig.AOFConfig): + Optional. AOF configuration. This field will + be ignored if mode is not AOF. + """ + + class PersistenceMode(proto.Enum): + r"""Possible persistence modes. + + Values: + PERSISTENCE_MODE_UNSPECIFIED (0): + Not set. + DISABLED (1): + Persistence is disabled, and any snapshot + data is deleted. + RDB (2): + RDB based persistence is enabled. + AOF (3): + AOF based persistence is enabled. + """ + + PERSISTENCE_MODE_UNSPECIFIED = 0 + DISABLED = 1 + RDB = 2 + AOF = 3 + + class RDBConfig(proto.Message): + r"""Configuration for RDB based persistence. + + Attributes: + rdb_snapshot_period (google.cloud.memorystore_v1beta.types.PersistenceConfig.RDBConfig.SnapshotPeriod): + Optional. Period between RDB snapshots. + rdb_snapshot_start_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Time that the first snapshot + was/will be attempted, and to which future + snapshots will be aligned. If not provided, the + current time will be used. + """ + + class SnapshotPeriod(proto.Enum): + r"""Possible snapshot periods. + + Values: + SNAPSHOT_PERIOD_UNSPECIFIED (0): + Not set. + ONE_HOUR (1): + One hour. + SIX_HOURS (2): + Six hours. + TWELVE_HOURS (3): + Twelve hours. + TWENTY_FOUR_HOURS (4): + Twenty four hours. + """ + + SNAPSHOT_PERIOD_UNSPECIFIED = 0 + ONE_HOUR = 1 + SIX_HOURS = 2 + TWELVE_HOURS = 3 + TWENTY_FOUR_HOURS = 4 + + rdb_snapshot_period: "PersistenceConfig.RDBConfig.SnapshotPeriod" = proto.Field( + proto.ENUM, + number=1, + enum="PersistenceConfig.RDBConfig.SnapshotPeriod", + ) + rdb_snapshot_start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + class AOFConfig(proto.Message): + r"""Configuration for AOF based persistence. + + Attributes: + append_fsync (google.cloud.memorystore_v1beta.types.PersistenceConfig.AOFConfig.AppendFsync): + Optional. The fsync mode. + """ + + class AppendFsync(proto.Enum): + r"""Possible fsync modes. + + Values: + APPEND_FSYNC_UNSPECIFIED (0): + Not set. Default: EVERY_SEC + NEVER (1): + Never fsync. Normally Linux will flush data + every 30 seconds with this configuration, but + it's up to the kernel's exact tuning. + EVERY_SEC (2): + Fsync every second. You may lose 1 second of + data if there is a disaster. + ALWAYS (3): + Fsync every time new write commands are + appended to the AOF. The best data loss + protection at the cost of performance. + """ + + APPEND_FSYNC_UNSPECIFIED = 0 + NEVER = 1 + EVERY_SEC = 2 + ALWAYS = 3 + + append_fsync: "PersistenceConfig.AOFConfig.AppendFsync" = proto.Field( + proto.ENUM, + number=1, + enum="PersistenceConfig.AOFConfig.AppendFsync", + ) + + mode: PersistenceMode = proto.Field( + proto.ENUM, + number=1, + enum=PersistenceMode, + ) + rdb_config: RDBConfig = proto.Field( + proto.MESSAGE, + number=2, + message=RDBConfig, + ) + aof_config: AOFConfig = proto.Field( + proto.MESSAGE, + number=3, + message=AOFConfig, + ) + + +class NodeConfig(proto.Message): + r"""Represents configuration for nodes of the instance. + + Attributes: + size_gb (float): + Output only. Memory size in GB of the node. + """ + + size_gb: float = proto.Field( + proto.DOUBLE, + number=1, + ) + + +class ZoneDistributionConfig(proto.Message): + r"""Zone distribution configuration for allocation of instance + resources. + + Attributes: + zone (str): + Optional. Defines zone where all resources will be allocated + with SINGLE_ZONE mode. Ignored for MULTI_ZONE mode. + mode (google.cloud.memorystore_v1beta.types.ZoneDistributionConfig.ZoneDistributionMode): + Optional. Current zone distribution mode. Defaults to + MULTI_ZONE. + """ + + class ZoneDistributionMode(proto.Enum): + r"""Possible zone distribution modes. + + Values: + ZONE_DISTRIBUTION_MODE_UNSPECIFIED (0): + Not Set. Default: MULTI_ZONE + MULTI_ZONE (1): + Distribute resources across 3 zones picked at + random within the region. + SINGLE_ZONE (2): + Provision resources in a single zone. Zone + field must be specified. + """ + + ZONE_DISTRIBUTION_MODE_UNSPECIFIED = 0 + MULTI_ZONE = 1 + SINGLE_ZONE = 2 + + zone: str = proto.Field( + proto.STRING, + number=2, + ) + mode: ZoneDistributionMode = proto.Field( + proto.ENUM, + number=1, + enum=ZoneDistributionMode, + ) + + +class RescheduleMaintenanceRequest(proto.Message): + r"""Request for rescheduling instance maintenance. + + Attributes: + name (str): + Required. Name of the instance to reschedule maintenance + for: + ``projects/{project}/locations/{location_id}/instances/{instance}`` + reschedule_type (google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest.RescheduleType): + Required. If reschedule type is SPECIFIC_TIME, schedule_time + must be set. + schedule_time (google.protobuf.timestamp_pb2.Timestamp): + Optional. Timestamp when the maintenance shall be + rescheduled to if reschedule_type=SPECIFIC_TIME, in RFC 3339 + format. Example: ``2012-11-15T16:19:00.094Z``. + """ + + class RescheduleType(proto.Enum): + r"""Reschedule options. + + Values: + RESCHEDULE_TYPE_UNSPECIFIED (0): + Not set. + IMMEDIATE (1): + If the user wants to schedule the maintenance + to happen now. + SPECIFIC_TIME (3): + If the user wants to reschedule the + maintenance to a specific time. + """ + + RESCHEDULE_TYPE_UNSPECIFIED = 0 + IMMEDIATE = 1 + SPECIFIC_TIME = 3 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + reschedule_type: RescheduleType = proto.Field( + proto.ENUM, + number=2, + enum=RescheduleType, + ) + schedule_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + + +class ListInstancesRequest(proto.Message): + r"""Request message for ``ListInstances``. + + Attributes: + parent (str): + Required. The parent to list instances from. + Format: projects/{project}/locations/{location} + page_size (int): + Optional. Requested page size. Server may + return fewer items than requested. If + unspecified, server will pick an appropriate + default. + page_token (str): + Optional. A token identifying a page of + results the server should return. + filter (str): + Optional. Expression for filtering results. + order_by (str): + Optional. Sort results by a defined order. Supported values: + "name", "create_time". + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListInstancesResponse(proto.Message): + r"""Response message for ``ListInstances``. + + Attributes: + instances (MutableSequence[google.cloud.memorystore_v1beta.types.Instance]): + If the {location} requested was "-" the + response contains a list of instances from all + locations. Instances in unreachable locations + will be omitted. + next_page_token (str): + A token, which can be sent as ``page_token`` to retrieve the + next page. If this field is omitted, there are no subsequent + pages. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + instances: MutableSequence["Instance"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Instance", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetInstanceRequest(proto.Message): + r"""Request message for ``GetInstance``. + + Attributes: + name (str): + Required. The name of the instance to + retrieve. Format: + projects/{project}/locations/{location}/instances/{instance} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class CreateInstanceRequest(proto.Message): + r"""Request message for [CreateInstance][]. + + Attributes: + parent (str): + Required. The parent resource where this + instance will be created. Format: + projects/{project}/locations/{location} + instance_id (str): + Required. The ID to use for the instance, which will become + the final component of the instance's resource name. + + This value is subject to the following restrictions: + + - Must be 4-63 characters in length + - Must begin with a letter or digit + - Must contain only lowercase letters, digits, and hyphens + - Must not end with a hyphen + - Must be unique within a location + instance (google.cloud.memorystore_v1beta.types.Instance): + Required. The instance to create. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + instance_id: str = proto.Field( + proto.STRING, + number=2, + ) + instance: "Instance" = proto.Field( + proto.MESSAGE, + number=3, + message="Instance", + ) + request_id: str = proto.Field( + proto.STRING, + number=4, + ) + + +class UpdateInstanceRequest(proto.Message): + r"""Request message for [UpdateInstance][]. + + Attributes: + update_mask (google.protobuf.field_mask_pb2.FieldMask): + Optional. The list of fields to be updated on + the instance. At least one field must be + specified. + instance (google.cloud.memorystore_v1beta.types.Instance): + Required. The instance to update. + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes since the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + update_mask: field_mask_pb2.FieldMask = proto.Field( + proto.MESSAGE, + number=1, + message=field_mask_pb2.FieldMask, + ) + instance: "Instance" = proto.Field( + proto.MESSAGE, + number=2, + message="Instance", + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class DeleteInstanceRequest(proto.Message): + r"""Request message for [DeleteInstance][]. + + Attributes: + name (str): + Required. The name of the instance to delete. + Format: + projects/{project}/locations/{location}/instances/{instance} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ListBackupCollectionsRequest(proto.Message): + r"""Request for ``ListBackupCollections``. + + Attributes: + parent (str): + Required. The resource name of the backupCollection location + using the form: + ``projects/{project_id}/locations/{location_id}`` where + ``location_id`` refers to a Google Cloud region. + page_size (int): + Optional. The maximum number of items to return. + + If not specified, a default value of 1000 will be used by + the service. Regardless of the page_size value, the response + may include a partial list and a caller should only rely on + response's ``next_page_token`` to determine if there are + more clusters left to be queried. + page_token (str): + Optional. The ``next_page_token`` value returned from a + previous ``ListBackupCollections`` request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBackupCollectionsResponse(proto.Message): + r"""Response for ``ListBackupCollections``. + + Attributes: + backup_collections (MutableSequence[google.cloud.memorystore_v1beta.types.BackupCollection]): + A list of backupCollections in the project. + + If the ``location_id`` in the parent field of the request is + "-", all regions available to the project are queried, and + the results aggregated. If in such an aggregated query a + location is unavailable, a placeholder backupCollection + entry is included in the response with the ``name`` field + set to a value of the form + ``projects/{project_id}/locations/{location_id}/backupCollections/``- + and the ``status`` field set to ERROR and ``status_message`` + field set to "location not available for + ListBackupCollections". + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + backup_collections: MutableSequence["BackupCollection"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="BackupCollection", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupCollectionRequest(proto.Message): + r"""Request for ``GetBackupCollection``. + + Attributes: + name (str): + Required. Instance backupCollection resource name using the + form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}`` + where ``location_id`` refers to a Google Cloud region. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListBackupsRequest(proto.Message): + r"""Request for ``ListBackups``. + + Attributes: + parent (str): + Required. The resource name of the backupCollection using + the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}`` + page_size (int): + Optional. The maximum number of items to return. + + If not specified, a default value of 1000 will be used by + the service. Regardless of the page_size value, the response + may include a partial list and a caller should only rely on + response's ``next_page_token`` to determine if there are + more clusters left to be queried. + page_token (str): + Optional. The ``next_page_token`` value returned from a + previous ``ListBackupCollections`` request, if any. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + + +class ListBackupsResponse(proto.Message): + r"""Response for ``ListBackups``. + + Attributes: + backups (MutableSequence[google.cloud.memorystore_v1beta.types.Backup]): + A list of backups in the project. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Backups that could not be reached. + """ + + @property + def raw_page(self): + return self + + backups: MutableSequence["Backup"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Backup", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetBackupRequest(proto.Message): + r"""Request for ``GetBackup``. + + Attributes: + name (str): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class DeleteBackupRequest(proto.Message): + r"""Request for ``DeleteBackup``. + + Attributes: + name (str): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + request_id (str): + Optional. Idempotent request UUID. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + +class ExportBackupRequest(proto.Message): + r"""Request for ``ExportBackup``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + gcs_bucket (str): + Google Cloud Storage bucket, like + "my-bucket". + + This field is a member of `oneof`_ ``destination``. + name (str): + Required. Instance backup resource name using the form: + ``projects/{project_id}/locations/{location_id}/backupCollections/{backup_collection_id}/backups/{backup_id}`` + """ + + gcs_bucket: str = proto.Field( + proto.STRING, + number=2, + oneof="destination", + ) + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class BackupInstanceRequest(proto.Message): + r"""Request for ``BackupInstance``. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + name (str): + Required. Instance resource name using the form: + ``projects/{project_id}/locations/{location_id}/instances/{instance_id}`` + where ``location_id`` refers to a Google Cloud region. + ttl (google.protobuf.duration_pb2.Duration): + Optional. TTL for the backup to expire. Value + range is 1 day to 100 years. If not specified, + the default value is 100 years. + backup_id (str): + Optional. The id of the backup to be created. If not + specified, the default value ([YYYYMMDDHHMMSS]\_[Shortened + Instance UID] is used. + + This field is a member of `oneof`_ ``_backup_id``. """ - size_gb: float = proto.Field( - proto.DOUBLE, + name: str = proto.Field( + proto.STRING, number=1, ) + ttl: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=2, + message=duration_pb2.Duration, + ) + backup_id: str = proto.Field( + proto.STRING, + number=3, + optional=True, + ) -class ZoneDistributionConfig(proto.Message): - r"""Zone distribution configuration for allocation of instance - resources. +class GetCertificateAuthorityRequest(proto.Message): + r"""Request message for ``GetCertificateAuthority``. Attributes: - zone (str): - Optional. Defines zone where all resources will be allocated - with SINGLE_ZONE mode. Ignored for MULTI_ZONE mode. - mode (google.cloud.memorystore_v1beta.types.ZoneDistributionConfig.ZoneDistributionMode): - Optional. Current zone distribution mode. Defaults to - MULTI_ZONE. - """ - - class ZoneDistributionMode(proto.Enum): - r"""Possible zone distribution modes. - - Values: - ZONE_DISTRIBUTION_MODE_UNSPECIFIED (0): - Not Set. Default: MULTI_ZONE - MULTI_ZONE (1): - Distribute resources across 3 zones picked at - random within the region. - SINGLE_ZONE (2): - Provision resources in a single zone. Zone - field must be specified. - """ + name (str): + Required. The name of the certificate + authority. Format: - ZONE_DISTRIBUTION_MODE_UNSPECIFIED = 0 - MULTI_ZONE = 1 - SINGLE_ZONE = 2 + projects/{project}/locations/{location}/instances/{instance}/certificateAuthority + """ - zone: str = proto.Field( + name: str = proto.Field( proto.STRING, - number=2, - ) - mode: ZoneDistributionMode = proto.Field( - proto.ENUM, number=1, - enum=ZoneDistributionMode, ) -class ListInstancesRequest(proto.Message): - r"""Request message for [ListInstances][]. +class ListTokenAuthUsersRequest(proto.Message): + r"""Request message for ``ListTokenAuthUsers``. Attributes: parent (str): - Required. The parent to list instances from. - Format: projects/{project}/locations/{location} + Required. The parent to list token auth users + from. Format: + projects/{project}/locations/{location}/instances/{instance} page_size (int): - Optional. Requested page size. Server may - return fewer items than requested. If - unspecified, server will pick an appropriate - default. + Optional. The maximum number of items to return. The maximum + value is 1000; values above 1000 will be coerced to 1000. If + not specified, a default value of 1000 will be used by the + service. Regardless of the page_size value, the response may + include a partial list and a caller should only rely on + response's ``next_page_token`` to determine if there are + more token auth users left to be queried. page_token (str): - Optional. A token identifying a page of - results the server should return. + Optional. The ``next_page_token`` value returned from a + previous ``ListTokenAuthUsers`` request, if any. filter (str): Optional. Expression for filtering results. order_by (str): - Optional. Sort results by a defined order. Supported values: - "name", "create_time". + Optional. Sort results by a defined order. """ parent: str = proto.Field( @@ -984,31 +2740,29 @@ class ListInstancesRequest(proto.Message): ) -class ListInstancesResponse(proto.Message): - r"""Response message for [ListInstances][]. +class ListTokenAuthUsersResponse(proto.Message): + r"""Response message for ``ListTokenAuthUsers``. Attributes: - instances (MutableSequence[google.cloud.memorystore_v1beta.types.Instance]): - If the {location} requested was "-" the - response contains a list of instances from all - locations. Instances in unreachable locations - will be omitted. + token_auth_users (MutableSequence[google.cloud.memorystore_v1beta.types.TokenAuthUser]): + A list of token auth users in the project. next_page_token (str): - A token, which can be sent as ``page_token`` to retrieve the - next page. If this field is omitted, there are no subsequent - pages. + Token to retrieve the next page of results, + or empty if there are no more results in the + list. unreachable (MutableSequence[str]): - Locations that could not be reached. + Unordered list. Token auth users that could + not be reached. """ @property def raw_page(self): return self - instances: MutableSequence["Instance"] = proto.RepeatedField( + token_auth_users: MutableSequence["TokenAuthUser"] = proto.RepeatedField( proto.MESSAGE, number=1, - message="Instance", + message="TokenAuthUser", ) next_page_token: str = proto.Field( proto.STRING, @@ -1020,14 +2774,14 @@ def raw_page(self): ) -class GetInstanceRequest(proto.Message): - r"""Request message for [GetInstance][]. +class GetTokenAuthUserRequest(proto.Message): + r"""Request message for ``GetTokenAuthUser``. Attributes: name (str): - Required. The name of the instance to - retrieve. Format: - projects/{project}/locations/{location}/instances/{instance} + Required. The name of token auth user for a basic auth + enabled instance. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} """ name: str = proto.Field( @@ -1036,124 +2790,133 @@ class GetInstanceRequest(proto.Message): ) -class CreateInstanceRequest(proto.Message): - r"""Request message for [CreateInstance][]. +class ListAuthTokensRequest(proto.Message): + r"""Request message for ``ListAuthTokens``. Attributes: parent (str): - Required. The parent resource where this - instance will be created. Format: - projects/{project}/locations/{location} - instance_id (str): - Required. The ID to use for the instance, which will become - the final component of the instance's resource name. - - This value is subject to the following restrictions: - - - Must be 4-63 characters in length - - Must begin with a letter or digit - - Must contain only lowercase letters, digits, and hyphens - - Must not end with a hyphen - - Must be unique within a location - instance (google.cloud.memorystore_v1beta.types.Instance): - Required. The instance to create. - request_id (str): - Optional. An optional request ID to identify - requests. Specify a unique request ID so that if - you must retry your request, the server will - know to ignore the request if it has already - been completed. The server will guarantee that - for at least 60 minutes since the first request. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be a valid UUID with the - exception that zero UUID is not supported - (00000000-0000-0000-0000-000000000000). + Required. The parent to list auth tokens from. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} + page_size (int): + Optional. The maximum number of items to return. The maximum + value is 1000; values above 1000 will be coerced to 1000. + + If not specified, a default value of 1000 will be used by + the service. Regardless of the page_size value, the response + may include a partial list and a caller should only rely on + response's ``next_page_token`` to determine if there are + more auth tokens left to be queried. + page_token (str): + Optional. The ``next_page_token`` value returned from a + previous ``ListAuthTokens`` request, if any. + filter (str): + Optional. Expression for filtering results. + order_by (str): + Optional. Sort results by a defined order. """ parent: str = proto.Field( proto.STRING, number=1, ) - instance_id: str = proto.Field( - proto.STRING, + page_size: int = proto.Field( + proto.INT32, number=2, ) - instance: "Instance" = proto.Field( - proto.MESSAGE, + page_token: str = proto.Field( + proto.STRING, number=3, - message="Instance", ) - request_id: str = proto.Field( + filter: str = proto.Field( proto.STRING, number=4, ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) -class UpdateInstanceRequest(proto.Message): - r"""Request message for [UpdateInstance][]. +class ListAuthTokensResponse(proto.Message): + r"""Response message for ``ListAuthTokens``. Attributes: - update_mask (google.protobuf.field_mask_pb2.FieldMask): - Optional. The list of fields to be updated on - the instance. At least one field must be - specified. - instance (google.cloud.memorystore_v1beta.types.Instance): - Required. The instance to update. - request_id (str): - Optional. An optional request ID to identify - requests. Specify a unique request ID so that if - you must retry your request, the server will - know to ignore the request if it has already - been completed. The server will guarantee that - for at least 60 minutes since the first request. - - For example, consider a situation where you make - an initial request and the request times out. If - you make the request again with the same request - ID, the server can check if original operation - with the same request ID was received, and if - so, will ignore the second request. This - prevents clients from accidentally creating - duplicate commitments. - - The request ID must be a valid UUID with the - exception that zero UUID is not supported - (00000000-0000-0000-0000-000000000000). + auth_tokens (MutableSequence[google.cloud.memorystore_v1beta.types.AuthToken]): + A list of auth tokens in the project. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + unreachable (MutableSequence[str]): + Unordered list. Auth tokens that could not be + reached. """ - update_mask: field_mask_pb2.FieldMask = proto.Field( + @property + def raw_page(self): + return self + + auth_tokens: MutableSequence["AuthToken"] = proto.RepeatedField( proto.MESSAGE, number=1, - message=field_mask_pb2.FieldMask, + message="AuthToken", ) - instance: "Instance" = proto.Field( - proto.MESSAGE, + next_page_token: str = proto.Field( + proto.STRING, number=2, - message="Instance", ) - request_id: str = proto.Field( + unreachable: MutableSequence[str] = proto.RepeatedField( proto.STRING, number=3, ) -class DeleteInstanceRequest(proto.Message): - r"""Request message for [DeleteInstance][]. +class GetAuthTokenRequest(proto.Message): + r"""Request message for ``GetAuthToken``. Attributes: name (str): - Required. The name of the instance to delete. - Format: + Required. The name of token auth user for a token auth + enabled instance. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{auth_token} + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class AddTokenAuthUserRequest(proto.Message): + r"""Request message for ``AddTokenAuthUser``. + + Attributes: + instance (str): + Required. The instance resource that this + token auth user will be added for. Format: projects/{project}/locations/{location}/instances/{instance} + token_auth_user (str): + Required. The name of the token auth user to + add. + """ + + instance: str = proto.Field( + proto.STRING, + number=1, + ) + token_auth_user: str = proto.Field( + proto.STRING, + number=2, + ) + + +class DeleteTokenAuthUserRequest(proto.Message): + r"""Request message for ``DeleteTokenAuthUser``. + + Attributes: + name (str): + Required. The name of the token auth user to delete. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user} request_id (str): Optional. An optional request ID to identify requests. Specify a unique request ID so that if @@ -1174,6 +2937,11 @@ class DeleteInstanceRequest(proto.Message): The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). + force (bool): + Optional. If set to true, any auth tokens + from this user will also be deleted. Otherwise, + the request will only work if the user has no + auth tokens. """ name: str = proto.Field( @@ -1184,17 +2952,42 @@ class DeleteInstanceRequest(proto.Message): proto.STRING, number=2, ) + force: bool = proto.Field( + proto.BOOL, + number=3, + ) -class GetCertificateAuthorityRequest(proto.Message): - r"""Request message for [GetCertificateAuthority][]. +class AddAuthTokenRequest(proto.Message): + r"""Request message for ``AddAuthToken``. Attributes: - name (str): - Required. The name of the certificate - authority. Format: + token_auth_user (str): + Required. The name of the token auth user + resource that this token will be added for. + auth_token (google.cloud.memorystore_v1beta.types.AuthToken): + Required. The auth token to add. + """ - projects/{project}/locations/{location}/instances/{instance}/certificateAuthority + token_auth_user: str = proto.Field( + proto.STRING, + number=1, + ) + auth_token: "AuthToken" = proto.Field( + proto.MESSAGE, + number=2, + message="AuthToken", + ) + + +class DeleteAuthTokenRequest(proto.Message): + r"""Request message for ``DeleteAuthToken``. + + Attributes: + name (str): + Required. The name of the token auth user resource that this + token will be deleted from. Format: + projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{name} """ name: str = proto.Field( @@ -1326,8 +3119,7 @@ class RegionalCertChain(proto.Message): class GetSharedRegionalCertificateAuthorityRequest(proto.Message): - r"""Request for - [GetSharedRegionalCertificateAuthority][google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority]. + r"""Request for ``GetSharedRegionalCertificateAuthority``. Attributes: name (str): @@ -1405,4 +3197,101 @@ class OperationMetadata(proto.Message): ) +class EncryptionInfo(proto.Message): + r"""EncryptionInfo describes the encryption information of a + cluster. + + Attributes: + encryption_type (google.cloud.memorystore_v1beta.types.EncryptionInfo.Type): + Output only. Type of encryption. + kms_key_versions (MutableSequence[str]): + Output only. KMS key versions that are being + used to protect the data at-rest. + kms_key_primary_state (google.cloud.memorystore_v1beta.types.EncryptionInfo.KmsKeyState): + Output only. The state of the primary version + of the KMS key perceived by the system. This + field is not populated in backups. + last_update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The most recent time when the + encryption info was updated. + """ + + class Type(proto.Enum): + r"""Possible encryption types. + + Values: + TYPE_UNSPECIFIED (0): + Encryption type not specified. Defaults to + GOOGLE_DEFAULT_ENCRYPTION. + GOOGLE_DEFAULT_ENCRYPTION (1): + The data is encrypted at rest with a key that + is fully managed by Google. No key version will + be populated. This is the default state. + CUSTOMER_MANAGED_ENCRYPTION (2): + The data is encrypted at rest with a key that + is managed by the customer. KMS key versions + will be populated. + """ + + TYPE_UNSPECIFIED = 0 + GOOGLE_DEFAULT_ENCRYPTION = 1 + CUSTOMER_MANAGED_ENCRYPTION = 2 + + class KmsKeyState(proto.Enum): + r"""The state of the KMS key perceived by the system. Refer to + the public documentation for the impact of each state. + + Values: + KMS_KEY_STATE_UNSPECIFIED (0): + The default value. This value is unused. + ENABLED (1): + The KMS key is enabled and correctly + configured. + PERMISSION_DENIED (2): + Permission denied on the KMS key. + DISABLED (3): + The KMS key is disabled. + DESTROYED (4): + The KMS key is destroyed. + DESTROY_SCHEDULED (5): + The KMS key is scheduled to be destroyed. + EKM_KEY_UNREACHABLE_DETECTED (6): + The EKM key is unreachable. + BILLING_DISABLED (7): + Billing is disabled for the project. + UNKNOWN_FAILURE (8): + All other unknown failures. + """ + + KMS_KEY_STATE_UNSPECIFIED = 0 + ENABLED = 1 + PERMISSION_DENIED = 2 + DISABLED = 3 + DESTROYED = 4 + DESTROY_SCHEDULED = 5 + EKM_KEY_UNREACHABLE_DETECTED = 6 + BILLING_DISABLED = 7 + UNKNOWN_FAILURE = 8 + + encryption_type: Type = proto.Field( + proto.ENUM, + number=1, + enum=Type, + ) + kms_key_versions: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + kms_key_primary_state: KmsKeyState = proto.Field( + proto.ENUM, + number=3, + enum=KmsKeyState, + ) + last_update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_auth_token_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_auth_token_async.py new file mode 100644 index 000000000000..53487e1f9fcf --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_auth_token_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 AddAuthToken +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_AddAuthToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_add_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddAuthTokenRequest( + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = await client.add_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_AddAuthToken_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_auth_token_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_auth_token_sync.py new file mode 100644 index 000000000000..05758ca4d187 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_auth_token_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 AddAuthToken +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_AddAuthToken_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 memorystore_v1beta + + +def sample_add_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddAuthTokenRequest( + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = client.add_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_AddAuthToken_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_token_auth_user_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_token_auth_user_async.py new file mode 100644 index 000000000000..0a37bcfa1f7f --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_token_auth_user_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 AddTokenAuthUser +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_AddTokenAuthUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_add_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddTokenAuthUserRequest( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = await client.add_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_AddTokenAuthUser_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_token_auth_user_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_token_auth_user_sync.py new file mode 100644 index 000000000000..377b8a02ab1d --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_add_token_auth_user_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 AddTokenAuthUser +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_AddTokenAuthUser_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 memorystore_v1beta + + +def sample_add_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.AddTokenAuthUserRequest( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Make the request + operation = client.add_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_AddTokenAuthUser_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_backup_instance_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_backup_instance_async.py new file mode 100644 index 000000000000..5446a679e567 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_backup_instance_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 BackupInstance +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_BackupInstance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_backup_instance(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.BackupInstanceRequest( + name="name_value", + ) + + # Make the request + operation = await client.backup_instance(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_BackupInstance_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_backup_instance_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_backup_instance_sync.py new file mode 100644 index 000000000000..93b454d92744 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_backup_instance_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 BackupInstance +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_BackupInstance_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 memorystore_v1beta + + +def sample_backup_instance(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.BackupInstanceRequest( + name="name_value", + ) + + # Make the request + operation = client.backup_instance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_BackupInstance_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_async.py index b8cc8389bbb3..556315cd30b8 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_async.py +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_async.py @@ -39,15 +39,9 @@ async def sample_create_instance(): client = memorystore_v1beta.MemorystoreAsyncClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - request = memorystore_v1beta.CreateInstanceRequest( parent="parent_value", instance_id="instance_id_value", - instance=instance, ) # Make the request diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_sync.py index 831b5f6f4913..6263868375f8 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_sync.py +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_create_instance_sync.py @@ -39,15 +39,9 @@ def sample_create_instance(): client = memorystore_v1beta.MemorystoreClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - request = memorystore_v1beta.CreateInstanceRequest( parent="parent_value", instance_id="instance_id_value", - instance=instance, ) # Make the request diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_auth_token_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_auth_token_async.py new file mode 100644 index 000000000000..2fb03c2af4d0 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_auth_token_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteAuthToken +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_DeleteAuthToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_delete_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteAuthTokenRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_DeleteAuthToken_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_auth_token_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_auth_token_sync.py new file mode 100644 index 000000000000..4abedc318931 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_auth_token_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteAuthToken +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_DeleteAuthToken_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 memorystore_v1beta + + +def sample_delete_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteAuthTokenRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_auth_token(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_DeleteAuthToken_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_backup_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_backup_async.py new file mode 100644 index 000000000000..a7a66cff42ee --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_backup_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteBackup +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_DeleteBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_delete_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_DeleteBackup_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_backup_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_backup_sync.py new file mode 100644 index 000000000000..39087df08111 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_backup_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteBackup +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_DeleteBackup_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 memorystore_v1beta + + +def sample_delete_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteBackupRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_DeleteBackup_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_token_auth_user_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_token_auth_user_async.py new file mode 100644 index 000000000000..5a1ce9b59d60 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_token_auth_user_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteTokenAuthUser +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_DeleteTokenAuthUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_delete_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + operation = await client.delete_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_DeleteTokenAuthUser_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_token_auth_user_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_token_auth_user_sync.py new file mode 100644 index 000000000000..d1068ded2472 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_delete_token_auth_user_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 DeleteTokenAuthUser +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_DeleteTokenAuthUser_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 memorystore_v1beta + + +def sample_delete_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.DeleteTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_token_auth_user(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_DeleteTokenAuthUser_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_export_backup_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_export_backup_async.py new file mode 100644 index 000000000000..ef54e978e889 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_export_backup_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ExportBackup +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ExportBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_export_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ExportBackupRequest( + gcs_bucket="gcs_bucket_value", + name="name_value", + ) + + # Make the request + operation = await client.export_backup(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ExportBackup_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_export_backup_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_export_backup_sync.py new file mode 100644 index 000000000000..cd4f28fc2e37 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_export_backup_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ExportBackup +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ExportBackup_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 memorystore_v1beta + + +def sample_export_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ExportBackupRequest( + gcs_bucket="gcs_bucket_value", + name="name_value", + ) + + # Make the request + operation = client.export_backup(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ExportBackup_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_finish_migration_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_finish_migration_async.py new file mode 100644 index 000000000000..1456f338821d --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_finish_migration_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 FinishMigration +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_FinishMigration_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_finish_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = await client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_FinishMigration_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_finish_migration_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_finish_migration_sync.py new file mode 100644 index 000000000000..20e1a96f4dc1 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_finish_migration_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 FinishMigration +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_FinishMigration_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 memorystore_v1beta + + +def sample_finish_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.FinishMigrationRequest( + name="name_value", + ) + + # Make the request + operation = client.finish_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_FinishMigration_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_auth_token_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_auth_token_async.py new file mode 100644 index 000000000000..c04bc53cc32d --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_auth_token_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetAuthToken +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetAuthToken_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_get_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetAuthTokenRequest( + name="name_value", + ) + + # Make the request + response = await client.get_auth_token(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetAuthToken_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_auth_token_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_auth_token_sync.py new file mode 100644 index 000000000000..2e9d802ad801 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_auth_token_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetAuthToken +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetAuthToken_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 memorystore_v1beta + + +def sample_get_auth_token(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetAuthTokenRequest( + name="name_value", + ) + + # Make the request + response = client.get_auth_token(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetAuthToken_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_async.py new file mode 100644 index 000000000000..5f2edbd3ca0b --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetBackup +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetBackup_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_get_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetBackup_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_collection_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_collection_async.py new file mode 100644 index 000000000000..d262985b0ca5 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_collection_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetBackupCollection +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetBackupCollection_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_get_backup_collection(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupCollectionRequest( + name="name_value", + ) + + # Make the request + response = await client.get_backup_collection(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetBackupCollection_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_collection_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_collection_sync.py new file mode 100644 index 000000000000..8c75b3731552 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_collection_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetBackupCollection +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetBackupCollection_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 memorystore_v1beta + + +def sample_get_backup_collection(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupCollectionRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup_collection(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetBackupCollection_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_sync.py new file mode 100644 index 000000000000..ed920ec674ac --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_backup_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetBackup +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetBackup_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 memorystore_v1beta + + +def sample_get_backup(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetBackupRequest( + name="name_value", + ) + + # Make the request + response = client.get_backup(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetBackup_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_token_auth_user_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_token_auth_user_async.py new file mode 100644 index 000000000000..258db7155366 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_token_auth_user_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetTokenAuthUser +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetTokenAuthUser_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_get_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + response = await client.get_token_auth_user(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetTokenAuthUser_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_token_auth_user_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_token_auth_user_sync.py new file mode 100644 index 000000000000..5b5c4837880d --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_get_token_auth_user_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 GetTokenAuthUser +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_GetTokenAuthUser_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 memorystore_v1beta + + +def sample_get_token_auth_user(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.GetTokenAuthUserRequest( + name="name_value", + ) + + # Make the request + response = client.get_token_auth_user(request=request) + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_GetTokenAuthUser_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_auth_tokens_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_auth_tokens_async.py new file mode 100644 index 000000000000..b90835d93d91 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_auth_tokens_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListAuthTokens +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListAuthTokens_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_list_auth_tokens(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListAuthTokensRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auth_tokens(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListAuthTokens_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_auth_tokens_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_auth_tokens_sync.py new file mode 100644 index 000000000000..9227c4eeb79d --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_auth_tokens_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListAuthTokens +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListAuthTokens_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 memorystore_v1beta + + +def sample_list_auth_tokens(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListAuthTokensRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_auth_tokens(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListAuthTokens_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backup_collections_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backup_collections_async.py new file mode 100644 index 000000000000..d8df7b0723ba --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backup_collections_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListBackupCollections +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListBackupCollections_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_list_backup_collections(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_collections(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListBackupCollections_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backup_collections_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backup_collections_sync.py new file mode 100644 index 000000000000..0e3d22d8d60e --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backup_collections_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListBackupCollections +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListBackupCollections_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 memorystore_v1beta + + +def sample_list_backup_collections(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupCollectionsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backup_collections(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListBackupCollections_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backups_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backups_async.py new file mode 100644 index 000000000000..65215cd0aee5 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backups_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListBackups +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListBackups_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_list_backups(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListBackups_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backups_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backups_sync.py new file mode 100644 index 000000000000..8f416025ab93 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_backups_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListBackups +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListBackups_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 memorystore_v1beta + + +def sample_list_backups(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListBackupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_backups(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListBackups_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_token_auth_users_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_token_auth_users_async.py new file mode 100644 index 000000000000..1f3768476f58 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_token_auth_users_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListTokenAuthUsers +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListTokenAuthUsers_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_list_token_auth_users(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListTokenAuthUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_token_auth_users(request=request) + + # Handle the response + async for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListTokenAuthUsers_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_token_auth_users_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_token_auth_users_sync.py new file mode 100644 index 000000000000..470c1c55070c --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_list_token_auth_users_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 ListTokenAuthUsers +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_ListTokenAuthUsers_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 memorystore_v1beta + + +def sample_list_token_auth_users(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.ListTokenAuthUsersRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_token_auth_users(request=request) + + # Handle the response + for response in page_result: + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_ListTokenAuthUsers_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_reschedule_maintenance_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_reschedule_maintenance_async.py new file mode 100644 index 000000000000..c536cc83bc0a --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_reschedule_maintenance_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 RescheduleMaintenance +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_RescheduleMaintenance_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_reschedule_maintenance(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + request = memorystore_v1beta.RescheduleMaintenanceRequest( + name="name_value", + reschedule_type="SPECIFIC_TIME", + ) + + # Make the request + operation = await client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_RescheduleMaintenance_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_reschedule_maintenance_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_reschedule_maintenance_sync.py new file mode 100644 index 000000000000..b54f53900560 --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_reschedule_maintenance_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 RescheduleMaintenance +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_RescheduleMaintenance_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 memorystore_v1beta + + +def sample_reschedule_maintenance(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + request = memorystore_v1beta.RescheduleMaintenanceRequest( + name="name_value", + reschedule_type="SPECIFIC_TIME", + ) + + # Make the request + operation = client.reschedule_maintenance(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_RescheduleMaintenance_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_start_migration_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_start_migration_async.py new file mode 100644 index 000000000000..3f2453d4314a --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_start_migration_async.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 StartMigration +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_StartMigration_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import memorystore_v1beta + + +async def sample_start_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreAsyncClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1beta.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1beta.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = await client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = await operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_StartMigration_async] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_start_migration_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_start_migration_sync.py new file mode 100644 index 000000000000..b0c2a25b4c1c --- /dev/null +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_start_migration_sync.py @@ -0,0 +1,63 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 StartMigration +# 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-memorystore + + +# [START memorystore_v1beta_generated_Memorystore_StartMigration_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 memorystore_v1beta + + +def sample_start_migration(): + # Create a client + client = memorystore_v1beta.MemorystoreClient() + + # Initialize request argument(s) + self_managed_source = memorystore_v1beta.SelfManagedSource() + self_managed_source.ip_address = "ip_address_value" + self_managed_source.port = 453 + self_managed_source.network_attachment = "network_attachment_value" + + request = memorystore_v1beta.StartMigrationRequest( + self_managed_source=self_managed_source, + name="name_value", + ) + + # Make the request + operation = client.start_migration(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + +# [END memorystore_v1beta_generated_Memorystore_StartMigration_sync] diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_async.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_async.py index 96c1ef2e1601..876929486ee8 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_async.py +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_async.py @@ -39,14 +39,7 @@ async def sample_update_instance(): client = memorystore_v1beta.MemorystoreAsyncClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - - request = memorystore_v1beta.UpdateInstanceRequest( - instance=instance, - ) + request = memorystore_v1beta.UpdateInstanceRequest() # Make the request operation = await client.update_instance(request=request) diff --git a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_sync.py b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_sync.py index 570bc3f5c3ad..58c73131d1c9 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_sync.py +++ b/packages/google-cloud-memorystore/samples/generated_samples/memorystore_v1beta_generated_memorystore_update_instance_sync.py @@ -39,14 +39,7 @@ def sample_update_instance(): client = memorystore_v1beta.MemorystoreClient() # Initialize request argument(s) - instance = memorystore_v1beta.Instance() - instance.psc_auto_connections.port = 453 - instance.psc_auto_connections.project_id = "project_id_value" - instance.psc_auto_connections.network = "network_value" - - request = memorystore_v1beta.UpdateInstanceRequest( - instance=instance, - ) + request = memorystore_v1beta.UpdateInstanceRequest() # Make the request operation = client.update_instance(request=request) diff --git a/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json b/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json index 2df43e2e7977..13772452ca97 100644 --- a/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json +++ b/packages/google-cloud-memorystore/samples/generated_samples/snippet_metadata_google.cloud.memorystore.v1beta.json @@ -19,30 +19,195 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", "shortName": "MemorystoreAsyncClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.create_instance", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.add_auth_token", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.CreateInstance", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.AddAuthToken", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "CreateInstance" + "shortName": "AddAuthToken" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.CreateInstanceRequest" + "type": "google.cloud.memorystore_v1beta.types.AddAuthTokenRequest" }, { - "name": "parent", + "name": "token_auth_user", + "type": "str" + }, + { + "name": "auth_token", + "type": "google.cloud.memorystore_v1beta.types.AuthToken" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "add_auth_token" + }, + "description": "Sample for AddAuthToken", + "file": "memorystore_v1beta_generated_memorystore_add_auth_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_AddAuthToken_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_add_auth_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.add_auth_token", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.AddAuthToken", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "AddAuthToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.AddAuthTokenRequest" + }, + { + "name": "token_auth_user", "type": "str" }, + { + "name": "auth_token", + "type": "google.cloud.memorystore_v1beta.types.AuthToken" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_auth_token" + }, + "description": "Sample for AddAuthToken", + "file": "memorystore_v1beta_generated_memorystore_add_auth_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_AddAuthToken_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_add_auth_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.add_token_auth_user", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.AddTokenAuthUser", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "AddTokenAuthUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.AddTokenAuthUserRequest" + }, { "name": "instance", - "type": "google.cloud.memorystore_v1beta.types.Instance" + "type": "str" }, { - "name": "instance_id", + "name": "token_auth_user", "type": "str" }, { @@ -59,21 +224,21 @@ } ], "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "create_instance" + "shortName": "add_token_auth_user" }, - "description": "Sample for CreateInstance", - "file": "memorystore_v1beta_generated_memorystore_create_instance_async.py", + "description": "Sample for AddTokenAuthUser", + "file": "memorystore_v1beta_generated_memorystore_add_token_auth_user_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_CreateInstance_async", + "regionTag": "memorystore_v1beta_generated_Memorystore_AddTokenAuthUser_async", "segments": [ { - "end": 62, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 56, "start": 27, "type": "SHORT" }, @@ -83,22 +248,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_create_instance_async.py" + "title": "memorystore_v1beta_generated_memorystore_add_token_auth_user_async.py" }, { "canonical": true, @@ -107,30 +272,107 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", "shortName": "MemorystoreClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.create_instance", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.add_token_auth_user", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.CreateInstance", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.AddTokenAuthUser", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "CreateInstance" + "shortName": "AddTokenAuthUser" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.CreateInstanceRequest" + "type": "google.cloud.memorystore_v1beta.types.AddTokenAuthUserRequest" }, { - "name": "parent", + "name": "instance", "type": "str" }, { - "name": "instance", - "type": "google.cloud.memorystore_v1beta.types.Instance" + "name": "token_auth_user", + "type": "str" }, { - "name": "instance_id", + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "add_token_auth_user" + }, + "description": "Sample for AddTokenAuthUser", + "file": "memorystore_v1beta_generated_memorystore_add_token_auth_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_AddTokenAuthUser_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_add_token_auth_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.backup_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.BackupInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "BackupInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.BackupInstanceRequest" + }, + { + "name": "name", "type": "str" }, { @@ -146,22 +388,2694 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "create_instance" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "backup_instance" }, - "description": "Sample for CreateInstance", - "file": "memorystore_v1beta_generated_memorystore_create_instance_sync.py", + "description": "Sample for BackupInstance", + "file": "memorystore_v1beta_generated_memorystore_backup_instance_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_CreateInstance_sync", + "regionTag": "memorystore_v1beta_generated_Memorystore_BackupInstance_async", "segments": [ { - "end": 62, + "end": 55, "start": 27, "type": "FULL" }, { - "end": 62, + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_backup_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.backup_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.BackupInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "BackupInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.BackupInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "backup_instance" + }, + "description": "Sample for BackupInstance", + "file": "memorystore_v1beta_generated_memorystore_backup_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_BackupInstance_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_backup_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.create_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.CreateInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.memorystore_v1beta.types.Instance" + }, + { + "name": "instance_id", + "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.api_core.operation_async.AsyncOperation", + "shortName": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "memorystore_v1beta_generated_memorystore_create_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_CreateInstance_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_create_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.create_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.CreateInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "CreateInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.CreateInstanceRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "instance", + "type": "google.cloud.memorystore_v1beta.types.Instance" + }, + { + "name": "instance_id", + "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.api_core.operation.Operation", + "shortName": "create_instance" + }, + "description": "Sample for CreateInstance", + "file": "memorystore_v1beta_generated_memorystore_create_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_CreateInstance_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_create_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.delete_auth_token", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteAuthToken", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteAuthToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteAuthTokenRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_auth_token" + }, + "description": "Sample for DeleteAuthToken", + "file": "memorystore_v1beta_generated_memorystore_delete_auth_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteAuthToken_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_auth_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.delete_auth_token", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteAuthToken", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteAuthToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteAuthTokenRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_auth_token" + }, + "description": "Sample for DeleteAuthToken", + "file": "memorystore_v1beta_generated_memorystore_delete_auth_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteAuthToken_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_auth_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.delete_backup", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteBackup", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "memorystore_v1beta_generated_memorystore_delete_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteBackup_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.delete_backup", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteBackup", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_backup" + }, + "description": "Sample for DeleteBackup", + "file": "memorystore_v1beta_generated_memorystore_delete_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteBackup_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.delete_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "memorystore_v1beta_generated_memorystore_delete_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteInstance_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.delete_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_instance" + }, + "description": "Sample for DeleteInstance", + "file": "memorystore_v1beta_generated_memorystore_delete_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteInstance_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.delete_token_auth_user", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteTokenAuthUser", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteTokenAuthUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteTokenAuthUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "delete_token_auth_user" + }, + "description": "Sample for DeleteTokenAuthUser", + "file": "memorystore_v1beta_generated_memorystore_delete_token_auth_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteTokenAuthUser_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_token_auth_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.delete_token_auth_user", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteTokenAuthUser", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "DeleteTokenAuthUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.DeleteTokenAuthUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "delete_token_auth_user" + }, + "description": "Sample for DeleteTokenAuthUser", + "file": "memorystore_v1beta_generated_memorystore_delete_token_auth_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteTokenAuthUser_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_delete_token_auth_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.export_backup", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ExportBackup", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "ExportBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.ExportBackupRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "export_backup" + }, + "description": "Sample for ExportBackup", + "file": "memorystore_v1beta_generated_memorystore_export_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_ExportBackup_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_export_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.export_backup", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ExportBackup", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "ExportBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.ExportBackupRequest" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "export_backup" + }, + "description": "Sample for ExportBackup", + "file": "memorystore_v1beta_generated_memorystore_export_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_ExportBackup_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_export_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.finish_migration", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.FinishMigration", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "FinishMigration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.FinishMigrationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "finish_migration" + }, + "description": "Sample for FinishMigration", + "file": "memorystore_v1beta_generated_memorystore_finish_migration_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_FinishMigration_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_finish_migration_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.finish_migration", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.FinishMigration", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "FinishMigration" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.FinishMigrationRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "force", + "type": "bool" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "finish_migration" + }, + "description": "Sample for FinishMigration", + "file": "memorystore_v1beta_generated_memorystore_finish_migration_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_FinishMigration_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_finish_migration_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_auth_token", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetAuthToken", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetAuthToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetAuthTokenRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.AuthToken", + "shortName": "get_auth_token" + }, + "description": "Sample for GetAuthToken", + "file": "memorystore_v1beta_generated_memorystore_get_auth_token_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetAuthToken_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_auth_token_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_auth_token", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetAuthToken", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetAuthToken" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetAuthTokenRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.AuthToken", + "shortName": "get_auth_token" + }, + "description": "Sample for GetAuthToken", + "file": "memorystore_v1beta_generated_memorystore_get_auth_token_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetAuthToken_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_auth_token_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_backup_collection", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetBackupCollection", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetBackupCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetBackupCollectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.BackupCollection", + "shortName": "get_backup_collection" + }, + "description": "Sample for GetBackupCollection", + "file": "memorystore_v1beta_generated_memorystore_get_backup_collection_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetBackupCollection_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_backup_collection_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_backup_collection", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetBackupCollection", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetBackupCollection" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetBackupCollectionRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.BackupCollection", + "shortName": "get_backup_collection" + }, + "description": "Sample for GetBackupCollection", + "file": "memorystore_v1beta_generated_memorystore_get_backup_collection_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetBackupCollection_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_backup_collection_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_backup", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetBackup", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "memorystore_v1beta_generated_memorystore_get_backup_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetBackup_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_backup_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_backup", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetBackup", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetBackup" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetBackupRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.Backup", + "shortName": "get_backup" + }, + "description": "Sample for GetBackup", + "file": "memorystore_v1beta_generated_memorystore_get_backup_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetBackup_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_backup_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_certificate_authority", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetCertificateAuthority", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetCertificateAuthority" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetCertificateAuthorityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.CertificateAuthority", + "shortName": "get_certificate_authority" + }, + "description": "Sample for GetCertificateAuthority", + "file": "memorystore_v1beta_generated_memorystore_get_certificate_authority_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetCertificateAuthority_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_certificate_authority_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_certificate_authority", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetCertificateAuthority", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetCertificateAuthority" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetCertificateAuthorityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.CertificateAuthority", + "shortName": "get_certificate_authority" + }, + "description": "Sample for GetCertificateAuthority", + "file": "memorystore_v1beta_generated_memorystore_get_certificate_authority_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetCertificateAuthority_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_certificate_authority_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "memorystore_v1beta_generated_memorystore_get_instance_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetInstance_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_instance_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_instance", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetInstance", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetInstance" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetInstanceRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.Instance", + "shortName": "get_instance" + }, + "description": "Sample for GetInstance", + "file": "memorystore_v1beta_generated_memorystore_get_instance_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetInstance_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_instance_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_shared_regional_certificate_authority", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetSharedRegionalCertificateAuthority" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority", + "shortName": "get_shared_regional_certificate_authority" + }, + "description": "Sample for GetSharedRegionalCertificateAuthority", + "file": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_shared_regional_certificate_authority", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetSharedRegionalCertificateAuthority" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority", + "shortName": "get_shared_regional_certificate_authority" + }, + "description": "Sample for GetSharedRegionalCertificateAuthority", + "file": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_token_auth_user", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetTokenAuthUser", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetTokenAuthUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetTokenAuthUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.TokenAuthUser", + "shortName": "get_token_auth_user" + }, + "description": "Sample for GetTokenAuthUser", + "file": "memorystore_v1beta_generated_memorystore_get_token_auth_user_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetTokenAuthUser_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_token_auth_user_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_token_auth_user", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetTokenAuthUser", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "GetTokenAuthUser" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.GetTokenAuthUserRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.memorystore_v1beta.types.TokenAuthUser", + "shortName": "get_token_auth_user" + }, + "description": "Sample for GetTokenAuthUser", + "file": "memorystore_v1beta_generated_memorystore_get_token_auth_user_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_GetTokenAuthUser_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_get_token_auth_user_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.list_auth_tokens", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListAuthTokens", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "ListAuthTokens" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.ListAuthTokensRequest" + }, + { + "name": "parent", + "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.memorystore_v1beta.services.memorystore.pagers.ListAuthTokensAsyncPager", + "shortName": "list_auth_tokens" + }, + "description": "Sample for ListAuthTokens", + "file": "memorystore_v1beta_generated_memorystore_list_auth_tokens_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListAuthTokens_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_list_auth_tokens_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.list_auth_tokens", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListAuthTokens", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "ListAuthTokens" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.ListAuthTokensRequest" + }, + { + "name": "parent", + "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.memorystore_v1beta.services.memorystore.pagers.ListAuthTokensPager", + "shortName": "list_auth_tokens" + }, + "description": "Sample for ListAuthTokens", + "file": "memorystore_v1beta_generated_memorystore_list_auth_tokens_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListAuthTokens_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_list_auth_tokens_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", + "shortName": "MemorystoreAsyncClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.list_backup_collections", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListBackupCollections", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "ListBackupCollections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.ListBackupCollectionsRequest" + }, + { + "name": "parent", + "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.memorystore_v1beta.services.memorystore.pagers.ListBackupCollectionsAsyncPager", + "shortName": "list_backup_collections" + }, + "description": "Sample for ListBackupCollections", + "file": "memorystore_v1beta_generated_memorystore_list_backup_collections_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListBackupCollections_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "memorystore_v1beta_generated_memorystore_list_backup_collections_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", + "shortName": "MemorystoreClient" + }, + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.list_backup_collections", + "method": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListBackupCollections", + "service": { + "fullName": "google.cloud.memorystore.v1beta.Memorystore", + "shortName": "Memorystore" + }, + "shortName": "ListBackupCollections" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.memorystore_v1beta.types.ListBackupCollectionsRequest" + }, + { + "name": "parent", + "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.memorystore_v1beta.services.memorystore.pagers.ListBackupCollectionsPager", + "shortName": "list_backup_collections" + }, + "description": "Sample for ListBackupCollections", + "file": "memorystore_v1beta_generated_memorystore_list_backup_collections_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListBackupCollections_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, "start": 27, "type": "SHORT" }, @@ -171,22 +3085,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 52, + "end": 45, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 59, - "start": 53, + "end": 48, + "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 63, - "start": 60, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_create_instance_sync.py" + "title": "memorystore_v1beta_generated_memorystore_list_backup_collections_sync.py" }, { "canonical": true, @@ -196,22 +3110,22 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", "shortName": "MemorystoreAsyncClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.delete_instance", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.list_backups", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteInstance", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListBackups", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "DeleteInstance" + "shortName": "ListBackups" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.DeleteInstanceRequest" + "type": "google.cloud.memorystore_v1beta.types.ListBackupsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -227,22 +3141,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation_async.AsyncOperation", - "shortName": "delete_instance" + "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListBackupsAsyncPager", + "shortName": "list_backups" }, - "description": "Sample for DeleteInstance", - "file": "memorystore_v1beta_generated_memorystore_delete_instance_async.py", + "description": "Sample for ListBackups", + "file": "memorystore_v1beta_generated_memorystore_list_backups_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteInstance_async", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListBackups_async", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -257,17 +3171,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_delete_instance_async.py" + "title": "memorystore_v1beta_generated_memorystore_list_backups_async.py" }, { "canonical": true, @@ -276,22 +3190,22 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", "shortName": "MemorystoreClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.delete_instance", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.list_backups", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.DeleteInstance", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListBackups", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "DeleteInstance" + "shortName": "ListBackups" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.DeleteInstanceRequest" + "type": "google.cloud.memorystore_v1beta.types.ListBackupsRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -307,22 +3221,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.api_core.operation.Operation", - "shortName": "delete_instance" + "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListBackupsPager", + "shortName": "list_backups" }, - "description": "Sample for DeleteInstance", - "file": "memorystore_v1beta_generated_memorystore_delete_instance_sync.py", + "description": "Sample for ListBackups", + "file": "memorystore_v1beta_generated_memorystore_list_backups_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_DeleteInstance_sync", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListBackups_sync", "segments": [ { - "end": 55, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 55, + "end": 52, "start": 27, "type": "SHORT" }, @@ -337,17 +3251,17 @@ "type": "REQUEST_INITIALIZATION" }, { - "end": 52, + "end": 48, "start": 46, "type": "REQUEST_EXECUTION" }, { - "end": 56, - "start": 53, + "end": 53, + "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_delete_instance_sync.py" + "title": "memorystore_v1beta_generated_memorystore_list_backups_sync.py" }, { "canonical": true, @@ -357,22 +3271,22 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", "shortName": "MemorystoreAsyncClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_certificate_authority", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.list_instances", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetCertificateAuthority", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListInstances", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "GetCertificateAuthority" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.GetCertificateAuthorityRequest" + "type": "google.cloud.memorystore_v1beta.types.ListInstancesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -388,22 +3302,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.types.CertificateAuthority", - "shortName": "get_certificate_authority" + "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListInstancesAsyncPager", + "shortName": "list_instances" }, - "description": "Sample for GetCertificateAuthority", - "file": "memorystore_v1beta_generated_memorystore_get_certificate_authority_async.py", + "description": "Sample for ListInstances", + "file": "memorystore_v1beta_generated_memorystore_list_instances_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_GetCertificateAuthority_async", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListInstances_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -423,12 +3337,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_get_certificate_authority_async.py" + "title": "memorystore_v1beta_generated_memorystore_list_instances_async.py" }, { "canonical": true, @@ -437,22 +3351,22 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", "shortName": "MemorystoreClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_certificate_authority", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.list_instances", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetCertificateAuthority", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListInstances", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "GetCertificateAuthority" + "shortName": "ListInstances" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.GetCertificateAuthorityRequest" + "type": "google.cloud.memorystore_v1beta.types.ListInstancesRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -468,22 +3382,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.types.CertificateAuthority", - "shortName": "get_certificate_authority" + "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListInstancesPager", + "shortName": "list_instances" }, - "description": "Sample for GetCertificateAuthority", - "file": "memorystore_v1beta_generated_memorystore_get_certificate_authority_sync.py", + "description": "Sample for ListInstances", + "file": "memorystore_v1beta_generated_memorystore_list_instances_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_GetCertificateAuthority_sync", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListInstances_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -503,12 +3417,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_get_certificate_authority_sync.py" + "title": "memorystore_v1beta_generated_memorystore_list_instances_sync.py" }, { "canonical": true, @@ -518,22 +3432,22 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", "shortName": "MemorystoreAsyncClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_instance", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.list_token_auth_users", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetInstance", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListTokenAuthUsers", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "GetInstance" + "shortName": "ListTokenAuthUsers" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.GetInstanceRequest" + "type": "google.cloud.memorystore_v1beta.types.ListTokenAuthUsersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -549,22 +3463,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.types.Instance", - "shortName": "get_instance" + "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListTokenAuthUsersAsyncPager", + "shortName": "list_token_auth_users" }, - "description": "Sample for GetInstance", - "file": "memorystore_v1beta_generated_memorystore_get_instance_async.py", + "description": "Sample for ListTokenAuthUsers", + "file": "memorystore_v1beta_generated_memorystore_list_token_auth_users_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_GetInstance_async", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListTokenAuthUsers_async", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -584,12 +3498,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_get_instance_async.py" + "title": "memorystore_v1beta_generated_memorystore_list_token_auth_users_async.py" }, { "canonical": true, @@ -598,22 +3512,22 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", "shortName": "MemorystoreClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_instance", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.list_token_auth_users", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetInstance", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListTokenAuthUsers", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "GetInstance" + "shortName": "ListTokenAuthUsers" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.GetInstanceRequest" + "type": "google.cloud.memorystore_v1beta.types.ListTokenAuthUsersRequest" }, { - "name": "name", + "name": "parent", "type": "str" }, { @@ -629,22 +3543,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.types.Instance", - "shortName": "get_instance" + "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListTokenAuthUsersPager", + "shortName": "list_token_auth_users" }, - "description": "Sample for GetInstance", - "file": "memorystore_v1beta_generated_memorystore_get_instance_sync.py", + "description": "Sample for ListTokenAuthUsers", + "file": "memorystore_v1beta_generated_memorystore_list_token_auth_users_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_GetInstance_sync", + "regionTag": "memorystore_v1beta_generated_Memorystore_ListTokenAuthUsers_sync", "segments": [ { - "end": 51, + "end": 52, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 52, "start": 27, "type": "SHORT" }, @@ -664,12 +3578,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 52, + "end": 53, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_get_instance_sync.py" + "title": "memorystore_v1beta_generated_memorystore_list_token_auth_users_sync.py" }, { "canonical": true, @@ -679,24 +3593,32 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", "shortName": "MemorystoreAsyncClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.get_shared_regional_certificate_authority", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.reschedule_maintenance", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.RescheduleMaintenance", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "GetSharedRegionalCertificateAuthority" + "shortName": "RescheduleMaintenance" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest" + "type": "google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest" }, { "name": "name", "type": "str" }, + { + "name": "reschedule_type", + "type": "google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest.RescheduleType" + }, + { + "name": "schedule_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -710,22 +3632,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority", - "shortName": "get_shared_regional_certificate_authority" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "reschedule_maintenance" }, - "description": "Sample for GetSharedRegionalCertificateAuthority", - "file": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_async.py", + "description": "Sample for RescheduleMaintenance", + "file": "memorystore_v1beta_generated_memorystore_reschedule_maintenance_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_async", + "regionTag": "memorystore_v1beta_generated_Memorystore_RescheduleMaintenance_async", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -735,22 +3657,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_async.py" + "title": "memorystore_v1beta_generated_memorystore_reschedule_maintenance_async.py" }, { "canonical": true, @@ -759,24 +3681,32 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", "shortName": "MemorystoreClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.get_shared_regional_certificate_authority", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.reschedule_maintenance", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.GetSharedRegionalCertificateAuthority", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.RescheduleMaintenance", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "GetSharedRegionalCertificateAuthority" + "shortName": "RescheduleMaintenance" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.GetSharedRegionalCertificateAuthorityRequest" + "type": "google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest" }, { "name": "name", "type": "str" }, + { + "name": "reschedule_type", + "type": "google.cloud.memorystore_v1beta.types.RescheduleMaintenanceRequest.RescheduleType" + }, + { + "name": "schedule_time", + "type": "google.protobuf.timestamp_pb2.Timestamp" + }, { "name": "retry", "type": "google.api_core.retry.Retry" @@ -790,22 +3720,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.types.SharedRegionalCertificateAuthority", - "shortName": "get_shared_regional_certificate_authority" + "resultType": "google.api_core.operation.Operation", + "shortName": "reschedule_maintenance" }, - "description": "Sample for GetSharedRegionalCertificateAuthority", - "file": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py", + "description": "Sample for RescheduleMaintenance", + "file": "memorystore_v1beta_generated_memorystore_reschedule_maintenance_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_GetSharedRegionalCertificateAuthority_sync", + "regionTag": "memorystore_v1beta_generated_Memorystore_RescheduleMaintenance_sync", "segments": [ { - "end": 51, + "end": 56, "start": 27, "type": "FULL" }, { - "end": 51, + "end": 56, "start": 27, "type": "SHORT" }, @@ -815,22 +3745,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 46, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 53, + "start": 47, "type": "REQUEST_EXECUTION" }, { - "end": 52, - "start": 49, + "end": 57, + "start": 54, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_get_shared_regional_certificate_authority_sync.py" + "title": "memorystore_v1beta_generated_memorystore_reschedule_maintenance_sync.py" }, { "canonical": true, @@ -840,23 +3770,19 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient", "shortName": "MemorystoreAsyncClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.list_instances", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreAsyncClient.start_migration", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListInstances", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.StartMigration", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "ListInstances" + "shortName": "StartMigration" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.ListInstancesRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.memorystore_v1beta.types.StartMigrationRequest" }, { "name": "retry", @@ -871,22 +3797,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListInstancesAsyncPager", - "shortName": "list_instances" + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "start_migration" }, - "description": "Sample for ListInstances", - "file": "memorystore_v1beta_generated_memorystore_list_instances_async.py", + "description": "Sample for StartMigration", + "file": "memorystore_v1beta_generated_memorystore_start_migration_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_ListInstances_async", + "regionTag": "memorystore_v1beta_generated_Memorystore_StartMigration_async", "segments": [ { - "end": 52, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 61, "start": 27, "type": "SHORT" }, @@ -896,22 +3822,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_list_instances_async.py" + "title": "memorystore_v1beta_generated_memorystore_start_migration_async.py" }, { "canonical": true, @@ -920,23 +3846,19 @@ "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient", "shortName": "MemorystoreClient" }, - "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.list_instances", + "fullName": "google.cloud.memorystore_v1beta.MemorystoreClient.start_migration", "method": { - "fullName": "google.cloud.memorystore.v1beta.Memorystore.ListInstances", + "fullName": "google.cloud.memorystore.v1beta.Memorystore.StartMigration", "service": { "fullName": "google.cloud.memorystore.v1beta.Memorystore", "shortName": "Memorystore" }, - "shortName": "ListInstances" + "shortName": "StartMigration" }, "parameters": [ { "name": "request", - "type": "google.cloud.memorystore_v1beta.types.ListInstancesRequest" - }, - { - "name": "parent", - "type": "str" + "type": "google.cloud.memorystore_v1beta.types.StartMigrationRequest" }, { "name": "retry", @@ -951,22 +3873,22 @@ "type": "Sequence[Tuple[str, Union[str, bytes]]]" } ], - "resultType": "google.cloud.memorystore_v1beta.services.memorystore.pagers.ListInstancesPager", - "shortName": "list_instances" + "resultType": "google.api_core.operation.Operation", + "shortName": "start_migration" }, - "description": "Sample for ListInstances", - "file": "memorystore_v1beta_generated_memorystore_list_instances_sync.py", + "description": "Sample for StartMigration", + "file": "memorystore_v1beta_generated_memorystore_start_migration_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "memorystore_v1beta_generated_Memorystore_ListInstances_sync", + "regionTag": "memorystore_v1beta_generated_Memorystore_StartMigration_sync", "segments": [ { - "end": 52, + "end": 61, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 61, "start": 27, "type": "SHORT" }, @@ -976,22 +3898,22 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 45, + "end": 51, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 48, - "start": 46, + "end": 58, + "start": 52, "type": "REQUEST_EXECUTION" }, { - "end": 53, - "start": 49, + "end": 62, + "start": 59, "type": "RESPONSE_HANDLING" } ], - "title": "memorystore_v1beta_generated_memorystore_list_instances_sync.py" + "title": "memorystore_v1beta_generated_memorystore_start_migration_sync.py" }, { "canonical": true, @@ -1046,12 +3968,12 @@ "regionTag": "memorystore_v1beta_generated_Memorystore_UpdateInstance_async", "segments": [ { - "end": 60, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 54, "start": 27, "type": "SHORT" }, @@ -1061,18 +3983,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], @@ -1130,12 +4052,12 @@ "regionTag": "memorystore_v1beta_generated_Memorystore_UpdateInstance_sync", "segments": [ { - "end": 60, + "end": 54, "start": 27, "type": "FULL" }, { - "end": 60, + "end": 54, "start": 27, "type": "SHORT" }, @@ -1145,18 +4067,18 @@ "type": "CLIENT_INITIALIZATION" }, { - "end": 50, + "end": 44, "start": 41, "type": "REQUEST_INITIALIZATION" }, { - "end": 57, - "start": 51, + "end": 51, + "start": 45, "type": "REQUEST_EXECUTION" }, { - "end": 61, - "start": 58, + "end": 55, + "start": 52, "type": "RESPONSE_HANDLING" } ], diff --git a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py index 66937835ef2f..514854769b88 100644 --- a/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py +++ b/packages/google-cloud-memorystore/tests/unit/gapic/memorystore_v1beta/test_memorystore.py @@ -40,9 +40,12 @@ import google.api_core.operation_async as operation_async # type: ignore import google.auth +import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.empty_pb2 as empty_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.type.dayofweek_pb2 as dayofweek_pb2 # type: ignore +import google.type.timeofday_pb2 as timeofday_pb2 # type: ignore from google.api_core import ( client_options, future, @@ -1283,7 +1286,11 @@ def test_memorystore_client_create_channel_credentials_file( credentials=file_creds, credentials_file=None, quota_project_id=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), scopes=None, default_host="memorystore.googleapis.com", ssl_credentials=None, @@ -1855,6 +1862,17 @@ def test_get_instance(request_type, transport: str = "grpc"): engine_version="engine_version_value", deletion_protection_enabled=True, mode=memorystore.Instance.Mode.STANDALONE, + simulate_maintenance_event=True, + ondemand_maintenance=True, + satisfies_pzs=True, + satisfies_pzi=True, + async_instance_endpoints_deletion_enabled=True, + kms_key="kms_key_value", + backup_collection="backup_collection_value", + maintenance_version="maintenance_version_value", + effective_maintenance_version="effective_maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + allow_fewer_zones_deployment=True, server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, server_ca_pool="server_ca_pool_value", rotate_server_certificate=True, @@ -1886,6 +1904,21 @@ def test_get_instance(request_type, transport: str = "grpc"): assert response.engine_version == "engine_version_value" assert response.deletion_protection_enabled is True assert response.mode == memorystore.Instance.Mode.STANDALONE + assert response.simulate_maintenance_event is True + assert response.ondemand_maintenance is True + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.async_instance_endpoints_deletion_enabled is True + assert response.kms_key == "kms_key_value" + assert response.backup_collection == "backup_collection_value" + assert response.maintenance_version == "maintenance_version_value" + assert ( + response.effective_maintenance_version == "effective_maintenance_version_value" + ) + assert response.available_maintenance_versions == [ + "available_maintenance_versions_value" + ] + assert response.allow_fewer_zones_deployment is True assert ( response.server_ca_mode == memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA @@ -2034,6 +2067,17 @@ async def test_get_instance_async(request_type, transport: str = "grpc_asyncio") engine_version="engine_version_value", deletion_protection_enabled=True, mode=memorystore.Instance.Mode.STANDALONE, + simulate_maintenance_event=True, + ondemand_maintenance=True, + satisfies_pzs=True, + satisfies_pzi=True, + async_instance_endpoints_deletion_enabled=True, + kms_key="kms_key_value", + backup_collection="backup_collection_value", + maintenance_version="maintenance_version_value", + effective_maintenance_version="effective_maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + allow_fewer_zones_deployment=True, server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, server_ca_pool="server_ca_pool_value", rotate_server_certificate=True, @@ -2066,6 +2110,21 @@ async def test_get_instance_async(request_type, transport: str = "grpc_asyncio") assert response.engine_version == "engine_version_value" assert response.deletion_protection_enabled is True assert response.mode == memorystore.Instance.Mode.STANDALONE + assert response.simulate_maintenance_event is True + assert response.ondemand_maintenance is True + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.async_instance_endpoints_deletion_enabled is True + assert response.kms_key == "kms_key_value" + assert response.backup_collection == "backup_collection_value" + assert response.maintenance_version == "maintenance_version_value" + assert ( + response.effective_maintenance_version == "effective_maintenance_version_value" + ) + assert response.available_maintenance_versions == [ + "available_maintenance_versions_value" + ] + assert response.allow_fewer_zones_deployment is True assert ( response.server_ca_mode == memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA @@ -2478,7 +2537,9 @@ def test_create_instance_flattened(): # using the keyword arguments to the method. client.create_instance( parent="parent_value", - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), instance_id="instance_id_value", ) @@ -2490,7 +2551,9 @@ def test_create_instance_flattened(): mock_val = "parent_value" assert arg == mock_val arg = args[0].instance - mock_val = memorystore.Instance(name="name_value") + mock_val = memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ) assert arg == mock_val arg = args[0].instance_id mock_val = "instance_id_value" @@ -2508,7 +2571,9 @@ def test_create_instance_flattened_error(): client.create_instance( memorystore.CreateInstanceRequest(), parent="parent_value", - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), instance_id="instance_id_value", ) @@ -2531,7 +2596,9 @@ async def test_create_instance_flattened_async(): # using the keyword arguments to the method. response = await client.create_instance( parent="parent_value", - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), instance_id="instance_id_value", ) @@ -2543,7 +2610,9 @@ async def test_create_instance_flattened_async(): mock_val = "parent_value" assert arg == mock_val arg = args[0].instance - mock_val = memorystore.Instance(name="name_value") + mock_val = memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ) assert arg == mock_val arg = args[0].instance_id mock_val = "instance_id_value" @@ -2562,7 +2631,9 @@ async def test_create_instance_flattened_error_async(): await client.create_instance( memorystore.CreateInstanceRequest(), parent="parent_value", - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), instance_id="instance_id_value", ) @@ -2821,7 +2892,9 @@ def test_update_instance_flattened(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.update_instance( - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2830,7 +2903,9 @@ def test_update_instance_flattened(): assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] arg = args[0].instance - mock_val = memorystore.Instance(name="name_value") + mock_val = memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ) assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -2847,7 +2922,9 @@ def test_update_instance_flattened_error(): with pytest.raises(ValueError): client.update_instance( memorystore.UpdateInstanceRequest(), - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2869,7 +2946,9 @@ async def test_update_instance_flattened_async(): # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. response = await client.update_instance( - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -2878,7 +2957,9 @@ async def test_update_instance_flattened_async(): assert len(call.mock_calls) _, args, _ = call.mock_calls[0] arg = args[0].instance - mock_val = memorystore.Instance(name="name_value") + mock_val = memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ) assert arg == mock_val arg = args[0].update_mask mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) @@ -2896,7 +2977,9 @@ async def test_update_instance_flattened_error_async(): with pytest.raises(ValueError): await client.update_instance( memorystore.UpdateInstanceRequest(), - instance=memorystore.Instance(name="name_value"), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @@ -3921,13 +4004,79 @@ async def test_get_shared_regional_certificate_authority_flattened_error_async() ) -def test_list_instances_rest_use_cached_wrapped_rpc(): +@pytest.mark.parametrize( + "request_type", + [ + memorystore.RescheduleMaintenanceRequest(), + {}, + ], +) +def test_reschedule_maintenance(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.reschedule_maintenance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.RescheduleMaintenanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_reschedule_maintenance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.RescheduleMaintenanceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.reschedule_maintenance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.RescheduleMaintenanceRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_reschedule_maintenance_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 = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -3935,260 +4084,375 @@ def test_list_instances_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods + assert ( + client._transport.reschedule_maintenance + 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_instances] = mock_rpc - + client._transport._wrapped_methods[client._transport.reschedule_maintenance] = ( + mock_rpc + ) request = {} - client.list_instances(request) + client.reschedule_maintenance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_instances(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.reschedule_maintenance(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_instances_rest_required_fields( - request_type=memorystore.ListInstancesRequest, +@pytest.mark.asyncio +async def test_reschedule_maintenance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MemorystoreRestTransport - - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) - - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["parent"] = "parent_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - ) - jsonified_request.update(unset_fields) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Ensure method has been cached + assert ( + client._client._transport.reschedule_maintenance + in client._client._transport._wrapped_methods + ) - # Designate an appropriate value for the returned response. - return_value = memorystore.ListInstancesResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.reschedule_maintenance + ] = mock_rpc - response_value = Response() - response_value.status_code = 200 + request = {} + await client.reschedule_maintenance(request) - # Convert return value to protobuf type - return_value = memorystore.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() - response = client.list_instances(request) + await client.reschedule_maintenance(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # 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_instances_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.RescheduleMaintenanceRequest(), + {}, + ], +) +async def test_reschedule_maintenance_async( + request_type, transport: str = "grpc_asyncio" +): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - unset_fields = transport.list_instances._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "filter", - "orderBy", - "pageSize", - "pageToken", - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") ) - & set(("parent",)) - ) + response = await client.reschedule_maintenance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.RescheduleMaintenanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -def test_list_instances_rest_flattened(): +def test_reschedule_maintenance_field_headers(): client = MemorystoreClient( 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 = memorystore.ListInstancesResponse() - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.RescheduleMaintenanceRequest() - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - ) - mock_args.update(sample_request) + request.name = "name_value" - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.ListInstancesResponse.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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reschedule_maintenance(request) - client.list_instances(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_reschedule_maintenance_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.RescheduleMaintenanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.reschedule_maintenance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_reschedule_maintenance_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.reschedule_maintenance( + name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) # 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/v1beta/{parent=projects/*/locations/*}/instances" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].reschedule_type + mock_val = memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + assert arg == mock_val + assert TimestampRule().to_proto( + args[0].schedule_time + ) == timestamp_pb2.Timestamp(seconds=751) -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_reschedule_maintenance_flattened_error(): client = MemorystoreClient( 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_instances( - memorystore.ListInstancesRequest(), - parent="parent_value", + client.reschedule_maintenance( + memorystore.RescheduleMaintenanceRequest(), + name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), ) -def test_list_instances_rest_pager(transport: str = "rest"): +@pytest.mark.asyncio +async def test_reschedule_maintenance_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.reschedule_maintenance( + name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].reschedule_type + mock_val = memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE + assert arg == mock_val + assert TimestampRule().to_proto( + args[0].schedule_time + ) == timestamp_pb2.Timestamp(seconds=751) + + +@pytest.mark.asyncio +async def test_reschedule_maintenance_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.reschedule_maintenance( + memorystore.RescheduleMaintenanceRequest(), + name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListBackupCollectionsRequest(), + {}, + ], +) +def test_list_backup_collections(request_type, transport: str = "grpc"): client = MemorystoreClient( 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 = ( - memorystore.ListInstancesResponse( - instances=[ - memorystore.Instance(), - memorystore.Instance(), - memorystore.Instance(), - ], - next_page_token="abc", - ), - memorystore.ListInstancesResponse( - instances=[], - next_page_token="def", - ), - memorystore.ListInstancesResponse( - instances=[ - memorystore.Instance(), - ], - next_page_token="ghi", - ), - memorystore.ListInstancesResponse( - instances=[ - memorystore.Instance(), - memorystore.Instance(), - ], - ), + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListBackupCollectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - # Two responses for two calls - response = response + response + response = client.list_backup_collections(request) - # Wrap the values into proper Response objs - response = tuple(memorystore.ListInstancesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.ListBackupCollectionsRequest() + assert args[0] == request - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupCollectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - pager = client.list_instances(request=sample_request) - assert pager.next_page_token == "abc" - assert str(pager).startswith(f"{pager.__class__.__name__}<") +def test_list_backup_collections_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, memorystore.Instance) for i in results) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.ListBackupCollectionsRequest( + parent="parent_value", + page_token="page_token_value", + ) - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backup_collections(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupCollectionsRequest( + parent="parent_value", + page_token="page_token_value", + ) + assert args[0] == request_msg -def test_get_instance_rest_use_cached_wrapped_rpc(): +def test_list_backup_collections_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 = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4196,393 +4460,561 @@ def test_get_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_instance in client._transport._wrapped_methods + assert ( + client._transport.list_backup_collections + 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_instance] = mock_rpc - + client._transport._wrapped_methods[ + client._transport.list_backup_collections + ] = mock_rpc request = {} - client.get_instance(request) + client.list_backup_collections(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_instance(request) + client.list_backup_collections(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_instance_rest_required_fields(request_type=memorystore.GetInstanceRequest): - transport_class = transports.MemorystoreRestTransport +@pytest.mark.asyncio +async def test_list_backup_collections_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # verify fields with default values are dropped + # Ensure method has been cached + assert ( + client._client._transport.list_backup_collections + in client._client._transport._wrapped_methods + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backup_collections + ] = mock_rpc - # verify required fields with default values are now present + request = {} + await client.list_backup_collections(request) - jsonified_request["name"] = "name_value" + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + await client.list_backup_collections(request) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListBackupCollectionsRequest(), + {}, + ], +) +async def test_list_backup_collections_async( + request_type, transport: str = "grpc_asyncio" +): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = memorystore.Instance() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "get", - "query_params": pb_request, - } - transcode.return_value = transcode_result + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - response_value = Response() - response_value.status_code = 200 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupCollectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backup_collections(request) - # Convert return value to protobuf type - return_value = memorystore.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.ListBackupCollectionsRequest() + assert args[0] == request - 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"} + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupCollectionsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] - response = client.get_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) +def test_list_backup_collections_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListBackupCollectionsRequest() -def test_get_instance_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + request.parent = "parent_value" - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + call.return_value = memorystore.ListBackupCollectionsResponse() + client.list_backup_collections(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_get_instance_rest_flattened(): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backup_collections_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = memorystore.Instance() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListBackupCollectionsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupCollectionsResponse() ) - mock_args.update(sample_request) + await client.list_backup_collections(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 = memorystore.Instance.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"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_instance(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backup_collections_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListBackupCollectionsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backup_collections( + parent="parent_value", + ) # 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/v1beta/{name=projects/*/locations/*/instances/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_get_instance_rest_flattened_error(transport: str = "rest"): +def test_list_backup_collections_flattened_error(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_instance( - memorystore.GetInstanceRequest(), - name="name_value", + client.list_backup_collections( + memorystore.ListBackupCollectionsRequest(), + parent="parent_value", ) -def test_create_instance_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 = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_list_backup_collections_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListBackupCollectionsResponse() - # 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. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupCollectionsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backup_collections( + parent="parent_value", ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc - - request = {} - client.create_instance(request) - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - client.create_instance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_list_backup_collections_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backup_collections( + memorystore.ListBackupCollectionsRequest(), + parent="parent_value", + ) -def test_create_instance_rest_required_fields( - request_type=memorystore.CreateInstanceRequest, -): - transport_class = transports.MemorystoreRestTransport - request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_list_backup_collections_pager(transport_name: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped - assert "instanceId" not in jsonified_request + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + next_page_token="abc", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[], + next_page_token="def", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + ), + RuntimeError, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backup_collections(request={}, retry=retry, timeout=timeout) - # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "instance_id", - "request_id", - ) - ) - jsonified_request.update(unset_fields) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.BackupCollection) for i in results) - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" +def test_list_backup_collections_pages(transport_name: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "post", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + next_page_token="abc", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[], + next_page_token="def", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backup_collections(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} +@pytest.mark.asyncio +async def test_list_backup_collections_async_pager(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) - response = client.create_instance(request) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + next_page_token="abc", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[], + next_page_token="def", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backup_collections( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + assert len(responses) == 6 + assert all(isinstance(i, memorystore.BackupCollection) for i in responses) -def test_create_instance_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials + +@pytest.mark.asyncio +async def test_list_backup_collections_async_pages(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.create_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "instanceId", - "requestId", - ) - ) - & set( - ( - "parent", - "instanceId", - "instance", - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + next_page_token="abc", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[], + next_page_token="def", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + ), + RuntimeError, ) - ) + pages = [] + async for page_ in (await client.list_backup_collections(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_create_instance_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetBackupCollectionRequest(), + {}, + ], +) +def test_get_backup_collection(request_type, transport: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance=memorystore.Instance(name="name_value"), - instance_id="instance_id_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.BackupCollection( + name="name_value", + instance_uid="instance_uid_value", + instance="instance_value", + kms_key="kms_key_value", + uid="uid_value", + total_backup_size_bytes=2457, + total_backup_count=1921, ) - mock_args.update(sample_request) + response = client.get_backup_collection(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.GetBackupCollectionRequest() + assert args[0] == request - client.create_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta/{parent=projects/*/locations/*}/instances" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.BackupCollection) + assert response.name == "name_value" + assert response.instance_uid == "instance_uid_value" + assert response.instance == "instance_value" + assert response.kms_key == "kms_key_value" + assert response.uid == "uid_value" + assert response.total_backup_size_bytes == 2457 + assert response.total_backup_count == 1921 -def test_create_instance_rest_flattened_error(transport: str = "rest"): +def test_get_backup_collection_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - memorystore.CreateInstanceRequest(), - parent="parent_value", - instance=memorystore.Instance(name="name_value"), - instance_id="instance_id_value", + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.GetBackupCollectionRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup_collection(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupCollectionRequest( + name="name_value", ) + assert args[0] == request_msg -def test_update_instance_rest_use_cached_wrapped_rpc(): +def test_get_backup_collection_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 = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4590,372 +5022,356 @@ def test_update_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + assert ( + client._transport.get_backup_collection + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc - + client._transport._wrapped_methods[client._transport.get_backup_collection] = ( + mock_rpc + ) request = {} - client.update_instance(request) + client.get_backup_collection(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper + client.get_backup_collection(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_collection_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 wrapper_fn.reset_mock() - client.update_instance(request) + # Ensure method has been cached + assert ( + client._client._transport.get_backup_collection + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup_collection + ] = mock_rpc + + request = {} + await client.get_backup_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_backup_collection(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_update_instance_rest_required_fields( - request_type=memorystore.UpdateInstanceRequest, +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetBackupCollectionRequest(), + {}, + ], +) +async def test_get_backup_collection_async( + request_type, transport: str = "grpc_asyncio" ): - transport_class = transports.MemorystoreRestTransport - - request_init = {} - 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) + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, ) - # verify fields with default values are dropped + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.BackupCollection( + name="name_value", + instance_uid="instance_uid_value", + instance="instance_value", + kms_key="kms_key_value", + uid="uid_value", + total_backup_size_bytes=2457, + total_backup_count=1921, + ) + ) + response = await client.get_backup_collection(request) - # verify required fields with default values are now present + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.GetBackupCollectionRequest() + assert args[0] == request - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "request_id", - "update_mask", - ) - ) - jsonified_request.update(unset_fields) + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.BackupCollection) + assert response.name == "name_value" + assert response.instance_uid == "instance_uid_value" + assert response.instance == "instance_value" + assert response.kms_key == "kms_key_value" + assert response.uid == "uid_value" + assert response.total_backup_size_bytes == 2457 + assert response.total_backup_count == 1921 - # verify required fields with non-default values are left alone +def test_get_backup_collection_field_headers(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "patch", - "query_params": pb_request, - } - transcode_result["body"] = pb_request - transcode.return_value = transcode_result + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetBackupCollectionRequest() - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + request.name = "name_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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + call.return_value = memorystore.BackupCollection() + client.get_backup_collection(request) - response = client.update_instance(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -def test_update_instance_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_get_backup_collection_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = transport.update_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "requestId", - "updateMask", - ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetBackupCollectionRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.BackupCollection() ) - & set(("instance",)) - ) + await client.get_backup_collection(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -def test_update_instance_rest_flattened(): + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_backup_collection_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - - # get truthy value for each flattened field - mock_args = dict( - instance=memorystore.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.BackupCollection() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup_collection( + name="name_value", ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta/{instance.name=projects/*/locations/*/instances/*}" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_get_backup_collection_flattened_error(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_instance( - memorystore.UpdateInstanceRequest(), - instance=memorystore.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_backup_collection( + memorystore.GetBackupCollectionRequest(), + name="name_value", ) -def test_delete_instance_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 = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() +@pytest.mark.asyncio +async def test_get_backup_collection_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.BackupCollection() - # 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. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.BackupCollection() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup_collection( + name="name_value", ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc - - request = {} - client.delete_instance(request) - - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_instance(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -def test_delete_instance_rest_required_fields( - request_type=memorystore.DeleteInstanceRequest, -): - transport_class = transports.MemorystoreRestTransport - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +@pytest.mark.asyncio +async def test_get_backup_collection_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - # verify fields with default values are dropped - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - - # verify required fields with default values are now present - - jsonified_request["name"] = "name_value" - - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) - jsonified_request.update(unset_fields) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup_collection( + memorystore.GetBackupCollectionRequest(), + name="name_value", + ) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListBackupsRequest(), + {}, + ], +) +def test_list_backups(request_type, transport: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - request = request_type(**request_init) - - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # We need to mock transcode() because providing default values - # for required fields will fail the real version if the http_options - # expect actual values for those fields. - with mock.patch.object(path_template, "transcode") as transcode: - # A uri without fields and an empty body will force all the - # request fields to show up in the query_params. - pb_request = request_type.pb(request) - transcode_result = { - "uri": "v1/sample_method", - "method": "delete", - "query_params": pb_request, - } - transcode.return_value = transcode_result - - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - response = client.delete_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backups(request) -def test_delete_instance_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials - ) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.ListBackupsRequest() + assert args[0] == request - unset_fields = transport.delete_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_instance_rest_flattened(): +def test_list_backups_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - - client.delete_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1beta/{name=projects/*/locations/*/instances/*}" - % client.transport._host, - args[1], - ) - - -def test_delete_instance_rest_flattened_error(transport: str = "rest"): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.ListBackupsRequest( + parent="parent_value", + page_token="page_token_value", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_instance( - memorystore.DeleteInstanceRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_backups(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupsRequest( + parent="parent_value", + page_token="page_token_value", ) + assert args[0] == request_msg -def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): +def test_list_backups_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 = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport="grpc", ) # Should wrap all calls on client creation @@ -4963,845 +5379,14611 @@ def test_get_certificate_authority_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_certificate_authority - in client._transport._wrapped_methods - ) + assert client._transport.list_backups 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_certificate_authority - ] = mock_rpc - + client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc request = {} - client.get_certificate_authority(request) + client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_certificate_authority(request) + client.list_backups(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_certificate_authority_rest_required_fields( - request_type=memorystore.GetCertificateAuthorityRequest, +@pytest.mark.asyncio +async def test_list_backups_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", ): - transport_class = transports.MemorystoreRestTransport - - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) - ) + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # verify fields with default values are dropped + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Ensure method has been cached + assert ( + client._client._transport.list_backups + in client._client._transport._wrapped_methods + ) - # verify required fields with default values are now present + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_backups + ] = mock_rpc - jsonified_request["name"] = "name_value" + request = {} + await client.list_backups(request) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_certificate_authority._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + await client.list_backups(request) - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Designate an appropriate value for the returned response. - return_value = memorystore.CertificateAuthority() - # 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 +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListBackupsRequest(), + {}, + ], +) +async def test_list_backups_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) - # Convert return value to protobuf type - return_value = memorystore.CertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - 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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_backups(request) - response = client.get_certificate_authority(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.ListBackupsRequest() + assert args[0] == request - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_certificate_authority_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials +def test_list_backups_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListBackupsRequest() + request.parent = "parent_value" -def test_get_certificate_authority_rest_flattened(): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = memorystore.ListBackupsResponse() + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_backups_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - # 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 = memorystore.CertificateAuthority() + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListBackupsRequest() - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/instances/sample3" - } + request.parent = "parent_value" - # get truthy value for each flattened field - mock_args = dict( - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupsResponse() ) - mock_args.update(sample_request) + await client.list_backups(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 = memorystore.CertificateAuthority.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"} + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request - client.get_certificate_authority(**mock_args) + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_backups_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListBackupsResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_backups( + parent="parent_value", + ) # 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/v1beta/{name=projects/*/locations/*/instances/*}/certificateAuthority" - % client.transport._host, - args[1], - ) + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val -def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): +def test_list_backups_flattened_error(): client = MemorystoreClient( 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_certificate_authority( - memorystore.GetCertificateAuthorityRequest(), - name="name_value", + client.list_backups( + memorystore.ListBackupsRequest(), + parent="parent_value", ) -def test_get_shared_regional_certificate_authority_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 = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) - # Should wrap all calls on client creation - assert wrapper_fn.call_count > 0 - wrapper_fn.reset_mock() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListBackupsResponse() - # Ensure method has been cached - assert ( - client._transport.get_shared_regional_certificate_authority - in client._transport._wrapped_methods + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupsResponse() ) - - # 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. + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backups( + parent="parent_value", ) - client._transport._wrapped_methods[ - client._transport.get_shared_regional_certificate_authority - ] = mock_rpc - request = {} - client.get_shared_regional_certificate_authority(request) + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val - # Establish that the underlying gRPC stub method was called. - assert mock_rpc.call_count == 1 - client.get_shared_regional_certificate_authority(request) - - # Establish that a new wrapper was not created for this call - assert wrapper_fn.call_count == 0 - assert mock_rpc.call_count == 2 +@pytest.mark.asyncio +async def test_list_backups_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backups( + memorystore.ListBackupsRequest(), + parent="parent_value", + ) -def test_get_shared_regional_certificate_authority_rest_required_fields( - request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, -): - transport_class = transports.MemorystoreRestTransport - request_init = {} - request_init["name"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson(pb_request, use_integers_for_enums=False) +def test_list_backups_pager(transport_name: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # verify fields with default values are dropped + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + memorystore.Backup(), + ], + next_page_token="abc", + ), + memorystore.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + ], + ), + RuntimeError, + ) - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_shared_regional_certificate_authority._get_unset_required_fields( - jsonified_request - ) - jsonified_request.update(unset_fields) + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backups(request={}, retry=retry, timeout=timeout) - # verify required fields with default values are now present + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout - jsonified_request["name"] = "name_value" + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).get_shared_regional_certificate_authority._get_unset_required_fields( - jsonified_request - ) - jsonified_request.update(unset_fields) + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.Backup) for i in results) - # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" +def test_list_backups_pages(transport_name: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport_name, ) - request = request_type(**request_init) - # Designate an appropriate value for the returned response. - return_value = memorystore.SharedRegionalCertificateAuthority() - # 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 + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + memorystore.Backup(), + ], + next_page_token="abc", + ), + memorystore.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + ], + ), + RuntimeError, + ) + pages = list(client.list_backups(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token - response_value = Response() - response_value.status_code = 200 - # Convert return value to protobuf type - return_value = memorystore.SharedRegionalCertificateAuthority.pb( - return_value - ) - json_return_value = json_format.MessageToJson(return_value) +@pytest.mark.asyncio +async def test_list_backups_async_pager(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) - 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"} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + memorystore.Backup(), + ], + next_page_token="abc", + ), + memorystore.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_backups( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") - response = client.get_shared_regional_certificate_authority(request) + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - expected_params = [("$alt", "json;enum-encoding=int")] - actual_params = req.call_args.kwargs["params"] - assert sorted(expected_params) == sorted(actual_params) + assert len(responses) == 6 + assert all(isinstance(i, memorystore.Backup) for i in responses) -def test_get_shared_regional_certificate_authority_rest_unset_required_fields(): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials +@pytest.mark.asyncio +async def test_list_backups_async_pages(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - unset_fields = ( - transport.get_shared_regional_certificate_authority._get_unset_required_fields( - {} + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + memorystore.Backup(), + ], + next_page_token="abc", + ), + memorystore.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + ], + ), + RuntimeError, ) - ) - assert set(unset_fields) == (set(()) & set(("name",))) + pages = [] + async for page_ in (await client.list_backups(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -def test_get_shared_regional_certificate_authority_rest_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetBackupRequest(), + {}, + ], +) +def test_get_backup(request_type, transport: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = memorystore.SharedRegionalCertificateAuthority() - - # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" - } + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # get truthy value for each flattened field - mock_args = dict( + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.Backup( name="name_value", + instance="instance_value", + instance_uid="instance_uid_value", + total_size_bytes=1732, + engine_version="engine_version_value", + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + replica_count=1384, + shard_count=1178, + backup_type=memorystore.Backup.BackupType.ON_DEMAND, + state=memorystore.Backup.State.CREATING, + uid="uid_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 = memorystore.SharedRegionalCertificateAuthority.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_backup(request) - client.get_shared_regional_certificate_authority(**mock_args) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.GetBackupRequest() + assert args[0] == request - # 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/v1beta/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}" - % client.transport._host, - args[1], - ) + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.Backup) + assert response.name == "name_value" + assert response.instance == "instance_value" + assert response.instance_uid == "instance_uid_value" + assert response.total_size_bytes == 1732 + assert response.engine_version == "engine_version_value" + assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO + assert response.replica_count == 1384 + assert response.shard_count == 1178 + assert response.backup_type == memorystore.Backup.BackupType.ON_DEMAND + assert response.state == memorystore.Backup.State.CREATING + assert response.uid == "uid_value" -def test_get_shared_regional_certificate_authority_rest_flattened_error( - transport: str = "rest", -): +def test_get_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_shared_regional_certificate_authority( - memorystore.GetSharedRegionalCertificateAuthorityRequest(), - name="name_value", - ) - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.MemorystoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.GetBackupRequest( + name="name_value", ) - with pytest.raises(ValueError): + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_backup(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_backup_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 = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + transport="grpc", ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.MemorystoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MemorystoreClient( - client_options={"credentials_file": "credentials.json"}, - transport=transport, + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_backup 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_backup] = mock_rpc + request = {} + client.get_backup(request) - # It is an error to provide an api_key and a transport instance. - transport = transports.MemorystoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = MemorystoreClient( - client_options=options, + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), 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 = MemorystoreClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() - # It is an error to provide scopes and a transport instance. - transport = transports.MemorystoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = MemorystoreClient( - client_options={"scopes": ["1", "2"]}, - transport=transport, + # Ensure method has been cached + assert ( + client._client._transport.get_backup + in client._client._transport._wrapped_methods ) + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_backup + ] = mock_rpc -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.MemorystoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = MemorystoreClient(transport=transport) - assert client.transport is transport + request = {} + await client.get_backup(request) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.MemorystoreGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + await client.get_backup(request) - transport = transports.MemorystoreGrpcAsyncIOTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - channel = transport.grpc_channel - assert channel + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 +@pytest.mark.asyncio @pytest.mark.parametrize( - "transport_class", + "request_type", [ - transports.MemorystoreGrpcTransport, - transports.MemorystoreGrpcAsyncIOTransport, - transports.MemorystoreRestTransport, + memorystore.GetBackupRequest(), + {}, ], ) -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() +async def test_get_backup_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type -def test_transport_kind_grpc(): - transport = MemorystoreClient.get_transport_class("grpc")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "grpc" + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.Backup( + name="name_value", + instance="instance_value", + instance_uid="instance_uid_value", + total_size_bytes=1732, + engine_version="engine_version_value", + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + replica_count=1384, + shard_count=1178, + backup_type=memorystore.Backup.BackupType.ON_DEMAND, + state=memorystore.Backup.State.CREATING, + uid="uid_value", + ) + ) + response = await client.get_backup(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.GetBackupRequest() + assert args[0] == request -def test_initialize_client_w_grpc(): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="grpc" - ) - assert client is not None + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.Backup) + assert response.name == "name_value" + assert response.instance == "instance_value" + assert response.instance_uid == "instance_uid_value" + assert response.total_size_bytes == 1732 + assert response.engine_version == "engine_version_value" + assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO + assert response.replica_count == 1384 + assert response.shard_count == 1178 + assert response.backup_type == memorystore.Backup.BackupType.ON_DEMAND + assert response.state == memorystore.Backup.State.CREATING + assert response.uid == "uid_value" -# 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_instances_empty_call_grpc(): +def test_get_backup_field_headers(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value = memorystore.ListInstancesResponse() - client.list_instances(request=None) - - # Establish that the underlying stub method was called. - call.assert_called() - _, args, _ = call.mock_calls[0] - request_msg = memorystore.ListInstancesRequest() - assert args[0] == request_msg - + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetBackupRequest() -# 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_instance_empty_call_grpc(): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) + request.name = "name_value" - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - call.return_value = memorystore.Instance() - client.get_instance(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = memorystore.Backup() + client.get_backup(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetInstanceRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# 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_create_instance_empty_call_grpc(): - client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", +@pytest.mark.asyncio +async def test_get_backup_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_instance(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetBackupRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(memorystore.Backup()) + await client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = memorystore.CreateInstanceRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# 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_update_instance_empty_call_grpc(): +def test_get_backup_flattened(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_instance(request=None) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.Backup() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_backup( + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = memorystore.UpdateInstanceRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# 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_delete_instance_empty_call_grpc(): +def test_get_backup_flattened_error(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_instance(request=None) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_backup( + memorystore.GetBackupRequest(), + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + +@pytest.mark.asyncio +async def test_get_backup_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.Backup() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(memorystore.Backup()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_backup( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = memorystore.DeleteInstanceRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# 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_certificate_authority_empty_call_grpc(): +@pytest.mark.asyncio +async def test_get_backup_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup( + memorystore.GetBackupRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteBackupRequest(), + {}, + ], +) +def test_delete_backup(request_type, transport: str = "grpc"): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" - ) as call: - call.return_value = memorystore.CertificateAuthority() - client.get_certificate_authority(request=None) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type - # Establish that the underlying stub method was called. - call.assert_called() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetCertificateAuthorityRequest() - assert args[0] == request_msg + request = memorystore.DeleteBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# 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_shared_regional_certificate_authority_empty_call_grpc(): +def test_delete_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_shared_regional_certificate_authority), "__call__" - ) as call: - call.return_value = memorystore.SharedRegionalCertificateAuthority() - client.get_shared_regional_certificate_authority(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.DeleteBackupRequest( + name="name_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + request_msg = memorystore.DeleteBackupRequest( + name="name_value", + ) assert args[0] == request_msg -def test_transport_kind_grpc_asyncio(): - transport = MemorystoreAsyncClient.get_transport_class("grpc_asyncio")( - credentials=async_anonymous_credentials() - ) - assert transport.kind == "grpc_asyncio" +def test_delete_backup_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() -def test_initialize_client_w_grpc_asyncio(): - client = MemorystoreAsyncClient( - credentials=async_anonymous_credentials(), transport="grpc_asyncio" - ) - assert client is not None + # Ensure method has been cached + assert client._transport.delete_backup 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.delete_backup] = mock_rpc + request = {} + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_list_instances_empty_call_grpc_asyncio(): +async def test_delete_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_backup + ] = mock_rpc + + request = {} + await client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteBackupRequest(), + {}, + ], +) +async def test_delete_backup_async(request_type, transport: str = "grpc_asyncio"): client = MemorystoreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + transport=transport, ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - memorystore.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - await client.list_instances(request=None) + response = await client.delete_backup(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = memorystore.ListInstancesRequest() - assert args[0] == request_msg + request = memorystore.DeleteBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_instance_empty_call_grpc_asyncio(): - client = MemorystoreAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_backup_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - memorystore.Instance( - name="name_value", - state=memorystore.Instance.State.CREATING, - uid="uid_value", - replica_count=1384, - authorization_mode=memorystore.Instance.AuthorizationMode.AUTH_DISABLED, - transit_encryption_mode=memorystore.Instance.TransitEncryptionMode.TRANSIT_ENCRYPTION_DISABLED, - shard_count=1178, - node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, - engine_version="engine_version_value", - deletion_protection_enabled=True, - mode=memorystore.Instance.Mode.STANDALONE, - server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, - server_ca_pool="server_ca_pool_value", - rotate_server_certificate=True, - ) - ) - await client.get_instance(request=None) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.DeleteBackupRequest() - # Establish that the underlying stub method was called. - call.assert_called() + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetInstanceRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_create_instance_empty_call_grpc_asyncio(): +async def test_delete_backup_field_headers_async(): client = MemorystoreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.DeleteBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + operations_pb2.Operation(name="operations/op") ) - await client.create_instance(request=None) + await client.delete_backup(request) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = memorystore.CreateInstanceRequest() - assert args[0] == request_msg + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_update_instance_empty_call_grpc_asyncio(): - client = MemorystoreAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", +def test_delete_backup_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_backup( + name="name_value", ) - await client.update_instance(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = memorystore.UpdateInstanceRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_backup_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup( + memorystore.DeleteBackupRequest(), + name="name_value", + ) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_instance_empty_call_grpc_asyncio(): +async def test_delete_backup_flattened_async(): client = MemorystoreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - await client.delete_instance(request=None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_backup( + name="name_value", + ) - # Establish that the underlying stub method was called. - call.assert_called() + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request_msg = memorystore.DeleteInstanceRequest() - assert args[0] == request_msg + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_get_certificate_authority_empty_call_grpc_asyncio(): +async def test_delete_backup_flattened_error_async(): client = MemorystoreAsyncClient( credentials=async_anonymous_credentials(), - transport="grpc_asyncio", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - memorystore.CertificateAuthority( - name="name_value", - ) + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_backup( + memorystore.DeleteBackupRequest(), + name="name_value", ) - await client.get_certificate_authority(request=None) - # Establish that the underlying stub method was called. - call.assert_called() + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ExportBackupRequest(), + {}, + ], +) +def test_export_backup(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetCertificateAuthorityRequest() - assert args[0] == request_msg + request = memorystore.ExportBackupRequest() + assert args[0] == request + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) -# This test is a coverage failsafe to make sure that totally empty calls, -# i.e. request == None and no flattened fields passed, work. -@pytest.mark.asyncio -async def test_get_shared_regional_certificate_authority_empty_call_grpc_asyncio(): - client = MemorystoreAsyncClient( - credentials=async_anonymous_credentials(), - transport="grpc_asyncio", + +def test_export_backup_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # Mock the actual call, and fake the request. - with mock.patch.object( - type(client.transport.get_shared_regional_certificate_authority), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - memorystore.SharedRegionalCertificateAuthority( - name="name_value", - ) - ) - await client.get_shared_regional_certificate_authority(request=None) + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.ExportBackupRequest( + gcs_bucket="gcs_bucket_value", + name="name_value", + ) - # Establish that the underlying stub method was called. + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.export_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + request_msg = memorystore.ExportBackupRequest( + gcs_bucket="gcs_bucket_value", + name="name_value", + ) assert args[0] == request_msg -def test_transport_kind_rest(): - transport = MemorystoreClient.get_transport_class("rest")( - credentials=ga_credentials.AnonymousCredentials() - ) - assert transport.kind == "rest" +def test_export_backup_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.export_backup 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.export_backup] = mock_rpc + request = {} + client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_export_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.export_backup + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.export_backup + ] = mock_rpc + + request = {} + await client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.export_backup(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ExportBackupRequest(), + {}, + ], +) +async def test_export_backup_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.ExportBackupRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_export_backup_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ExportBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_export_backup_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ExportBackupRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.BackupInstanceRequest(), + {}, + ], +) +def test_backup_instance(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.BackupInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_backup_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.BackupInstanceRequest( + name="name_value", + backup_id="backup_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.backup_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.BackupInstanceRequest( + name="name_value", + backup_id="backup_id_value", + ) + assert args[0] == request_msg + + +def test_backup_instance_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.backup_instance 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.backup_instance] = mock_rpc + request = {} + client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.backup_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_backup_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.backup_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.backup_instance + ] = mock_rpc + + request = {} + await client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.backup_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.BackupInstanceRequest(), + {}, + ], +) +async def test_backup_instance_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.BackupInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_backup_instance_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.BackupInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_backup_instance_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.BackupInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_backup_instance_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.backup_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_backup_instance_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.backup_instance( + memorystore.BackupInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_backup_instance_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.backup_instance( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_backup_instance_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.backup_instance( + memorystore.BackupInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.StartMigrationRequest(), + {}, + ], +) +def test_start_migration(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.StartMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_migration_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.StartMigrationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.start_migration(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_start_migration_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.start_migration 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.start_migration] = mock_rpc + request = {} + client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.start_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_start_migration_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.start_migration + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.start_migration + ] = mock_rpc + + request = {} + await client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.start_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.StartMigrationRequest(), + {}, + ], +) +async def test_start_migration_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.StartMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_start_migration_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.StartMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_start_migration_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.StartMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.FinishMigrationRequest(), + {}, + ], +) +def test_finish_migration(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.FinishMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_finish_migration_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.FinishMigrationRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.finish_migration(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_finish_migration_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.finish_migration 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.finish_migration] = ( + mock_rpc + ) + request = {} + client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.finish_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_finish_migration_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.finish_migration + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.finish_migration + ] = mock_rpc + + request = {} + await client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.finish_migration(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.FinishMigrationRequest(), + {}, + ], +) +async def test_finish_migration_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.FinishMigrationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_finish_migration_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.FinishMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_finish_migration_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.FinishMigrationRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_finish_migration_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.finish_migration( + name="name_value", + force=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val + + +def test_finish_migration_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.finish_migration( + memorystore.FinishMigrationRequest(), + name="name_value", + force=True, + ) + + +@pytest.mark.asyncio +async def test_finish_migration_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.finish_migration( + name="name_value", + force=True, + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + arg = args[0].force + mock_val = True + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_finish_migration_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.finish_migration( + memorystore.FinishMigrationRequest(), + name="name_value", + force=True, + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListTokenAuthUsersRequest(), + {}, + ], +) +def test_list_token_auth_users(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListTokenAuthUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.ListTokenAuthUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTokenAuthUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_token_auth_users_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.ListTokenAuthUsersRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_token_auth_users(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListTokenAuthUsersRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_token_auth_users_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.list_token_auth_users + 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_token_auth_users] = ( + mock_rpc + ) + request = {} + client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_token_auth_users(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_token_auth_users_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_token_auth_users + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_token_auth_users + ] = mock_rpc + + request = {} + await client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_token_auth_users(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListTokenAuthUsersRequest(), + {}, + ], +) +async def test_list_token_auth_users_async( + request_type, transport: str = "grpc_asyncio" +): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListTokenAuthUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.ListTokenAuthUsersRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTokenAuthUsersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_token_auth_users_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListTokenAuthUsersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + call.return_value = memorystore.ListTokenAuthUsersResponse() + client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_token_auth_users_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListTokenAuthUsersRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListTokenAuthUsersResponse() + ) + await client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_token_auth_users_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListTokenAuthUsersResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_token_auth_users( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_token_auth_users_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_token_auth_users( + memorystore.ListTokenAuthUsersRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_token_auth_users_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListTokenAuthUsersResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListTokenAuthUsersResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_token_auth_users( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_token_auth_users_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_token_auth_users( + memorystore.ListTokenAuthUsersRequest(), + parent="parent_value", + ) + + +def test_list_token_auth_users_pager(transport_name: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + next_page_token="abc", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[], + next_page_token="def", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + ], + next_page_token="ghi", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_token_auth_users(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.TokenAuthUser) for i in results) + + +def test_list_token_auth_users_pages(transport_name: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + next_page_token="abc", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[], + next_page_token="def", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + ], + next_page_token="ghi", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + ), + RuntimeError, + ) + pages = list(client.list_token_auth_users(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_token_auth_users_async_pager(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + next_page_token="abc", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[], + next_page_token="def", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + ], + next_page_token="ghi", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_token_auth_users( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, memorystore.TokenAuthUser) for i in responses) + + +@pytest.mark.asyncio +async def test_list_token_auth_users_async_pages(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + next_page_token="abc", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[], + next_page_token="def", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + ], + next_page_token="ghi", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_token_auth_users(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetTokenAuthUserRequest(), + {}, + ], +) +def test_get_token_auth_user(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.TokenAuthUser( + name="name_value", + state=memorystore.TokenAuthUser.State.ACTIVE, + ) + response = client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.GetTokenAuthUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.TokenAuthUser) + assert response.name == "name_value" + assert response.state == memorystore.TokenAuthUser.State.ACTIVE + + +def test_get_token_auth_user_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.GetTokenAuthUserRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_token_auth_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetTokenAuthUserRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_token_auth_user_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.get_token_auth_user 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_token_auth_user] = ( + mock_rpc + ) + request = {} + client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_token_auth_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_token_auth_user_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_token_auth_user + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_token_auth_user + ] = mock_rpc + + request = {} + await client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_token_auth_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetTokenAuthUserRequest(), + {}, + ], +) +async def test_get_token_auth_user_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.TokenAuthUser( + name="name_value", + state=memorystore.TokenAuthUser.State.ACTIVE, + ) + ) + response = await client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.GetTokenAuthUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.TokenAuthUser) + assert response.name == "name_value" + assert response.state == memorystore.TokenAuthUser.State.ACTIVE + + +def test_get_token_auth_user_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetTokenAuthUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + call.return_value = memorystore.TokenAuthUser() + client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_token_auth_user_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetTokenAuthUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.TokenAuthUser() + ) + await client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_token_auth_user_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.TokenAuthUser() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_token_auth_user( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_token_auth_user_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_token_auth_user( + memorystore.GetTokenAuthUserRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_token_auth_user_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.TokenAuthUser() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.TokenAuthUser() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_token_auth_user( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_token_auth_user_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_token_auth_user( + memorystore.GetTokenAuthUserRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListAuthTokensRequest(), + {}, + ], +) +def test_list_auth_tokens(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListAuthTokensResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.ListAuthTokensRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthTokensPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auth_tokens_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.ListAuthTokensRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_auth_tokens(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListAuthTokensRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", + ) + assert args[0] == request_msg + + +def test_list_auth_tokens_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_auth_tokens 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_auth_tokens] = ( + mock_rpc + ) + request = {} + client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auth_tokens(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_auth_tokens_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_auth_tokens + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_auth_tokens + ] = mock_rpc + + request = {} + await client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_auth_tokens(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListAuthTokensRequest(), + {}, + ], +) +async def test_list_auth_tokens_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListAuthTokensResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.ListAuthTokensRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListAuthTokensAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_auth_tokens_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListAuthTokensRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + call.return_value = memorystore.ListAuthTokensResponse() + client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_auth_tokens_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.ListAuthTokensRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListAuthTokensResponse() + ) + await client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_auth_tokens_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListAuthTokensResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_auth_tokens( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_auth_tokens_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_auth_tokens( + memorystore.ListAuthTokensRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_auth_tokens_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.ListAuthTokensResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListAuthTokensResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_auth_tokens( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_auth_tokens_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_auth_tokens( + memorystore.ListAuthTokensRequest(), + parent="parent_value", + ) + + +def test_list_auth_tokens_pager(transport_name: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + next_page_token="abc", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[], + next_page_token="def", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + ], + next_page_token="ghi", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_auth_tokens(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.AuthToken) for i in results) + + +def test_list_auth_tokens_pages(transport_name: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + next_page_token="abc", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[], + next_page_token="def", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + ], + next_page_token="ghi", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + ), + RuntimeError, + ) + pages = list(client.list_auth_tokens(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_auth_tokens_async_pager(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auth_tokens), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + next_page_token="abc", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[], + next_page_token="def", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + ], + next_page_token="ghi", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_auth_tokens( + request={}, + ) + assert async_pager.next_page_token == "abc" + assert str(async_pager).startswith(f"{async_pager.__class__.__name__}<") + + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, memorystore.AuthToken) for i in responses) + + +@pytest.mark.asyncio +async def test_list_auth_tokens_async_pages(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_auth_tokens), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + next_page_token="abc", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[], + next_page_token="def", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + ], + next_page_token="ghi", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_auth_tokens(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetAuthTokenRequest(), + {}, + ], +) +def test_get_auth_token(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.AuthToken( + name="name_value", + token="token_value", + state=memorystore.AuthToken.State.ACTIVE, + ) + response = client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.GetAuthTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.AuthToken) + assert response.name == "name_value" + assert response.token == "token_value" + assert response.state == memorystore.AuthToken.State.ACTIVE + + +def test_get_auth_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.GetAuthTokenRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_auth_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetAuthTokenRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_get_auth_token_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_auth_token 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_auth_token] = mock_rpc + request = {} + client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auth_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_auth_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_auth_token + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_auth_token + ] = mock_rpc + + request = {} + await client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_auth_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetAuthTokenRequest(), + {}, + ], +) +async def test_get_auth_token_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.AuthToken( + name="name_value", + token="token_value", + state=memorystore.AuthToken.State.ACTIVE, + ) + ) + response = await client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.GetAuthTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.AuthToken) + assert response.name == "name_value" + assert response.token == "token_value" + assert response.state == memorystore.AuthToken.State.ACTIVE + + +def test_get_auth_token_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetAuthTokenRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + call.return_value = memorystore.AuthToken() + client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_auth_token_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.GetAuthTokenRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.AuthToken() + ) + await client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_auth_token_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.AuthToken() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_auth_token( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_auth_token_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_auth_token( + memorystore.GetAuthTokenRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_auth_token_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = memorystore.AuthToken() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.AuthToken() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_auth_token( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_get_auth_token_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_auth_token( + memorystore.GetAuthTokenRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.AddTokenAuthUserRequest(), + {}, + ], +) +def test_add_token_auth_user(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.AddTokenAuthUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_token_auth_user_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.AddTokenAuthUserRequest( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.add_token_auth_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddTokenAuthUserRequest( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + assert args[0] == request_msg + + +def test_add_token_auth_user_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.add_token_auth_user 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.add_token_auth_user] = ( + mock_rpc + ) + request = {} + client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_token_auth_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_add_token_auth_user_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.add_token_auth_user + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.add_token_auth_user + ] = mock_rpc + + request = {} + await client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.add_token_auth_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.AddTokenAuthUserRequest(), + {}, + ], +) +async def test_add_token_auth_user_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.AddTokenAuthUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_token_auth_user_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.AddTokenAuthUserRequest() + + request.instance = "instance_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "instance=instance_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_token_auth_user_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.AddTokenAuthUserRequest() + + request.instance = "instance_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "instance=instance_value", + ) in kw["metadata"] + + +def test_add_token_auth_user_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_token_auth_user( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].instance + mock_val = "instance_value" + assert arg == mock_val + arg = args[0].token_auth_user + mock_val = "token_auth_user_value" + assert arg == mock_val + + +def test_add_token_auth_user_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_token_auth_user( + memorystore.AddTokenAuthUserRequest(), + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + +@pytest.mark.asyncio +async def test_add_token_auth_user_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_token_auth_user( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].instance + mock_val = "instance_value" + assert arg == mock_val + arg = args[0].token_auth_user + mock_val = "token_auth_user_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_add_token_auth_user_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_token_auth_user( + memorystore.AddTokenAuthUserRequest(), + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteTokenAuthUserRequest(), + {}, + ], +) +def test_delete_token_auth_user(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.DeleteTokenAuthUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_token_auth_user_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.DeleteTokenAuthUserRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_token_auth_user(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteTokenAuthUserRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_token_auth_user_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.delete_token_auth_user + 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.delete_token_auth_user] = ( + mock_rpc + ) + request = {} + client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_token_auth_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_token_auth_user_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_token_auth_user + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_token_auth_user + ] = mock_rpc + + request = {} + await client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_token_auth_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteTokenAuthUserRequest(), + {}, + ], +) +async def test_delete_token_auth_user_async( + request_type, transport: str = "grpc_asyncio" +): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.DeleteTokenAuthUserRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_token_auth_user_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.DeleteTokenAuthUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_token_auth_user_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.DeleteTokenAuthUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_token_auth_user_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_token_auth_user( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_token_auth_user_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_token_auth_user( + memorystore.DeleteTokenAuthUserRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_token_auth_user_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_token_auth_user( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_token_auth_user_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_token_auth_user( + memorystore.DeleteTokenAuthUserRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.AddAuthTokenRequest(), + {}, + ], +) +def test_add_auth_token(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.AddAuthTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_auth_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.AddAuthTokenRequest( + token_auth_user="token_auth_user_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.add_auth_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddAuthTokenRequest( + token_auth_user="token_auth_user_value", + ) + assert args[0] == request_msg + + +def test_add_auth_token_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.add_auth_token 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.add_auth_token] = mock_rpc + request = {} + client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_auth_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_add_auth_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.add_auth_token + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.add_auth_token + ] = mock_rpc + + request = {} + await client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.add_auth_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.AddAuthTokenRequest(), + {}, + ], +) +async def test_add_auth_token_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.AddAuthTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_add_auth_token_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.AddAuthTokenRequest() + + request.token_auth_user = "token_auth_user_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "token_auth_user=token_auth_user_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_add_auth_token_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.AddAuthTokenRequest() + + request.token_auth_user = "token_auth_user_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "token_auth_user=token_auth_user_value", + ) in kw["metadata"] + + +def test_add_auth_token_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.add_auth_token( + token_auth_user="token_auth_user_value", + auth_token=memorystore.AuthToken(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].token_auth_user + mock_val = "token_auth_user_value" + assert arg == mock_val + arg = args[0].auth_token + mock_val = memorystore.AuthToken(name="name_value") + assert arg == mock_val + + +def test_add_auth_token_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.add_auth_token( + memorystore.AddAuthTokenRequest(), + token_auth_user="token_auth_user_value", + auth_token=memorystore.AuthToken(name="name_value"), + ) + + +@pytest.mark.asyncio +async def test_add_auth_token_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.add_auth_token( + token_auth_user="token_auth_user_value", + auth_token=memorystore.AuthToken(name="name_value"), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].token_auth_user + mock_val = "token_auth_user_value" + assert arg == mock_val + arg = args[0].auth_token + mock_val = memorystore.AuthToken(name="name_value") + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_add_auth_token_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.add_auth_token( + memorystore.AddAuthTokenRequest(), + token_auth_user="token_auth_user_value", + auth_token=memorystore.AuthToken(name="name_value"), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteAuthTokenRequest(), + {}, + ], +) +def test_delete_auth_token(request_type, transport: str = "grpc"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = memorystore.DeleteAuthTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_auth_token_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = memorystore.DeleteAuthTokenRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.delete_auth_token(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteAuthTokenRequest( + name="name_value", + ) + assert args[0] == request_msg + + +def test_delete_auth_token_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_auth_token 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.delete_auth_token] = ( + mock_rpc + ) + request = {} + client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_auth_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_delete_auth_token_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.delete_auth_token + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.delete_auth_token + ] = mock_rpc + + request = {} + await client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.delete_auth_token(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteAuthTokenRequest(), + {}, + ], +) +async def test_delete_auth_token_async(request_type, transport: str = "grpc_asyncio"): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = memorystore.DeleteAuthTokenRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_auth_token_field_headers(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.DeleteAuthTokenRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_auth_token_field_headers_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = memorystore.DeleteAuthTokenRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_auth_token_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_auth_token( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_auth_token_flattened_error(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_auth_token( + memorystore.DeleteAuthTokenRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_auth_token_flattened_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_auth_token( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_auth_token_flattened_error_async(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_auth_token( + memorystore.DeleteAuthTokenRequest(), + name="name_value", + ) + + +def test_list_instances_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 = MemorystoreClient( + 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_instances 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_instances] = mock_rpc + + request = {} + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_instances(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_instances_rest_required_fields( + request_type=memorystore.ListInstancesRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_instances._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.ListInstancesResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.ListInstancesResponse.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_instances(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_instances_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_instances._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_instances_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.ListInstancesResponse.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_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/instances" + % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_instances( + memorystore.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = MemorystoreClient( + 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 = ( + memorystore.ListInstancesResponse( + instances=[ + memorystore.Instance(), + memorystore.Instance(), + memorystore.Instance(), + ], + next_page_token="abc", + ), + memorystore.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + memorystore.ListInstancesResponse( + instances=[ + memorystore.Instance(), + ], + next_page_token="ghi", + ), + memorystore.ListInstancesResponse( + instances=[ + memorystore.Instance(), + memorystore.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(memorystore.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_instances(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_instance_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 = MemorystoreClient( + 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_instance 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_instance] = mock_rpc + + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(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_instance_rest_required_fields(request_type=memorystore.GetInstanceRequest): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.Instance() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = memorystore.Instance.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_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_instance_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.Instance() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.Instance.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_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_get_instance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_instance( + memorystore.GetInstanceRequest(), + name="name_value", + ) + + +def test_create_instance_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_create_instance_rest_required_fields( + request_type=memorystore.CreateInstanceRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["instance_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + assert "instanceId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "instance_id", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.create_instance(request) + + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_create_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.create_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "requestId", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) + + +def test_create_instance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + instance_id="instance_id_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.create_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{parent=projects/*/locations/*}/instances" + % client.transport._host, + args[1], + ) + + +def test_create_instance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_instance( + memorystore.CreateInstanceRequest(), + parent="parent_value", + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + instance_id="instance_id_value", + ) + + +def test_update_instance_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 = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.update_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc + + request = {} + client.update_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.update_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_update_instance_rest_required_fields( + request_type=memorystore.UpdateInstanceRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + 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() + ).update_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).update_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "request_id", + "update_mask", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.update_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_update_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "requestId", + "updateMask", + ) + ) + & set(("instance",)) + ) + + +def test_update_instance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.update_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{instance.name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_update_instance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_instance( + memorystore.UpdateInstanceRequest(), + instance=memorystore.Instance( + gcs_source=memorystore.Instance.GcsBackupSource(uris=["uris_value"]) + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_instance_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 = MemorystoreClient( + 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.delete_instance 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.delete_instance] = mock_rpc + + request = {} + client.delete_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_instance(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_delete_instance_rest_required_fields( + request_type=memorystore.DeleteInstanceRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_instance._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_instance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.delete_instance( + memorystore.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_get_certificate_authority_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 = MemorystoreClient( + 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_certificate_authority + 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_certificate_authority + ] = mock_rpc + + request = {} + client.get_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_certificate_authority(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_certificate_authority_rest_required_fields( + request_type=memorystore.GetCertificateAuthorityRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_certificate_authority._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.CertificateAuthority() + # 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 = memorystore.CertificateAuthority.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_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_certificate_authority_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_certificate_authority._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_certificate_authority_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.CertificateAuthority() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.CertificateAuthority.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_certificate_authority(**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/v1beta/{name=projects/*/locations/*/instances/*}/certificateAuthority" + % client.transport._host, + args[1], + ) + + +def test_get_certificate_authority_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_certificate_authority( + memorystore.GetCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_get_shared_regional_certificate_authority_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 = MemorystoreClient( + 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_shared_regional_certificate_authority + 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_shared_regional_certificate_authority + ] = mock_rpc + + request = {} + client.get_shared_regional_certificate_authority(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_shared_regional_certificate_authority(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_shared_regional_certificate_authority_rest_required_fields( + request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_shared_regional_certificate_authority._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_shared_regional_certificate_authority._get_unset_required_fields( + jsonified_request + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.SharedRegionalCertificateAuthority() + # 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 = memorystore.SharedRegionalCertificateAuthority.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_shared_regional_certificate_authority(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_shared_regional_certificate_authority_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = ( + transport.get_shared_regional_certificate_authority._get_unset_required_fields( + {} + ) + ) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_shared_regional_certificate_authority_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.SharedRegionalCertificateAuthority() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.SharedRegionalCertificateAuthority.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_shared_regional_certificate_authority(**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/v1beta/{name=projects/*/locations/*/sharedRegionalCertificateAuthority}" + % client.transport._host, + args[1], + ) + + +def test_get_shared_regional_certificate_authority_rest_flattened_error( + transport: str = "rest", +): + client = MemorystoreClient( + 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_shared_regional_certificate_authority( + memorystore.GetSharedRegionalCertificateAuthorityRequest(), + name="name_value", + ) + + +def test_reschedule_maintenance_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 = MemorystoreClient( + 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.reschedule_maintenance + 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.reschedule_maintenance] = ( + mock_rpc + ) + + request = {} + client.reschedule_maintenance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.reschedule_maintenance(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_reschedule_maintenance_rest_required_fields( + request_type=memorystore.RescheduleMaintenanceRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reschedule_maintenance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).reschedule_maintenance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.reschedule_maintenance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_reschedule_maintenance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.reschedule_maintenance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "name", + "rescheduleType", + ) + ) + ) + + +def test_reschedule_maintenance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.reschedule_maintenance(**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/v1beta/{name=projects/*/locations/*/instances/*}:rescheduleMaintenance" + % client.transport._host, + args[1], + ) + + +def test_reschedule_maintenance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.reschedule_maintenance( + memorystore.RescheduleMaintenanceRequest(), + name="name_value", + reschedule_type=memorystore.RescheduleMaintenanceRequest.RescheduleType.IMMEDIATE, + schedule_time=timestamp_pb2.Timestamp(seconds=751), + ) + + +def test_list_backup_collections_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 = MemorystoreClient( + 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_backup_collections + 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_backup_collections + ] = mock_rpc + + request = {} + client.list_backup_collections(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backup_collections(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_backup_collections_rest_required_fields( + request_type=memorystore.ListBackupCollectionsRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_backup_collections._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_backup_collections._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.ListBackupCollectionsResponse() + # 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 = memorystore.ListBackupCollectionsResponse.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_backup_collections(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backup_collections_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_backup_collections._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_backup_collections_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.ListBackupCollectionsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.ListBackupCollectionsResponse.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_backup_collections(**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/v1beta/{parent=projects/*/locations/*}/backupCollections" + % client.transport._host, + args[1], + ) + + +def test_list_backup_collections_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_backup_collections( + memorystore.ListBackupCollectionsRequest(), + parent="parent_value", + ) + + +def test_list_backup_collections_rest_pager(transport: str = "rest"): + client = MemorystoreClient( + 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 = ( + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + next_page_token="abc", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[], + next_page_token="def", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupCollectionsResponse( + backup_collections=[ + memorystore.BackupCollection(), + memorystore.BackupCollection(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + memorystore.ListBackupCollectionsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_backup_collections(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.BackupCollection) for i in results) + + pages = list(client.list_backup_collections(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_backup_collection_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 = MemorystoreClient( + 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_backup_collection + 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_backup_collection] = ( + mock_rpc + ) + + request = {} + client.get_backup_collection(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup_collection(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_backup_collection_rest_required_fields( + request_type=memorystore.GetBackupCollectionRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_backup_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_backup_collection._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.BackupCollection() + # 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 = memorystore.BackupCollection.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_backup_collection(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_collection_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_backup_collection._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_backup_collection_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.BackupCollection() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.BackupCollection.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_backup_collection(**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/v1beta/{name=projects/*/locations/*/backupCollections/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_collection_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_backup_collection( + memorystore.GetBackupCollectionRequest(), + name="name_value", + ) + + +def test_list_backups_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 = MemorystoreClient( + 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_backups 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_backups] = mock_rpc + + request = {} + client.list_backups(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_backups(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_backups_rest_required_fields(request_type=memorystore.ListBackupsRequest): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_backups._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_backups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.ListBackupsResponse() + # 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 = memorystore.ListBackupsResponse.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_backups(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_backups_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_backups._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_backups_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.ListBackupsResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.ListBackupsResponse.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_backups(**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/v1beta/{parent=projects/*/locations/*/backupCollections/*}/backups" + % client.transport._host, + args[1], + ) + + +def test_list_backups_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_backups( + memorystore.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_rest_pager(transport: str = "rest"): + client = MemorystoreClient( + 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 = ( + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + memorystore.Backup(), + ], + next_page_token="abc", + ), + memorystore.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + ], + next_page_token="ghi", + ), + memorystore.ListBackupsResponse( + backups=[ + memorystore.Backup(), + memorystore.Backup(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(memorystore.ListBackupsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/backupCollections/sample3" + } + + pager = client.list_backups(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.Backup) for i in results) + + pages = list(client.list_backups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_backup_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 = MemorystoreClient( + 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_backup 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_backup] = mock_rpc + + request = {} + client.get_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_backup(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_backup_rest_required_fields(request_type=memorystore.GetBackupRequest): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.Backup() + # 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 = memorystore.Backup.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_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_backup_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_backup_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.Backup() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.Backup.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_backup(**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/v1beta/{name=projects/*/locations/*/backupCollections/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_get_backup_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_backup( + memorystore.GetBackupRequest(), + name="name_value", + ) + + +def test_delete_backup_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 = MemorystoreClient( + 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.delete_backup 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.delete_backup] = mock_rpc + + request = {} + client.delete_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_backup(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_delete_backup_rest_required_fields( + request_type=memorystore.DeleteBackupRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("request_id",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_backup_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("name",))) + + +def test_delete_backup_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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.delete_backup(**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/v1beta/{name=projects/*/locations/*/backupCollections/*/backups/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_backup_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.delete_backup( + memorystore.DeleteBackupRequest(), + name="name_value", + ) + + +def test_export_backup_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 = MemorystoreClient( + 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.export_backup 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.export_backup] = mock_rpc + + request = {} + client.export_backup(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.export_backup(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_export_backup_rest_required_fields( + request_type=memorystore.ExportBackupRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).export_backup._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.export_backup(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_export_backup_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.export_backup._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_backup_instance_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 = MemorystoreClient( + 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.backup_instance 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.backup_instance] = mock_rpc + + request = {} + client.backup_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.backup_instance(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_backup_instance_rest_required_fields( + request_type=memorystore.BackupInstanceRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).backup_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).backup_instance._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.backup_instance(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_backup_instance_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.backup_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_backup_instance_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.backup_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1beta/{name=projects/*/locations/*/instances/*}:backup" + % client.transport._host, + args[1], + ) + + +def test_backup_instance_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.backup_instance( + memorystore.BackupInstanceRequest(), + name="name_value", + ) + + +def test_start_migration_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 = MemorystoreClient( + 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.start_migration 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.start_migration] = mock_rpc + + request = {} + client.start_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.start_migration(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_start_migration_rest_required_fields( + request_type=memorystore.StartMigrationRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).start_migration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).start_migration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.start_migration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_start_migration_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.start_migration._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "selfManagedSource", + "name", + ) + ) + ) + + +def test_finish_migration_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 = MemorystoreClient( + 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.finish_migration 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.finish_migration] = ( + mock_rpc + ) + + request = {} + client.finish_migration(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.finish_migration(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_finish_migration_rest_required_fields( + request_type=memorystore.FinishMigrationRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).finish_migration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).finish_migration._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.finish_migration(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_finish_migration_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.finish_migration._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_finish_migration_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + force=True, + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.finish_migration(**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/v1beta/{name=projects/*/locations/*/instances/*}:finishMigration" + % client.transport._host, + args[1], + ) + + +def test_finish_migration_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.finish_migration( + memorystore.FinishMigrationRequest(), + name="name_value", + force=True, + ) + + +def test_list_token_auth_users_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 = MemorystoreClient( + 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_token_auth_users + 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_token_auth_users] = ( + mock_rpc + ) + + request = {} + client.list_token_auth_users(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_token_auth_users(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_token_auth_users_rest_required_fields( + request_type=memorystore.ListTokenAuthUsersRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_token_auth_users._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_token_auth_users._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.ListTokenAuthUsersResponse() + # 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 = memorystore.ListTokenAuthUsersResponse.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_token_auth_users(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_token_auth_users_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_token_auth_users._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_token_auth_users_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.ListTokenAuthUsersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.ListTokenAuthUsersResponse.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_token_auth_users(**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/v1beta/{parent=projects/*/locations/*/instances/*}/tokenAuthUsers" + % client.transport._host, + args[1], + ) + + +def test_list_token_auth_users_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_token_auth_users( + memorystore.ListTokenAuthUsersRequest(), + parent="parent_value", + ) + + +def test_list_token_auth_users_rest_pager(transport: str = "rest"): + client = MemorystoreClient( + 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 = ( + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + next_page_token="abc", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[], + next_page_token="def", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + ], + next_page_token="ghi", + ), + memorystore.ListTokenAuthUsersResponse( + token_auth_users=[ + memorystore.TokenAuthUser(), + memorystore.TokenAuthUser(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + memorystore.ListTokenAuthUsersResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3" + } + + pager = client.list_token_auth_users(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.TokenAuthUser) for i in results) + + pages = list(client.list_token_auth_users(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_token_auth_user_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 = MemorystoreClient( + 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_token_auth_user 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_token_auth_user] = ( + mock_rpc + ) + + request = {} + client.get_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_token_auth_user(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_token_auth_user_rest_required_fields( + request_type=memorystore.GetTokenAuthUserRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_token_auth_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_token_auth_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.TokenAuthUser() + # 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 = memorystore.TokenAuthUser.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_token_auth_user(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_token_auth_user_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_token_auth_user._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_token_auth_user_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.TokenAuthUser() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.TokenAuthUser.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_token_auth_user(**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/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*}" + % client.transport._host, + args[1], + ) + + +def test_get_token_auth_user_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_token_auth_user( + memorystore.GetTokenAuthUserRequest(), + name="name_value", + ) + + +def test_list_auth_tokens_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 = MemorystoreClient( + 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_auth_tokens 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_auth_tokens] = ( + mock_rpc + ) + + request = {} + client.list_auth_tokens(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.list_auth_tokens(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_auth_tokens_rest_required_fields( + request_type=memorystore.ListAuthTokensRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_auth_tokens._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_auth_tokens._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.ListAuthTokensResponse() + # 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 = memorystore.ListAuthTokensResponse.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_auth_tokens(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_list_auth_tokens_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_auth_tokens._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +def test_list_auth_tokens_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.ListAuthTokensResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.ListAuthTokensResponse.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_auth_tokens(**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/v1beta/{parent=projects/*/locations/*/instances/*/tokenAuthUsers/*}/authTokens" + % client.transport._host, + args[1], + ) + + +def test_list_auth_tokens_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_auth_tokens( + memorystore.ListAuthTokensRequest(), + parent="parent_value", + ) + + +def test_list_auth_tokens_rest_pager(transport: str = "rest"): + client = MemorystoreClient( + 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 = ( + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + next_page_token="abc", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[], + next_page_token="def", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + ], + next_page_token="ghi", + ), + memorystore.ListAuthTokensResponse( + auth_tokens=[ + memorystore.AuthToken(), + memorystore.AuthToken(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + memorystore.ListAuthTokensResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } + + pager = client.list_auth_tokens(request=sample_request) + + assert pager.next_page_token == "abc" + assert str(pager).startswith(f"{pager.__class__.__name__}<") + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, memorystore.AuthToken) for i in results) + + pages = list(client.list_auth_tokens(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_auth_token_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 = MemorystoreClient( + 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_auth_token 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_auth_token] = mock_rpc + + request = {} + client.get_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_auth_token(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_auth_token_rest_required_fields( + request_type=memorystore.GetAuthTokenRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_auth_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_auth_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = memorystore.AuthToken() + # 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 = memorystore.AuthToken.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_auth_token(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_auth_token_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_auth_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_get_auth_token_rest_flattened(): + client = MemorystoreClient( + 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 = memorystore.AuthToken() + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4/authTokens/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = memorystore.AuthToken.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_auth_token(**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/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*/authTokens/*}" + % client.transport._host, + args[1], + ) + + +def test_get_auth_token_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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_auth_token( + memorystore.GetAuthTokenRequest(), + name="name_value", + ) + + +def test_add_token_auth_user_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 = MemorystoreClient( + 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.add_token_auth_user 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.add_token_auth_user] = ( + mock_rpc + ) + + request = {} + client.add_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_token_auth_user(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_add_token_auth_user_rest_required_fields( + request_type=memorystore.AddTokenAuthUserRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["instance"] = "" + request_init["token_auth_user"] = "" + 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() + ).add_token_auth_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["instance"] = "instance_value" + jsonified_request["tokenAuthUser"] = "token_auth_user_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_token_auth_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "tokenAuthUser" in jsonified_request + assert jsonified_request["tokenAuthUser"] == "token_auth_user_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.add_token_auth_user(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_add_token_auth_user_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_token_auth_user._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instance", + "tokenAuthUser", + ) + ) + ) + + +def test_add_token_auth_user_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "instance": "projects/sample1/locations/sample2/instances/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.add_token_auth_user(**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/v1beta/{instance=projects/*/locations/*/instances/*}:addTokenAuthUser" + % client.transport._host, + args[1], + ) + + +def test_add_token_auth_user_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.add_token_auth_user( + memorystore.AddTokenAuthUserRequest(), + instance="instance_value", + token_auth_user="token_auth_user_value", + ) + + +def test_delete_token_auth_user_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 = MemorystoreClient( + 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.delete_token_auth_user + 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.delete_token_auth_user] = ( + mock_rpc + ) + + request = {} + client.delete_token_auth_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_token_auth_user(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_delete_token_auth_user_rest_required_fields( + request_type=memorystore.DeleteTokenAuthUserRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_token_auth_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_token_auth_user._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "force", + "request_id", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_token_auth_user(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_token_auth_user_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_token_auth_user._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "force", + "requestId", + ) + ) + & set(("name",)) + ) + + +def test_delete_token_auth_user_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + 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.delete_token_auth_user(**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/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_token_auth_user_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.delete_token_auth_user( + memorystore.DeleteTokenAuthUserRequest(), + name="name_value", + ) + + +def test_add_auth_token_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 = MemorystoreClient( + 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.add_auth_token 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.add_auth_token] = mock_rpc + + request = {} + client.add_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.add_auth_token(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_add_auth_token_rest_required_fields( + request_type=memorystore.AddAuthTokenRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["token_auth_user"] = "" + 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() + ).add_auth_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["tokenAuthUser"] = "token_auth_user_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).add_auth_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "tokenAuthUser" in jsonified_request + assert jsonified_request["tokenAuthUser"] == "token_auth_user_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.add_auth_token(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_add_auth_token_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.add_auth_token._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "tokenAuthUser", + "authToken", + ) + ) + ) + + +def test_add_auth_token_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "token_auth_user": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + token_auth_user="token_auth_user_value", + auth_token=memorystore.AuthToken(name="name_value"), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.add_auth_token(**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/v1beta/{token_auth_user=projects/*/locations/*/instances/*/tokenAuthUsers/*}:addAuthToken" + % client.transport._host, + args[1], + ) + + +def test_add_auth_token_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.add_auth_token( + memorystore.AddAuthTokenRequest(), + token_auth_user="token_auth_user_value", + auth_token=memorystore.AuthToken(name="name_value"), + ) + + +def test_delete_auth_token_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 = MemorystoreClient( + 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.delete_auth_token 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.delete_auth_token] = ( + mock_rpc + ) + + request = {} + client.delete_auth_token(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.delete_auth_token(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_delete_auth_token_rest_required_fields( + request_type=memorystore.DeleteAuthTokenRequest, +): + transport_class = transports.MemorystoreRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_auth_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_auth_token._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.delete_auth_token(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_delete_auth_token_rest_unset_required_fields(): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_auth_token._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_delete_auth_token_rest_flattened(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4/authTokens/sample5" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + client.delete_auth_token(**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/v1beta/{name=projects/*/locations/*/instances/*/tokenAuthUsers/*/authTokens/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_auth_token_rest_flattened_error(transport: str = "rest"): + client = MemorystoreClient( + 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.delete_auth_token( + memorystore.DeleteAuthTokenRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.MemorystoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.MemorystoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MemorystoreClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.MemorystoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = MemorystoreClient( + 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 = MemorystoreClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.MemorystoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = MemorystoreClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.MemorystoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = MemorystoreClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.MemorystoreGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.MemorystoreGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.MemorystoreGrpcTransport, + transports.MemorystoreGrpcAsyncIOTransport, + transports.MemorystoreRestTransport, + ], +) +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_grpc(): + transport = MemorystoreClient.get_transport_class("grpc")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "grpc" + + +def test_initialize_client_w_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="grpc" + ) + 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_list_instances_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = memorystore.ListInstancesResponse() + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListInstancesRequest() + 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_get_instance_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = memorystore.Instance() + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetInstanceRequest() + 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_create_instance_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.CreateInstanceRequest() + 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_update_instance_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.UpdateInstanceRequest() + 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_delete_instance_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteInstanceRequest() + 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_get_certificate_authority_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + call.return_value = memorystore.CertificateAuthority() + client.get_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetCertificateAuthorityRequest() + 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_get_shared_regional_certificate_authority_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shared_regional_certificate_authority), "__call__" + ) as call: + call.return_value = memorystore.SharedRegionalCertificateAuthority() + client.get_shared_regional_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + 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_reschedule_maintenance_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.RescheduleMaintenanceRequest() + 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_backup_collections_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + call.return_value = memorystore.ListBackupCollectionsResponse() + client.list_backup_collections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupCollectionsRequest() + 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_get_backup_collection_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + call.return_value = memorystore.BackupCollection() + client.get_backup_collection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupCollectionRequest() + 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_backups_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = memorystore.ListBackupsResponse() + client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupsRequest() + 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_get_backup_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = memorystore.Backup() + client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupRequest() + 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_delete_backup_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteBackupRequest() + 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_export_backup_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.export_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ExportBackupRequest() + 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_backup_instance_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.backup_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.BackupInstanceRequest() + 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_start_migration_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.start_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest() + 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_finish_migration_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.finish_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest() + 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_token_auth_users_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + call.return_value = memorystore.ListTokenAuthUsersResponse() + client.list_token_auth_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListTokenAuthUsersRequest() + 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_get_token_auth_user_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + call.return_value = memorystore.TokenAuthUser() + client.get_token_auth_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetTokenAuthUserRequest() + 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_auth_tokens_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + call.return_value = memorystore.ListAuthTokensResponse() + client.list_auth_tokens(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListAuthTokensRequest() + 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_get_auth_token_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + call.return_value = memorystore.AuthToken() + client.get_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetAuthTokenRequest() + 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_add_token_auth_user_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_token_auth_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddTokenAuthUserRequest() + 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_delete_token_auth_user_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_token_auth_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteTokenAuthUserRequest() + 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_add_auth_token_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.add_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddAuthTokenRequest() + 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_delete_auth_token_empty_call_grpc(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteAuthTokenRequest() + assert args[0] == request_msg + + +def test_transport_kind_grpc_asyncio(): + transport = MemorystoreAsyncClient.get_transport_class("grpc_asyncio")( + credentials=async_anonymous_credentials() + ) + assert transport.kind == "grpc_asyncio" + + +def test_initialize_client_w_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), transport="grpc_asyncio" + ) + 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. +@pytest.mark.asyncio +async def test_list_instances_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListInstancesRequest() + 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. +@pytest.mark.asyncio +async def test_get_instance_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.Instance( + name="name_value", + state=memorystore.Instance.State.CREATING, + uid="uid_value", + replica_count=1384, + authorization_mode=memorystore.Instance.AuthorizationMode.AUTH_DISABLED, + transit_encryption_mode=memorystore.Instance.TransitEncryptionMode.TRANSIT_ENCRYPTION_DISABLED, + shard_count=1178, + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + engine_version="engine_version_value", + deletion_protection_enabled=True, + mode=memorystore.Instance.Mode.STANDALONE, + simulate_maintenance_event=True, + ondemand_maintenance=True, + satisfies_pzs=True, + satisfies_pzi=True, + async_instance_endpoints_deletion_enabled=True, + kms_key="kms_key_value", + backup_collection="backup_collection_value", + maintenance_version="maintenance_version_value", + effective_maintenance_version="effective_maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + allow_fewer_zones_deployment=True, + server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, + server_ca_pool="server_ca_pool_value", + rotate_server_certificate=True, + ) + ) + await client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetInstanceRequest() + 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. +@pytest.mark.asyncio +async def test_create_instance_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.CreateInstanceRequest() + 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. +@pytest.mark.asyncio +async def test_update_instance_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.UpdateInstanceRequest() + 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. +@pytest.mark.asyncio +async def test_delete_instance_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteInstanceRequest() + 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. +@pytest.mark.asyncio +async def test_get_certificate_authority_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.CertificateAuthority( + name="name_value", + ) + ) + await client.get_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetCertificateAuthorityRequest() + 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. +@pytest.mark.asyncio +async def test_get_shared_regional_certificate_authority_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shared_regional_certificate_authority), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.SharedRegionalCertificateAuthority( + name="name_value", + ) + ) + await client.get_shared_regional_certificate_authority(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + 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. +@pytest.mark.asyncio +async def test_reschedule_maintenance_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.reschedule_maintenance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.RescheduleMaintenanceRequest() + 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. +@pytest.mark.asyncio +async def test_list_backup_collections_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupCollectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backup_collections(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupCollectionsRequest() + 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. +@pytest.mark.asyncio +async def test_get_backup_collection_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.BackupCollection( + name="name_value", + instance_uid="instance_uid_value", + instance="instance_value", + kms_key="kms_key_value", + uid="uid_value", + total_backup_size_bytes=2457, + total_backup_count=1921, + ) + ) + await client.get_backup_collection(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupCollectionRequest() + 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. +@pytest.mark.asyncio +async def test_list_backups_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_backups(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupsRequest() + 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. +@pytest.mark.asyncio +async def test_get_backup_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.Backup( + name="name_value", + instance="instance_value", + instance_uid="instance_uid_value", + total_size_bytes=1732, + engine_version="engine_version_value", + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + replica_count=1384, + shard_count=1178, + backup_type=memorystore.Backup.BackupType.ON_DEMAND, + state=memorystore.Backup.State.CREATING, + uid="uid_value", + ) + ) + await client.get_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupRequest() + 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. +@pytest.mark.asyncio +async def test_delete_backup_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteBackupRequest() + 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. +@pytest.mark.asyncio +async def test_export_backup_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.export_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ExportBackupRequest() + 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. +@pytest.mark.asyncio +async def test_backup_instance_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.backup_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.BackupInstanceRequest() + 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. +@pytest.mark.asyncio +async def test_start_migration_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.start_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest() + 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. +@pytest.mark.asyncio +async def test_finish_migration_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.finish_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest() + 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. +@pytest.mark.asyncio +async def test_list_token_auth_users_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListTokenAuthUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_token_auth_users(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListTokenAuthUsersRequest() + 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. +@pytest.mark.asyncio +async def test_get_token_auth_user_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.TokenAuthUser( + name="name_value", + state=memorystore.TokenAuthUser.State.ACTIVE, + ) + ) + await client.get_token_auth_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetTokenAuthUserRequest() + 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. +@pytest.mark.asyncio +async def test_list_auth_tokens_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.ListAuthTokensResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + await client.list_auth_tokens(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListAuthTokensRequest() + 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. +@pytest.mark.asyncio +async def test_get_auth_token_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + memorystore.AuthToken( + name="name_value", + token="token_value", + state=memorystore.AuthToken.State.ACTIVE, + ) + ) + await client.get_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetAuthTokenRequest() + 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. +@pytest.mark.asyncio +async def test_add_token_auth_user_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_token_auth_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddTokenAuthUserRequest() + 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. +@pytest.mark.asyncio +async def test_delete_token_auth_user_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_token_auth_user), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_token_auth_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteTokenAuthUserRequest() + 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. +@pytest.mark.asyncio +async def test_add_auth_token_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.add_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddAuthTokenRequest() + 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. +@pytest.mark.asyncio +async def test_delete_auth_token_empty_call_grpc_asyncio(): + client = MemorystoreAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.delete_auth_token), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.delete_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteAuthTokenRequest() + assert args[0] == request_msg + + +def test_transport_kind_rest(): + transport = MemorystoreClient.get_transport_class("rest")( + credentials=ga_credentials.AnonymousCredentials() + ) + assert transport.kind == "rest" + + +def test_list_instances_rest_bad_request(request_type=memorystore.ListInstancesRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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_instances(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListInstancesRequest, + dict, + ], +) +def test_list_instances_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = memorystore.ListInstancesResponse.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_instances(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_instances_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_list_instances" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_list_instances_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_list_instances" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.ListInstancesRequest.pb( + memorystore.ListInstancesRequest() + ) + 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 = memorystore.ListInstancesResponse.to_json( + memorystore.ListInstancesResponse() + ) + req.return_value.content = return_value + + request = memorystore.ListInstancesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.ListInstancesResponse() + post_with_metadata.return_value = memorystore.ListInstancesResponse(), metadata + + client.list_instances( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_instance_rest_bad_request(request_type=memorystore.GetInstanceRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetInstanceRequest, + dict, + ], +) +def test_get_instance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.Instance( + name="name_value", + state=memorystore.Instance.State.CREATING, + uid="uid_value", + replica_count=1384, + authorization_mode=memorystore.Instance.AuthorizationMode.AUTH_DISABLED, + transit_encryption_mode=memorystore.Instance.TransitEncryptionMode.TRANSIT_ENCRYPTION_DISABLED, + shard_count=1178, + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + engine_version="engine_version_value", + deletion_protection_enabled=True, + mode=memorystore.Instance.Mode.STANDALONE, + simulate_maintenance_event=True, + ondemand_maintenance=True, + satisfies_pzs=True, + satisfies_pzi=True, + async_instance_endpoints_deletion_enabled=True, + kms_key="kms_key_value", + backup_collection="backup_collection_value", + maintenance_version="maintenance_version_value", + effective_maintenance_version="effective_maintenance_version_value", + available_maintenance_versions=["available_maintenance_versions_value"], + allow_fewer_zones_deployment=True, + server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, + server_ca_pool="server_ca_pool_value", + rotate_server_certificate=True, + ) + + # 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 = memorystore.Instance.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_instance(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.Instance) + assert response.name == "name_value" + assert response.state == memorystore.Instance.State.CREATING + assert response.uid == "uid_value" + assert response.replica_count == 1384 + assert ( + response.authorization_mode + == memorystore.Instance.AuthorizationMode.AUTH_DISABLED + ) + assert ( + response.transit_encryption_mode + == memorystore.Instance.TransitEncryptionMode.TRANSIT_ENCRYPTION_DISABLED + ) + assert response.shard_count == 1178 + assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO + assert response.engine_version == "engine_version_value" + assert response.deletion_protection_enabled is True + assert response.mode == memorystore.Instance.Mode.STANDALONE + assert response.simulate_maintenance_event is True + assert response.ondemand_maintenance is True + assert response.satisfies_pzs is True + assert response.satisfies_pzi is True + assert response.async_instance_endpoints_deletion_enabled is True + assert response.kms_key == "kms_key_value" + assert response.backup_collection == "backup_collection_value" + assert response.maintenance_version == "maintenance_version_value" + assert ( + response.effective_maintenance_version == "effective_maintenance_version_value" + ) + assert response.available_maintenance_versions == [ + "available_maintenance_versions_value" + ] + assert response.allow_fewer_zones_deployment is True + assert ( + response.server_ca_mode + == memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA + ) + assert response.server_ca_pool == "server_ca_pool_value" + assert response.rotate_server_certificate is True + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_instance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_get_instance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_get_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_get_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetInstanceRequest.pb(memorystore.GetInstanceRequest()) + 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 = memorystore.Instance.to_json(memorystore.Instance()) + req.return_value.content = return_value + + request = memorystore.GetInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.Instance() + post_with_metadata.return_value = memorystore.Instance(), metadata + + client.get_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_create_instance_rest_bad_request( + request_type=memorystore.CreateInstanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.create_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.CreateInstanceRequest, + dict, + ], +) +def test_create_instance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["instance"] = { + "gcs_source": {"uris": ["uris_value1", "uris_value2"]}, + "managed_backup_source": {"backup": "backup_value"}, + "name": "name_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "state_info": { + "update_info": { + "target_shard_count": 1920, + "target_replica_count": 2126, + "target_engine_version": "target_engine_version_value", + "target_node_type": 1, + } + }, + "uid": "uid_value", + "replica_count": 1384, + "authorization_mode": 1, + "transit_encryption_mode": 1, + "shard_count": 1178, + "discovery_endpoints": [ + {"address": "address_value", "port": 453, "network": "network_value"} + ], + "node_type": 1, + "persistence_config": { + "mode": 1, + "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, + "aof_config": {"append_fsync": 1}, + }, + "engine_version": "engine_version_value", + "engine_configs": {}, + "node_config": {"size_gb": 0.739}, + "zone_distribution_config": {"zone": "zone_value", "mode": 1}, + "deletion_protection_enabled": True, + "psc_auto_connections": [ + { + "port": 453, + "psc_connection_id": "psc_connection_id_value", + "ip_address": "ip_address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + "service_attachment": "service_attachment_value", + "psc_connection_status": 1, + "connection_type": 1, + } + ], + "psc_attachment_details": [ + {"service_attachment": "service_attachment_value", "connection_type": 1} + ], + "endpoints": [ + { + "connections": [ + { + "psc_auto_connection": {}, + "psc_connection": { + "port": 453, + "psc_connection_id": "psc_connection_id_value", + "ip_address": "ip_address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + "service_attachment": "service_attachment_value", + "psc_connection_status": 1, + "connection_type": 1, + }, + } + ] + } + ], + "mode": 1, + "simulate_maintenance_event": True, + "ondemand_maintenance": True, + "satisfies_pzs": True, + "satisfies_pzi": True, + "maintenance_policy": { + "create_time": {}, + "update_time": {}, + "weekly_maintenance_window": [ + { + "day": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + } + ], + }, + "maintenance_schedule": {"start_time": {}, "end_time": {}}, + "cross_instance_replication_config": { + "instance_role": 1, + "primary_instance": {"instance": "instance_value", "uid": "uid_value"}, + "secondary_instances": {}, + "update_time": {}, + "membership": {"primary_instance": {}, "secondary_instances": {}}, + }, + "async_instance_endpoints_deletion_enabled": True, + "kms_key": "kms_key_value", + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + "kms_key_primary_state": 1, + "last_update_time": {}, + }, + "backup_collection": "backup_collection_value", + "automated_backup_config": { + "fixed_frequency_schedule": {"start_time": {}}, + "automated_backup_mode": 1, + "retention": {"seconds": 751, "nanos": 543}, + }, + "maintenance_version": "maintenance_version_value", + "effective_maintenance_version": "effective_maintenance_version_value", + "available_maintenance_versions": [ + "available_maintenance_versions_value1", + "available_maintenance_versions_value2", + ], + "allow_fewer_zones_deployment": True, + "server_ca_mode": 1, + "server_ca_pool": "server_ca_pool_value", + "rotate_server_certificate": True, + "migration_config": { + "self_managed_source": { + "ip_address": "ip_address_value", + "port": 453, + "network_attachment": "network_attachment_value", + }, + "state": 1, + "force_finish_migration": True, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = memorystore.CreateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.create_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_create_instance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_create_instance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_create_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_create_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.CreateInstanceRequest.pb( + memorystore.CreateInstanceRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.CreateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.create_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_update_instance_rest_bad_request( + request_type=memorystore.UpdateInstanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.update_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.UpdateInstanceRequest, + dict, + ], +) +def test_update_instance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + } + request_init["instance"] = { + "gcs_source": {"uris": ["uris_value1", "uris_value2"]}, + "managed_backup_source": {"backup": "backup_value"}, + "name": "projects/sample1/locations/sample2/instances/sample3", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "labels": {}, + "state": 1, + "state_info": { + "update_info": { + "target_shard_count": 1920, + "target_replica_count": 2126, + "target_engine_version": "target_engine_version_value", + "target_node_type": 1, + } + }, + "uid": "uid_value", + "replica_count": 1384, + "authorization_mode": 1, + "transit_encryption_mode": 1, + "shard_count": 1178, + "discovery_endpoints": [ + {"address": "address_value", "port": 453, "network": "network_value"} + ], + "node_type": 1, + "persistence_config": { + "mode": 1, + "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, + "aof_config": {"append_fsync": 1}, + }, + "engine_version": "engine_version_value", + "engine_configs": {}, + "node_config": {"size_gb": 0.739}, + "zone_distribution_config": {"zone": "zone_value", "mode": 1}, + "deletion_protection_enabled": True, + "psc_auto_connections": [ + { + "port": 453, + "psc_connection_id": "psc_connection_id_value", + "ip_address": "ip_address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + "service_attachment": "service_attachment_value", + "psc_connection_status": 1, + "connection_type": 1, + } + ], + "psc_attachment_details": [ + {"service_attachment": "service_attachment_value", "connection_type": 1} + ], + "endpoints": [ + { + "connections": [ + { + "psc_auto_connection": {}, + "psc_connection": { + "port": 453, + "psc_connection_id": "psc_connection_id_value", + "ip_address": "ip_address_value", + "forwarding_rule": "forwarding_rule_value", + "project_id": "project_id_value", + "network": "network_value", + "service_attachment": "service_attachment_value", + "psc_connection_status": 1, + "connection_type": 1, + }, + } + ] + } + ], + "mode": 1, + "simulate_maintenance_event": True, + "ondemand_maintenance": True, + "satisfies_pzs": True, + "satisfies_pzi": True, + "maintenance_policy": { + "create_time": {}, + "update_time": {}, + "weekly_maintenance_window": [ + { + "day": 1, + "start_time": { + "hours": 561, + "minutes": 773, + "seconds": 751, + "nanos": 543, + }, + } + ], + }, + "maintenance_schedule": {"start_time": {}, "end_time": {}}, + "cross_instance_replication_config": { + "instance_role": 1, + "primary_instance": {"instance": "instance_value", "uid": "uid_value"}, + "secondary_instances": {}, + "update_time": {}, + "membership": {"primary_instance": {}, "secondary_instances": {}}, + }, + "async_instance_endpoints_deletion_enabled": True, + "kms_key": "kms_key_value", + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + "kms_key_primary_state": 1, + "last_update_time": {}, + }, + "backup_collection": "backup_collection_value", + "automated_backup_config": { + "fixed_frequency_schedule": {"start_time": {}}, + "automated_backup_mode": 1, + "retention": {"seconds": 751, "nanos": 543}, + }, + "maintenance_version": "maintenance_version_value", + "effective_maintenance_version": "effective_maintenance_version_value", + "available_maintenance_versions": [ + "available_maintenance_versions_value1", + "available_maintenance_versions_value2", + ], + "allow_fewer_zones_deployment": True, + "server_ca_mode": 1, + "server_ca_pool": "server_ca_pool_value", + "rotate_server_certificate": True, + "migration_config": { + "self_managed_source": { + "ip_address": "ip_address_value", + "port": 453, + "network_attachment": "network_attachment_value", + }, + "state": 1, + "force_finish_migration": True, + }, + } + # The version of a generated dependency at test runtime may differ from the version used during generation. + # Delete any fields which are not present in the current runtime dependency + # See https://github.com/googleapis/gapic-generator-python/issues/1748 + + # Determine if the message type is proto-plus or protobuf + test_field = memorystore.UpdateInstanceRequest.meta.fields["instance"] + + def get_message_fields(field): + # Given a field which is a message (composite type), return a list with + # all the fields of the message. + # If the field is not a composite type, return an empty list. + message_fields = [] + + if hasattr(field, "message") and field.message: + is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + + if is_field_type_proto_plus_type: + message_fields = field.message.meta.fields.values() + # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types + else: # pragma: NO COVER + message_fields = field.message.DESCRIPTOR.fields + return message_fields + + runtime_nested_fields = [ + (field.name, nested_field.name) + for field in get_message_fields(test_field) + for nested_field in get_message_fields(field) + ] + + subfields_not_in_runtime = [] + + # For each item in the sample request, create a list of sub fields which are not present at runtime + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for field, value in request_init["instance"].items(): # pragma: NO COVER + result = None + is_repeated = False + # For repeated fields + if isinstance(value, list) and len(value): + is_repeated = True + result = value[0] + # For fields where the type is another message + if isinstance(value, dict): + result = value + + if result and hasattr(result, "keys"): + for subfield in result.keys(): + if (field, subfield) not in runtime_nested_fields: + subfields_not_in_runtime.append( + { + "field": field, + "subfield": subfield, + "is_repeated": is_repeated, + } + ) + + # Remove fields from the sample request which are not present in the runtime version of the dependency + # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime + for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER + field = subfield_to_delete.get("field") + field_repeated = subfield_to_delete.get("is_repeated") + subfield = subfield_to_delete.get("subfield") + if subfield: + if field_repeated: + for i in range(0, len(request_init["instance"][field])): + del request_init["instance"][field][i][subfield] + else: + del request_init["instance"][field][subfield] + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.update_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_update_instance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_update_instance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_update_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_update_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.UpdateInstanceRequest.pb( + memorystore.UpdateInstanceRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.UpdateInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.update_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_instance_rest_bad_request( + request_type=memorystore.DeleteInstanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.delete_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteInstanceRequest, + dict, + ], +) +def test_delete_instance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_instance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_delete_instance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_delete_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_delete_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.DeleteInstanceRequest.pb( + memorystore.DeleteInstanceRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.DeleteInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_certificate_authority_rest_bad_request( + request_type=memorystore.GetCertificateAuthorityRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetCertificateAuthorityRequest, + dict, + ], +) +def test_get_certificate_authority_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.CertificateAuthority( + name="name_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 = memorystore.CertificateAuthority.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_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.CertificateAuthority) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_get_certificate_authority" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_get_certificate_authority_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_get_certificate_authority" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetCertificateAuthorityRequest.pb( + memorystore.GetCertificateAuthorityRequest() + ) + 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 = memorystore.CertificateAuthority.to_json( + memorystore.CertificateAuthority() + ) + req.return_value.content = return_value + + request = memorystore.GetCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.CertificateAuthority() + post_with_metadata.return_value = memorystore.CertificateAuthority(), metadata + + client.get_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_shared_regional_certificate_authority_rest_bad_request( + request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" + } + 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_shared_regional_certificate_authority(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetSharedRegionalCertificateAuthorityRequest, + dict, + ], +) +def test_get_shared_regional_certificate_authority_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" + } + 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 = memorystore.SharedRegionalCertificateAuthority( + name="name_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 = memorystore.SharedRegionalCertificateAuthority.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_shared_regional_certificate_authority(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.SharedRegionalCertificateAuthority) + assert response.name == "name_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_shared_regional_certificate_authority_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, + "post_get_shared_regional_certificate_authority", + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_get_shared_regional_certificate_authority_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "pre_get_shared_regional_certificate_authority", + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( + memorystore.GetSharedRegionalCertificateAuthorityRequest() + ) + 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 = memorystore.SharedRegionalCertificateAuthority.to_json( + memorystore.SharedRegionalCertificateAuthority() + ) + req.return_value.content = return_value + + request = memorystore.GetSharedRegionalCertificateAuthorityRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.SharedRegionalCertificateAuthority() + post_with_metadata.return_value = ( + memorystore.SharedRegionalCertificateAuthority(), + metadata, + ) + + client.get_shared_regional_certificate_authority( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_reschedule_maintenance_rest_bad_request( + request_type=memorystore.RescheduleMaintenanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.reschedule_maintenance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.RescheduleMaintenanceRequest, + dict, + ], +) +def test_reschedule_maintenance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.reschedule_maintenance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_reschedule_maintenance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_reschedule_maintenance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_reschedule_maintenance_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_reschedule_maintenance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.RescheduleMaintenanceRequest.pb( + memorystore.RescheduleMaintenanceRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.RescheduleMaintenanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.reschedule_maintenance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backup_collections_rest_bad_request( + request_type=memorystore.ListBackupCollectionsRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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_backup_collections(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListBackupCollectionsRequest, + dict, + ], +) +def test_list_backup_collections_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.ListBackupCollectionsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = memorystore.ListBackupCollectionsResponse.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_backup_collections(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupCollectionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backup_collections_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_list_backup_collections" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_list_backup_collections_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_list_backup_collections" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.ListBackupCollectionsRequest.pb( + memorystore.ListBackupCollectionsRequest() + ) + 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 = memorystore.ListBackupCollectionsResponse.to_json( + memorystore.ListBackupCollectionsResponse() + ) + req.return_value.content = return_value + + request = memorystore.ListBackupCollectionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.ListBackupCollectionsResponse() + post_with_metadata.return_value = ( + memorystore.ListBackupCollectionsResponse(), + metadata, + ) + + client.list_backup_collections( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_collection_rest_bad_request( + request_type=memorystore.GetBackupCollectionRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/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.get_backup_collection(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetBackupCollectionRequest, + dict, + ], +) +def test_get_backup_collection_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/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 = memorystore.BackupCollection( + name="name_value", + instance_uid="instance_uid_value", + instance="instance_value", + kms_key="kms_key_value", + uid="uid_value", + total_backup_size_bytes=2457, + total_backup_count=1921, + ) + + # 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 = memorystore.BackupCollection.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_backup_collection(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.BackupCollection) + assert response.name == "name_value" + assert response.instance_uid == "instance_uid_value" + assert response.instance == "instance_value" + assert response.kms_key == "kms_key_value" + assert response.uid == "uid_value" + assert response.total_backup_size_bytes == 2457 + assert response.total_backup_count == 1921 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_collection_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_get_backup_collection" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_get_backup_collection_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_get_backup_collection" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetBackupCollectionRequest.pb( + memorystore.GetBackupCollectionRequest() + ) + 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 = memorystore.BackupCollection.to_json( + memorystore.BackupCollection() + ) + req.return_value.content = return_value + + request = memorystore.GetBackupCollectionRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.BackupCollection() + post_with_metadata.return_value = memorystore.BackupCollection(), metadata + + client.get_backup_collection( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_backups_rest_bad_request(request_type=memorystore.ListBackupsRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupCollections/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_backups(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListBackupsRequest, + dict, + ], +) +def test_list_backups_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "parent": "projects/sample1/locations/sample2/backupCollections/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 = memorystore.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = memorystore.ListBackupsResponse.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_backups(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_backups_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_list_backups" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_list_backups_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_list_backups" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.ListBackupsRequest.pb(memorystore.ListBackupsRequest()) + 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 = memorystore.ListBackupsResponse.to_json( + memorystore.ListBackupsResponse() + ) + req.return_value.content = return_value + + request = memorystore.ListBackupsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.ListBackupsResponse() + post_with_metadata.return_value = memorystore.ListBackupsResponse(), metadata + + client.list_backups( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_backup_rest_bad_request(request_type=memorystore.GetBackupRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/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_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.GetBackupRequest, + dict, + ], +) +def test_get_backup_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/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 = memorystore.Backup( + name="name_value", + instance="instance_value", + instance_uid="instance_uid_value", + total_size_bytes=1732, + engine_version="engine_version_value", + node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, + replica_count=1384, + shard_count=1178, + backup_type=memorystore.Backup.BackupType.ON_DEMAND, + state=memorystore.Backup.State.CREATING, + uid="uid_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 = memorystore.Backup.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_backup(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.Backup) + assert response.name == "name_value" + assert response.instance == "instance_value" + assert response.instance_uid == "instance_uid_value" + assert response.total_size_bytes == 1732 + assert response.engine_version == "engine_version_value" + assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO + assert response.replica_count == 1384 + assert response.shard_count == 1178 + assert response.backup_type == memorystore.Backup.BackupType.ON_DEMAND + assert response.state == memorystore.Backup.State.CREATING + assert response.uid == "uid_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_backup_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_get_backup" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_get_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_get_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetBackupRequest.pb(memorystore.GetBackupRequest()) + 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 = memorystore.Backup.to_json(memorystore.Backup()) + req.return_value.content = return_value + + request = memorystore.GetBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.Backup() + post_with_metadata.return_value = memorystore.Backup(), metadata + + client.get_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_delete_backup_rest_bad_request(request_type=memorystore.DeleteBackupRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/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.delete_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.DeleteBackupRequest, + dict, + ], +) +def test_delete_backup_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.delete_backup(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_backup_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_delete_backup" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_delete_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_delete_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.DeleteBackupRequest.pb( + memorystore.DeleteBackupRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.DeleteBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.delete_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_export_backup_rest_bad_request(request_type=memorystore.ExportBackupRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/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.export_backup(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ExportBackupRequest, + dict, + ], +) +def test_export_backup_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/backupCollections/sample3/backups/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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.export_backup(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_export_backup_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_export_backup" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_export_backup_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_export_backup" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.ExportBackupRequest.pb( + memorystore.ExportBackupRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.ExportBackupRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.export_backup( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_backup_instance_rest_bad_request( + request_type=memorystore.BackupInstanceRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.backup_instance(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.BackupInstanceRequest, + dict, + ], +) +def test_backup_instance_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.backup_instance(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_backup_instance_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_backup_instance" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_backup_instance_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_backup_instance" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.BackupInstanceRequest.pb( + memorystore.BackupInstanceRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.BackupInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.backup_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_start_migration_rest_bad_request( + request_type=memorystore.StartMigrationRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.start_migration(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.StartMigrationRequest, + dict, + ], +) +def test_start_migration_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.start_migration(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_start_migration_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_start_migration" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_start_migration_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_start_migration" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.StartMigrationRequest.pb( + memorystore.StartMigrationRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.StartMigrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.start_migration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_finish_migration_rest_bad_request( + request_type=memorystore.FinishMigrationRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a 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.finish_migration(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.FinishMigrationRequest, + dict, + ], +) +def test_finish_migration_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + response = client.finish_migration(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_finish_migration_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(transport=transport) + + with ( + mock.patch.object(type(client.transport._session), "request") as req, + mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_finish_migration" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_finish_migration_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_finish_migration" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.FinishMigrationRequest.pb( + memorystore.FinishMigrationRequest() + ) + 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 = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = memorystore.FinishMigrationRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata + + client.finish_migration( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_list_token_auth_users_rest_bad_request( + request_type=memorystore.ListTokenAuthUsersRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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_token_auth_users(request) + + +@pytest.mark.parametrize( + "request_type", + [ + memorystore.ListTokenAuthUsersRequest, + dict, + ], +) +def test_list_token_auth_users_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = memorystore.ListTokenAuthUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_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 = memorystore.ListTokenAuthUsersResponse.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_token_auth_users(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListTokenAuthUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_token_auth_users_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_list_token_auth_users" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, + "post_list_token_auth_users_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_list_token_auth_users" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.ListTokenAuthUsersRequest.pb( + memorystore.ListTokenAuthUsersRequest() + ) + 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 = memorystore.ListTokenAuthUsersResponse.to_json( + memorystore.ListTokenAuthUsersResponse() + ) + req.return_value.content = return_value + + request = memorystore.ListTokenAuthUsersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.ListTokenAuthUsersResponse() + post_with_metadata.return_value = ( + memorystore.ListTokenAuthUsersResponse(), + metadata, + ) + + client.list_token_auth_users( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_instances_rest_bad_request(request_type=memorystore.ListInstancesRequest): +def test_get_token_auth_user_rest_bad_request( + request_type=memorystore.GetTokenAuthUserRequest, +): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5817,31 +19999,33 @@ def test_list_instances_rest_bad_request(request_type=memorystore.ListInstancesR response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_instances(request) + client.get_token_auth_user(request) @pytest.mark.parametrize( "request_type", [ - memorystore.ListInstancesRequest, + memorystore.GetTokenAuthUserRequest, dict, ], ) -def test_list_instances_rest_call_success(request_type): +def test_get_token_auth_user_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/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 = memorystore.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + return_value = memorystore.TokenAuthUser( + name="name_value", + state=memorystore.TokenAuthUser.State.ACTIVE, ) # Wrap the value into a proper Response obj @@ -5849,21 +20033,21 @@ def test_list_instances_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.ListInstancesResponse.pb(return_value) + return_value = memorystore.TokenAuthUser.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_instances(request) + response = client.get_token_auth_user(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, memorystore.TokenAuthUser) + assert response.name == "name_value" + assert response.state == memorystore.TokenAuthUser.State.ACTIVE @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): +def test_get_token_auth_user_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -5876,20 +20060,21 @@ def test_list_instances_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_list_instances" + transports.MemorystoreRestInterceptor, "post_get_token_auth_user" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_list_instances_with_metadata" + transports.MemorystoreRestInterceptor, + "post_get_token_auth_user_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_list_instances" + transports.MemorystoreRestInterceptor, "pre_get_token_auth_user" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.ListInstancesRequest.pb( - memorystore.ListInstancesRequest() + pb_message = memorystore.GetTokenAuthUserRequest.pb( + memorystore.GetTokenAuthUserRequest() ) transcode.return_value = { "method": "post", @@ -5901,21 +20086,19 @@ def test_list_instances_rest_interceptors(null_interceptor): 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 = memorystore.ListInstancesResponse.to_json( - memorystore.ListInstancesResponse() - ) + return_value = memorystore.TokenAuthUser.to_json(memorystore.TokenAuthUser()) req.return_value.content = return_value - request = memorystore.ListInstancesRequest() + request = memorystore.GetTokenAuthUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.ListInstancesResponse() - post_with_metadata.return_value = memorystore.ListInstancesResponse(), metadata + post.return_value = memorystore.TokenAuthUser() + post_with_metadata.return_value = memorystore.TokenAuthUser(), metadata - client.list_instances( + client.get_token_auth_user( request, metadata=[ ("key", "val"), @@ -5928,12 +20111,16 @@ def test_list_instances_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_instance_rest_bad_request(request_type=memorystore.GetInstanceRequest): +def test_list_auth_tokens_rest_bad_request( + request_type=memorystore.ListAuthTokensRequest, +): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "parent": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -5949,43 +20136,33 @@ def test_get_instance_rest_bad_request(request_type=memorystore.GetInstanceReque response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_instance(request) + client.list_auth_tokens(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetInstanceRequest, + memorystore.ListAuthTokensRequest, dict, ], ) -def test_get_instance_rest_call_success(request_type): +def test_list_auth_tokens_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "parent": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/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 = memorystore.Instance( - name="name_value", - state=memorystore.Instance.State.CREATING, - uid="uid_value", - replica_count=1384, - authorization_mode=memorystore.Instance.AuthorizationMode.AUTH_DISABLED, - transit_encryption_mode=memorystore.Instance.TransitEncryptionMode.TRANSIT_ENCRYPTION_DISABLED, - shard_count=1178, - node_type=memorystore.Instance.NodeType.SHARED_CORE_NANO, - engine_version="engine_version_value", - deletion_protection_enabled=True, - mode=memorystore.Instance.Mode.STANDALONE, - server_ca_mode=memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA, - server_ca_pool="server_ca_pool_value", - rotate_server_certificate=True, + return_value = memorystore.ListAuthTokensResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) # Wrap the value into a proper Response obj @@ -5993,42 +20170,21 @@ def test_get_instance_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = memorystore.Instance.pb(return_value) + return_value = memorystore.ListAuthTokensResponse.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_instance(request) + response = client.list_auth_tokens(request) # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.Instance) - assert response.name == "name_value" - assert response.state == memorystore.Instance.State.CREATING - assert response.uid == "uid_value" - assert response.replica_count == 1384 - assert ( - response.authorization_mode - == memorystore.Instance.AuthorizationMode.AUTH_DISABLED - ) - assert ( - response.transit_encryption_mode - == memorystore.Instance.TransitEncryptionMode.TRANSIT_ENCRYPTION_DISABLED - ) - assert response.shard_count == 1178 - assert response.node_type == memorystore.Instance.NodeType.SHARED_CORE_NANO - assert response.engine_version == "engine_version_value" - assert response.deletion_protection_enabled is True - assert response.mode == memorystore.Instance.Mode.STANDALONE - assert ( - response.server_ca_mode - == memorystore.Instance.ServerCaMode.GOOGLE_MANAGED_PER_INSTANCE_CA - ) - assert response.server_ca_pool == "server_ca_pool_value" - assert response.rotate_server_certificate is True + assert isinstance(response, pagers.ListAuthTokensPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): +def test_list_auth_tokens_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6041,19 +20197,21 @@ def test_get_instance_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_instance" + transports.MemorystoreRestInterceptor, "post_list_auth_tokens" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_instance_with_metadata" + transports.MemorystoreRestInterceptor, "post_list_auth_tokens_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_get_instance" + transports.MemorystoreRestInterceptor, "pre_list_auth_tokens" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.GetInstanceRequest.pb(memorystore.GetInstanceRequest()) + pb_message = memorystore.ListAuthTokensRequest.pb( + memorystore.ListAuthTokensRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -6064,19 +20222,21 @@ def test_get_instance_rest_interceptors(null_interceptor): 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 = memorystore.Instance.to_json(memorystore.Instance()) + return_value = memorystore.ListAuthTokensResponse.to_json( + memorystore.ListAuthTokensResponse() + ) req.return_value.content = return_value - request = memorystore.GetInstanceRequest() + request = memorystore.ListAuthTokensRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.Instance() - post_with_metadata.return_value = memorystore.Instance(), metadata + post.return_value = memorystore.ListAuthTokensResponse() + post_with_metadata.return_value = memorystore.ListAuthTokensResponse(), metadata - client.get_instance( + client.list_auth_tokens( request, metadata=[ ("key", "val"), @@ -6089,14 +20249,14 @@ def test_get_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_create_instance_rest_bad_request( - request_type=memorystore.CreateInstanceRequest, -): +def test_get_auth_token_rest_bad_request(request_type=memorystore.GetAuthTokenRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4/authTokens/sample5" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6112,155 +20272,159 @@ def test_create_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.create_instance(request) + client.get_auth_token(request) @pytest.mark.parametrize( "request_type", [ - memorystore.CreateInstanceRequest, + memorystore.GetAuthTokenRequest, dict, ], ) -def test_create_instance_rest_call_success(request_type): +def test_get_auth_token_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["instance"] = { - "name": "name_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "state": 1, - "state_info": { - "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} - }, - "uid": "uid_value", - "replica_count": 1384, - "authorization_mode": 1, - "transit_encryption_mode": 1, - "shard_count": 1178, - "discovery_endpoints": [ - {"address": "address_value", "port": 453, "network": "network_value"} - ], - "node_type": 1, - "persistence_config": { - "mode": 1, - "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, - "aof_config": {"append_fsync": 1}, - }, - "engine_version": "engine_version_value", - "engine_configs": {}, - "node_config": {"size_gb": 0.739}, - "zone_distribution_config": {"zone": "zone_value", "mode": 1}, - "deletion_protection_enabled": True, - "psc_auto_connections": [ - { - "port": 453, - "psc_connection_id": "psc_connection_id_value", - "ip_address": "ip_address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - "service_attachment": "service_attachment_value", - "psc_connection_status": 1, - "connection_type": 1, - } - ], - "endpoints": [ - { - "connections": [ - { - "psc_auto_connection": {}, - "psc_connection": { - "psc_connection_id": "psc_connection_id_value", - "ip_address": "ip_address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - "service_attachment": "service_attachment_value", - "psc_connection_status": 1, - "connection_type": 1, - }, - } - ] - } - ], - "mode": 1, - "server_ca_mode": 1, - "server_ca_pool": "server_ca_pool_value", - "rotate_server_certificate": True, + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4/authTokens/sample5" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 + request = request_type(**request_init) - # Determine if the message type is proto-plus or protobuf - test_field = memorystore.CreateInstanceRequest.meta.fields["instance"] + # 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 = memorystore.AuthToken( + name="name_value", + token="token_value", + state=memorystore.AuthToken.State.ACTIVE, + ) - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] + # 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 = memorystore.AuthToken.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_auth_token(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, memorystore.AuthToken) + assert response.name == "name_value" + assert response.token == "token_value" + assert response.state == memorystore.AuthToken.State.ACTIVE + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_auth_token_rest_interceptors(null_interceptor): + transport = transports.MemorystoreRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.MemorystoreRestInterceptor(), + ) + client = MemorystoreClient(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.MemorystoreRestInterceptor, "post_get_auth_token" + ) as post, + mock.patch.object( + transports.MemorystoreRestInterceptor, "post_get_auth_token_with_metadata" + ) as post_with_metadata, + mock.patch.object( + transports.MemorystoreRestInterceptor, "pre_get_auth_token" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = memorystore.GetAuthTokenRequest.pb( + memorystore.GetAuthTokenRequest() + ) + 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 = memorystore.AuthToken.to_json(memorystore.AuthToken()) + req.return_value.content = return_value + + request = memorystore.GetAuthTokenRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = memorystore.AuthToken() + post_with_metadata.return_value = memorystore.AuthToken(), metadata + + client.get_auth_token( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] +def test_add_token_auth_user_rest_bad_request( + request_type=memorystore.AddTokenAuthUserRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/sample3"} + request = request_type(**request_init) - subfields_not_in_runtime = [] + # 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.add_token_auth_user(request) - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) +@pytest.mark.parametrize( + "request_type", + [ + memorystore.AddTokenAuthUserRequest, + dict, + ], +) +def test_add_token_auth_user_rest_call_success(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] + # send a request that will satisfy transcoding + request_init = {"instance": "projects/sample1/locations/sample2/instances/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -6275,14 +20439,14 @@ def get_message_fields(field): 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.create_instance(request) + response = client.add_token_auth_user(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): +def test_add_token_auth_user_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6296,20 +20460,21 @@ def test_create_instance_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_create_instance" + transports.MemorystoreRestInterceptor, "post_add_token_auth_user" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_create_instance_with_metadata" + transports.MemorystoreRestInterceptor, + "post_add_token_auth_user_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_create_instance" + transports.MemorystoreRestInterceptor, "pre_add_token_auth_user" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.CreateInstanceRequest.pb( - memorystore.CreateInstanceRequest() + pb_message = memorystore.AddTokenAuthUserRequest.pb( + memorystore.AddTokenAuthUserRequest() ) transcode.return_value = { "method": "post", @@ -6324,7 +20489,7 @@ def test_create_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.CreateInstanceRequest() + request = memorystore.AddTokenAuthUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -6333,7 +20498,7 @@ def test_create_instance_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.create_instance( + client.add_token_auth_user( request, metadata=[ ("key", "val"), @@ -6346,15 +20511,15 @@ def test_create_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_update_instance_rest_bad_request( - request_type=memorystore.UpdateInstanceRequest, +def test_delete_token_auth_user_rest_bad_request( + request_type=memorystore.DeleteTokenAuthUserRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" } request = request_type(**request_init) @@ -6371,157 +20536,25 @@ def test_update_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.update_instance(request) + client.delete_token_auth_user(request) @pytest.mark.parametrize( "request_type", [ - memorystore.UpdateInstanceRequest, + memorystore.DeleteTokenAuthUserRequest, dict, ], ) -def test_update_instance_rest_call_success(request_type): +def test_delete_token_auth_user_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding request_init = { - "instance": {"name": "projects/sample1/locations/sample2/instances/sample3"} - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/instances/sample3", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "labels": {}, - "state": 1, - "state_info": { - "update_info": {"target_shard_count": 1920, "target_replica_count": 2126} - }, - "uid": "uid_value", - "replica_count": 1384, - "authorization_mode": 1, - "transit_encryption_mode": 1, - "shard_count": 1178, - "discovery_endpoints": [ - {"address": "address_value", "port": 453, "network": "network_value"} - ], - "node_type": 1, - "persistence_config": { - "mode": 1, - "rdb_config": {"rdb_snapshot_period": 1, "rdb_snapshot_start_time": {}}, - "aof_config": {"append_fsync": 1}, - }, - "engine_version": "engine_version_value", - "engine_configs": {}, - "node_config": {"size_gb": 0.739}, - "zone_distribution_config": {"zone": "zone_value", "mode": 1}, - "deletion_protection_enabled": True, - "psc_auto_connections": [ - { - "port": 453, - "psc_connection_id": "psc_connection_id_value", - "ip_address": "ip_address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - "service_attachment": "service_attachment_value", - "psc_connection_status": 1, - "connection_type": 1, - } - ], - "endpoints": [ - { - "connections": [ - { - "psc_auto_connection": {}, - "psc_connection": { - "psc_connection_id": "psc_connection_id_value", - "ip_address": "ip_address_value", - "forwarding_rule": "forwarding_rule_value", - "project_id": "project_id_value", - "network": "network_value", - "service_attachment": "service_attachment_value", - "psc_connection_status": 1, - "connection_type": 1, - }, - } - ] - } - ], - "mode": 1, - "server_ca_mode": 1, - "server_ca_pool": "server_ca_pool_value", - "rotate_server_certificate": True, + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" } - # The version of a generated dependency at test runtime may differ from the version used during generation. - # Delete any fields which are not present in the current runtime dependency - # See https://github.com/googleapis/gapic-generator-python/issues/1748 - - # Determine if the message type is proto-plus or protobuf - test_field = memorystore.UpdateInstanceRequest.meta.fields["instance"] - - def get_message_fields(field): - # Given a field which is a message (composite type), return a list with - # all the fields of the message. - # If the field is not a composite type, return an empty list. - message_fields = [] - - if hasattr(field, "message") and field.message: - is_field_type_proto_plus_type = not hasattr(field.message, "DESCRIPTOR") - - if is_field_type_proto_plus_type: - message_fields = field.message.meta.fields.values() - # Add `# pragma: NO COVER` because there may not be any `*_pb2` field types - else: # pragma: NO COVER - message_fields = field.message.DESCRIPTOR.fields - return message_fields - - runtime_nested_fields = [ - (field.name, nested_field.name) - for field in get_message_fields(test_field) - for nested_field in get_message_fields(field) - ] - - subfields_not_in_runtime = [] - - # For each item in the sample request, create a list of sub fields which are not present at runtime - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for field, value in request_init["instance"].items(): # pragma: NO COVER - result = None - is_repeated = False - # For repeated fields - if isinstance(value, list) and len(value): - is_repeated = True - result = value[0] - # For fields where the type is another message - if isinstance(value, dict): - result = value - - if result and hasattr(result, "keys"): - for subfield in result.keys(): - if (field, subfield) not in runtime_nested_fields: - subfields_not_in_runtime.append( - { - "field": field, - "subfield": subfield, - "is_repeated": is_repeated, - } - ) - - # Remove fields from the sample request which are not present in the runtime version of the dependency - # Add `# pragma: NO COVER` because this test code will not run if all subfields are present at runtime - for subfield_to_delete in subfields_not_in_runtime: # pragma: NO COVER - field = subfield_to_delete.get("field") - field_repeated = subfield_to_delete.get("is_repeated") - subfield = subfield_to_delete.get("subfield") - if subfield: - if field_repeated: - for i in range(0, len(request_init["instance"][field])): - del request_init["instance"][field][i][subfield] - else: - del request_init["instance"][field][subfield] request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -6536,14 +20569,14 @@ def get_message_fields(field): 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.update_instance(request) + response = client.delete_token_auth_user(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_delete_token_auth_user_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6557,20 +20590,21 @@ def test_update_instance_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_update_instance" + transports.MemorystoreRestInterceptor, "post_delete_token_auth_user" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_update_instance_with_metadata" + transports.MemorystoreRestInterceptor, + "post_delete_token_auth_user_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_update_instance" + transports.MemorystoreRestInterceptor, "pre_delete_token_auth_user" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.UpdateInstanceRequest.pb( - memorystore.UpdateInstanceRequest() + pb_message = memorystore.DeleteTokenAuthUserRequest.pb( + memorystore.DeleteTokenAuthUserRequest() ) transcode.return_value = { "method": "post", @@ -6585,7 +20619,7 @@ def test_update_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.UpdateInstanceRequest() + request = memorystore.DeleteTokenAuthUserRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -6594,7 +20628,7 @@ def test_update_instance_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.update_instance( + client.delete_token_auth_user( request, metadata=[ ("key", "val"), @@ -6607,14 +20641,14 @@ def test_update_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_delete_instance_rest_bad_request( - request_type=memorystore.DeleteInstanceRequest, -): +def test_add_auth_token_rest_bad_request(request_type=memorystore.AddAuthTokenRequest): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "token_auth_user": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6630,23 +20664,25 @@ def test_delete_instance_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_instance(request) + client.add_auth_token(request) @pytest.mark.parametrize( "request_type", [ - memorystore.DeleteInstanceRequest, + memorystore.AddAuthTokenRequest, dict, ], ) -def test_delete_instance_rest_call_success(request_type): +def test_add_auth_token_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "token_auth_user": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -6661,14 +20697,14 @@ def test_delete_instance_rest_call_success(request_type): 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.delete_instance(request) + response = client.add_auth_token(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_add_auth_token_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6682,20 +20718,20 @@ def test_delete_instance_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_delete_instance" + transports.MemorystoreRestInterceptor, "post_add_auth_token" ) as post, mock.patch.object( - transports.MemorystoreRestInterceptor, "post_delete_instance_with_metadata" + transports.MemorystoreRestInterceptor, "post_add_auth_token_with_metadata" ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_delete_instance" + transports.MemorystoreRestInterceptor, "pre_add_auth_token" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.DeleteInstanceRequest.pb( - memorystore.DeleteInstanceRequest() + pb_message = memorystore.AddAuthTokenRequest.pb( + memorystore.AddAuthTokenRequest() ) transcode.return_value = { "method": "post", @@ -6710,7 +20746,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.DeleteInstanceRequest() + request = memorystore.AddAuthTokenRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -6719,7 +20755,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): post.return_value = operations_pb2.Operation() post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.delete_instance( + client.add_auth_token( request, metadata=[ ("key", "val"), @@ -6732,14 +20768,16 @@ def test_delete_instance_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_certificate_authority_rest_bad_request( - request_type=memorystore.GetCertificateAuthorityRequest, +def test_delete_auth_token_rest_bad_request( + request_type=memorystore.DeleteAuthTokenRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4/authTokens/sample5" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -6755,51 +20793,47 @@ def test_get_certificate_authority_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_certificate_authority(request) + client.delete_auth_token(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetCertificateAuthorityRequest, + memorystore.DeleteAuthTokenRequest, dict, ], ) -def test_get_certificate_authority_rest_call_success(request_type): +def test_delete_auth_token_rest_call_success(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/instances/sample3"} + request_init = { + "name": "projects/sample1/locations/sample2/instances/sample3/tokenAuthUsers/sample4/authTokens/sample5" + } 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 = memorystore.CertificateAuthority( - name="name_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # 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 = memorystore.CertificateAuthority.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_certificate_authority(request) + response = client.delete_auth_token(request) # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.CertificateAuthority) - assert response.name == "name_value" + json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_certificate_authority_rest_interceptors(null_interceptor): +def test_delete_auth_token_rest_interceptors(null_interceptor): transport = transports.MemorystoreRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -6811,22 +20845,23 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): with ( mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, + mock.patch.object(operation.Operation, "_set_result_from_operation"), mock.patch.object( - transports.MemorystoreRestInterceptor, "post_get_certificate_authority" + transports.MemorystoreRestInterceptor, "post_delete_auth_token" ) as post, mock.patch.object( transports.MemorystoreRestInterceptor, - "post_get_certificate_authority_with_metadata", + "post_delete_auth_token_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.MemorystoreRestInterceptor, "pre_get_certificate_authority" + transports.MemorystoreRestInterceptor, "pre_delete_auth_token" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = memorystore.GetCertificateAuthorityRequest.pb( - memorystore.GetCertificateAuthorityRequest() + pb_message = memorystore.DeleteAuthTokenRequest.pb( + memorystore.DeleteAuthTokenRequest() ) transcode.return_value = { "method": "post", @@ -6838,21 +20873,19 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): 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 = memorystore.CertificateAuthority.to_json( - memorystore.CertificateAuthority() - ) + return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = memorystore.GetCertificateAuthorityRequest() + request = memorystore.DeleteAuthTokenRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = memorystore.CertificateAuthority() - post_with_metadata.return_value = memorystore.CertificateAuthority(), metadata + post.return_value = operations_pb2.Operation() + post_with_metadata.return_value = operations_pb2.Operation(), metadata - client.get_certificate_authority( + client.delete_auth_token( request, metadata=[ ("key", "val"), @@ -6865,156 +20898,264 @@ def test_get_certificate_authority_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_shared_regional_certificate_authority_rest_bad_request( - request_type=memorystore.GetSharedRegionalCertificateAuthorityRequest, +def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.get_location(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.GetLocationRequest, + dict, + ], +) +def test_get_location_rest(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.Location() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.get_location(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) + + +def test_list_locations_rest_bad_request( + request_type=locations_pb2.ListLocationsRequest, ): client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" - } + request = request_type() + request = json_format.ParseDict({"name": "projects/sample1"}, request) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.list_locations(request) + + +@pytest.mark.parametrize( + "request_type", + [ + locations_pb2.ListLocationsRequest, + dict, + ], +) +def test_list_locations_rest(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1"} request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = locations_pb2.ListLocationsResponse() + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.list_locations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) + + +def test_cancel_operation_rest_bad_request( + request_type=operations_pb2.CancelOperationRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with ( mock.patch.object(Session, "request") as req, pytest.raises(core_exceptions.BadRequest), ): + # Wrap the value into a proper Response obj + response_value = Response() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + client.cancel_operation(request) + + +@pytest.mark.parametrize( + "request_type", + [ + operations_pb2.CancelOperationRequest, + dict, + ], +) +def test_cancel_operation_rest(request_type): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + # Wrap the value into a proper Response obj response_value = mock.Mock() + response_value.status_code = 200 + json_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.cancel_operation(request) + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_rest_bad_request( + request_type=operations_pb2.DeleteOperationRequest, +): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type() + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request + ) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = Response() json_return_value = "" response_value.json = mock.Mock(return_value={}) response_value.status_code = 400 - response_value.request = mock.Mock() + response_value.request = Request() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_shared_regional_certificate_authority(request) + client.delete_operation(request) @pytest.mark.parametrize( "request_type", [ - memorystore.GetSharedRegionalCertificateAuthorityRequest, + operations_pb2.DeleteOperationRequest, dict, ], ) -def test_get_shared_regional_certificate_authority_rest_call_success(request_type): +def test_delete_operation_rest(request_type): client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/sharedRegionalCertificateAuthority" - } + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: + with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = memorystore.SharedRegionalCertificateAuthority( - name="name_value", - ) + return_value = None # 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 = memorystore.SharedRegionalCertificateAuthority.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_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_shared_regional_certificate_authority(request) - - # Establish that the response is the type that we expect. - assert isinstance(response, memorystore.SharedRegionalCertificateAuthority) - assert response.name == "name_value" - - -@pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_shared_regional_certificate_authority_rest_interceptors(null_interceptor): - transport = transports.MemorystoreRestTransport( - credentials=ga_credentials.AnonymousCredentials(), - interceptor=None - if null_interceptor - else transports.MemorystoreRestInterceptor(), - ) - client = MemorystoreClient(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.MemorystoreRestInterceptor, - "post_get_shared_regional_certificate_authority", - ) as post, - mock.patch.object( - transports.MemorystoreRestInterceptor, - "post_get_shared_regional_certificate_authority_with_metadata", - ) as post_with_metadata, - mock.patch.object( - transports.MemorystoreRestInterceptor, - "pre_get_shared_regional_certificate_authority", - ) as pre, - ): - pre.assert_not_called() - post.assert_not_called() - post_with_metadata.assert_not_called() - pb_message = memorystore.GetSharedRegionalCertificateAuthorityRequest.pb( - memorystore.GetSharedRegionalCertificateAuthorityRequest() - ) - 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 = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - return_value = memorystore.SharedRegionalCertificateAuthority.to_json( - memorystore.SharedRegionalCertificateAuthority() - ) - req.return_value.content = return_value - - request = memorystore.GetSharedRegionalCertificateAuthorityRequest() - metadata = [ - ("key", "val"), - ("cephalopod", "squid"), - ] - pre.return_value = request, metadata - post.return_value = memorystore.SharedRegionalCertificateAuthority() - post_with_metadata.return_value = ( - memorystore.SharedRegionalCertificateAuthority(), - metadata, - ) - client.get_shared_regional_certificate_authority( - request, - metadata=[ - ("key", "val"), - ("cephalopod", "squid"), - ], - ) + response = client.delete_operation(request) - pre.assert_called_once() - post.assert_called_once() - post_with_metadata.assert_called_once() + # Establish that the response is the type that we expect. + assert response is None -def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): +def test_get_operation_rest_bad_request( + request_type=operations_pb2.GetOperationRequest, +): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request + {"name": "projects/sample1/locations/sample2/operations/sample3"}, request ) # Mock the http request call within the method and fake a BadRequest error. @@ -7030,28 +21171,28 @@ def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationReq response_value.request = Request() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_location(request) + client.get_operation(request) @pytest.mark.parametrize( "request_type", [ - locations_pb2.GetLocationRequest, + operations_pb2.GetOperationRequest, dict, ], ) -def test_get_location_rest(request_type): +def test_get_operation_rest(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2"} + request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = locations_pb2.Location() + return_value = operations_pb2.Operation() # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -7062,21 +21203,23 @@ def test_get_location_rest(request_type): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_location(request) + response = client.get_operation(request) # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.Location) + assert isinstance(response, operations_pb2.Operation) -def test_list_locations_rest_bad_request( - request_type=locations_pb2.ListLocationsRequest, +def test_list_operations_rest_bad_request( + request_type=operations_pb2.ListOperationsRequest, ): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type() - request = json_format.ParseDict({"name": "projects/sample1"}, request) + request = json_format.ParseDict( + {"name": "projects/sample1/locations/sample2"}, request + ) # Mock the http request call within the method and fake a BadRequest error. with ( @@ -7091,28 +21234,28 @@ def test_list_locations_rest_bad_request( response_value.request = Request() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_locations(request) + client.list_operations(request) @pytest.mark.parametrize( "request_type", [ - locations_pb2.ListLocationsRequest, + operations_pb2.ListOperationsRequest, dict, ], ) -def test_list_locations_rest(request_type): +def test_list_operations_rest(request_type): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1"} + request_init = {"name": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # Designate an appropriate value for the returned response. - return_value = locations_pb2.ListLocationsResponse() + return_value = operations_pb2.ListOperationsResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() @@ -7123,369 +21266,456 @@ def test_list_locations_rest(request_type): req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_locations(request) + response = client.list_operations(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +def test_initialize_client_w_rest(): + client = MemorystoreClient( + 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_list_instances_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + client.list_instances(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListInstancesRequest() + 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_get_instance_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + client.get_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetInstanceRequest() + 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_create_instance_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + client.create_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.CreateInstanceRequest() + 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_update_instance_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + client.update_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.UpdateInstanceRequest() + 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_delete_instance_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + client.delete_instance(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteInstanceRequest() + 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_get_certificate_authority_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_certificate_authority), "__call__" + ) as call: + client.get_certificate_authority(request=None) - # Establish that the response is the type that we expect. - assert isinstance(response, locations_pb2.ListLocationsResponse) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetCertificateAuthorityRequest() + assert args[0] == request_msg -def test_cancel_operation_rest_bad_request( - request_type=operations_pb2.CancelOperationRequest, -): +# 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_shared_regional_certificate_authority_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.cancel_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_shared_regional_certificate_authority), "__call__" + ) as call: + client.get_shared_regional_certificate_authority(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.CancelOperationRequest, - dict, - ], -) -def test_cancel_operation_rest(request_type): + +# 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_reschedule_maintenance_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_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.cancel_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.reschedule_maintenance), "__call__" + ) as call: + client.reschedule_maintenance(request=None) - # Establish that the response is the type that we expect. - assert response is None + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.RescheduleMaintenanceRequest() + assert args[0] == request_msg -def test_delete_operation_rest_bad_request( - request_type=operations_pb2.DeleteOperationRequest, -): +# 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_backup_collections_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.list_backup_collections), "__call__" + ) as call: + client.list_backup_collections(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupCollectionsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.DeleteOperationRequest, - dict, - ], -) -def test_delete_operation_rest(request_type): + +# 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_backup_collection_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = None - - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_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.delete_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.get_backup_collection), "__call__" + ) as call: + client.get_backup_collection(request=None) - # Establish that the response is the type that we expect. - assert response is None + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupCollectionRequest() + assert args[0] == request_msg -def test_get_operation_rest_bad_request( - request_type=operations_pb2.GetOperationRequest, -): +# 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_backups_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2/operations/sample3"}, request - ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_operation(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + client.list_backups(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ListBackupsRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.GetOperationRequest, - dict, - ], -) -def test_get_operation_rest(request_type): + +# 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_backup_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2/operations/sample3"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + client.get_backup(request=None) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.GetBackupRequest() + assert args[0] == request_msg - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.get_operation(request) +# 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_delete_backup_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.Operation) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + client.delete_backup(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.DeleteBackupRequest() + assert args[0] == request_msg -def test_list_operations_rest_bad_request( - request_type=operations_pb2.ListOperationsRequest, -): +# 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_export_backup_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request = request_type() - request = json_format.ParseDict( - {"name": "projects/sample1/locations/sample2"}, request - ) - # Mock the http request call within the method and fake a BadRequest error. - with ( - mock.patch.object(Session, "request") as req, - pytest.raises(core_exceptions.BadRequest), - ): - # Wrap the value into a proper Response obj - response_value = Response() - json_return_value = "" - response_value.json = mock.Mock(return_value={}) - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_operations(request) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.export_backup), "__call__") as call: + client.export_backup(request=None) + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.ExportBackupRequest() + assert args[0] == request_msg -@pytest.mark.parametrize( - "request_type", - [ - operations_pb2.ListOperationsRequest, - dict, - ], -) -def test_list_operations_rest(request_type): + +# 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_backup_instance_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) - request_init = {"name": "projects/sample1/locations/sample2"} - request = request_type(**request_init) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.ListOperationsResponse() + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.backup_instance), "__call__") as call: + client.backup_instance(request=None) - # Wrap the value into a proper Response obj - response_value = mock.Mock() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value.content = json_return_value.encode("UTF-8") + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.BackupInstanceRequest() + assert args[0] == request_msg - req.return_value = response_value - req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - response = client.list_operations(request) +# 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_start_migration_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) - # Establish that the response is the type that we expect. - assert isinstance(response, operations_pb2.ListOperationsResponse) + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.start_migration), "__call__") as call: + client.start_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.StartMigrationRequest() + assert args[0] == request_msg -def test_initialize_client_w_rest(): +# 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_finish_migration_empty_call_rest(): client = MemorystoreClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", ) - assert client is not None + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.finish_migration), "__call__") as call: + client.finish_migration(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.FinishMigrationRequest() + 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_instances_empty_call_rest(): +def test_list_token_auth_users_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - client.list_instances(request=None) + with mock.patch.object( + type(client.transport.list_token_auth_users), "__call__" + ) as call: + client.list_token_auth_users(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.ListInstancesRequest() + request_msg = memorystore.ListTokenAuthUsersRequest() 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_get_instance_empty_call_rest(): +def test_get_token_auth_user_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: - client.get_instance(request=None) + with mock.patch.object( + type(client.transport.get_token_auth_user), "__call__" + ) as call: + client.get_token_auth_user(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetInstanceRequest() + request_msg = memorystore.GetTokenAuthUserRequest() 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_create_instance_empty_call_rest(): +def test_list_auth_tokens_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - client.create_instance(request=None) + with mock.patch.object(type(client.transport.list_auth_tokens), "__call__") as call: + client.list_auth_tokens(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.CreateInstanceRequest() + request_msg = memorystore.ListAuthTokensRequest() 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_update_instance_empty_call_rest(): +def test_get_auth_token_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: - client.update_instance(request=None) + with mock.patch.object(type(client.transport.get_auth_token), "__call__") as call: + client.get_auth_token(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.UpdateInstanceRequest() + request_msg = memorystore.GetAuthTokenRequest() 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_delete_instance_empty_call_rest(): +def test_add_token_auth_user_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: - client.delete_instance(request=None) + with mock.patch.object( + type(client.transport.add_token_auth_user), "__call__" + ) as call: + client.add_token_auth_user(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.DeleteInstanceRequest() + request_msg = memorystore.AddTokenAuthUserRequest() 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_get_certificate_authority_empty_call_rest(): +def test_delete_token_auth_user_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7493,20 +21723,39 @@ def test_get_certificate_authority_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_certificate_authority), "__call__" + type(client.transport.delete_token_auth_user), "__call__" ) as call: - client.get_certificate_authority(request=None) + client.delete_token_auth_user(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetCertificateAuthorityRequest() + request_msg = memorystore.DeleteTokenAuthUserRequest() 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_get_shared_regional_certificate_authority_empty_call_rest(): +def test_add_auth_token_empty_call_rest(): + client = MemorystoreClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.add_auth_token), "__call__") as call: + client.add_auth_token(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = memorystore.AddAuthTokenRequest() + 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_delete_auth_token_empty_call_rest(): client = MemorystoreClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -7514,14 +21763,14 @@ def test_get_shared_regional_certificate_authority_empty_call_rest(): # Mock the actual call, and fake the request. with mock.patch.object( - type(client.transport.get_shared_regional_certificate_authority), "__call__" + type(client.transport.delete_auth_token), "__call__" ) as call: - client.get_shared_regional_certificate_authority(request=None) + client.delete_auth_token(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = memorystore.GetSharedRegionalCertificateAuthorityRequest() + request_msg = memorystore.DeleteAuthTokenRequest() assert args[0] == request_msg @@ -7582,6 +21831,24 @@ def test_memorystore_base_transport(): "delete_instance", "get_certificate_authority", "get_shared_regional_certificate_authority", + "reschedule_maintenance", + "list_backup_collections", + "get_backup_collection", + "list_backups", + "get_backup", + "delete_backup", + "export_backup", + "backup_instance", + "start_migration", + "finish_migration", + "list_token_auth_users", + "get_token_auth_user", + "list_auth_tokens", + "get_auth_token", + "add_token_auth_user", + "delete_token_auth_user", + "add_auth_token", + "delete_auth_token", "get_location", "list_locations", "get_operation", @@ -7629,7 +21896,11 @@ def test_memorystore_base_transport_with_credentials_file(): load_creds.assert_called_once_with( "credentials.json", scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), quota_project_id="octopus", ) @@ -7655,7 +21926,11 @@ def test_memorystore_auth_adc(): MemorystoreClient() adc.assert_called_once_with( scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), quota_project_id=None, ) @@ -7675,7 +21950,11 @@ def test_memorystore_transport_auth_adc(transport_class): transport_class(quota_project_id="octopus", scopes=["1", "2"]) adc.assert_called_once_with( scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), quota_project_id="octopus", ) @@ -7728,7 +22007,11 @@ def test_memorystore_transport_create_channel(transport_class, grpc_helpers): credentials=creds, credentials_file=None, quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + default_scopes=( + "https://www.googleapis.com/auth/cloud-platform", + "https://www.googleapis.com/auth/memorystore.read-only", + "https://www.googleapis.com/auth/memorystore.read-write", + ), scopes=["1", "2"], default_host="memorystore.googleapis.com", ssl_credentials=None, @@ -7876,6 +22159,60 @@ def test_memorystore_client_transport_session_collision(transport_name): session1 = client1.transport.get_shared_regional_certificate_authority._session session2 = client2.transport.get_shared_regional_certificate_authority._session assert session1 != session2 + session1 = client1.transport.reschedule_maintenance._session + session2 = client2.transport.reschedule_maintenance._session + assert session1 != session2 + session1 = client1.transport.list_backup_collections._session + session2 = client2.transport.list_backup_collections._session + assert session1 != session2 + session1 = client1.transport.get_backup_collection._session + session2 = client2.transport.get_backup_collection._session + assert session1 != session2 + session1 = client1.transport.list_backups._session + session2 = client2.transport.list_backups._session + assert session1 != session2 + session1 = client1.transport.get_backup._session + session2 = client2.transport.get_backup._session + assert session1 != session2 + session1 = client1.transport.delete_backup._session + session2 = client2.transport.delete_backup._session + assert session1 != session2 + session1 = client1.transport.export_backup._session + session2 = client2.transport.export_backup._session + assert session1 != session2 + session1 = client1.transport.backup_instance._session + session2 = client2.transport.backup_instance._session + assert session1 != session2 + session1 = client1.transport.start_migration._session + session2 = client2.transport.start_migration._session + assert session1 != session2 + session1 = client1.transport.finish_migration._session + session2 = client2.transport.finish_migration._session + assert session1 != session2 + session1 = client1.transport.list_token_auth_users._session + session2 = client2.transport.list_token_auth_users._session + assert session1 != session2 + session1 = client1.transport.get_token_auth_user._session + session2 = client2.transport.get_token_auth_user._session + assert session1 != session2 + session1 = client1.transport.list_auth_tokens._session + session2 = client2.transport.list_auth_tokens._session + assert session1 != session2 + session1 = client1.transport.get_auth_token._session + session2 = client2.transport.get_auth_token._session + assert session1 != session2 + session1 = client1.transport.add_token_auth_user._session + session2 = client2.transport.add_token_auth_user._session + assert session1 != session2 + session1 = client1.transport.delete_token_auth_user._session + session2 = client2.transport.delete_token_auth_user._session + assert session1 != session2 + session1 = client1.transport.add_auth_token._session + session2 = client2.transport.add_auth_token._session + assert session1 != session2 + session1 = client1.transport.delete_auth_token._session + session2 = client2.transport.delete_auth_token._session + assert session1 != session2 def test_memorystore_grpc_transport_channel(): @@ -8031,6 +22368,97 @@ def test_memorystore_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client +def test_auth_token_path(): + project = "squid" + location = "clam" + instance = "whelk" + token_auth_user = "octopus" + auth_token = "oyster" + expected = "projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}/authTokens/{auth_token}".format( + project=project, + location=location, + instance=instance, + token_auth_user=token_auth_user, + auth_token=auth_token, + ) + actual = MemorystoreClient.auth_token_path( + project, location, instance, token_auth_user, auth_token + ) + assert expected == actual + + +def test_parse_auth_token_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "instance": "mussel", + "token_auth_user": "winkle", + "auth_token": "nautilus", + } + path = MemorystoreClient.auth_token_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_auth_token_path(path) + assert expected == actual + + +def test_backup_path(): + project = "scallop" + location = "abalone" + backup_collection = "squid" + backup = "clam" + expected = "projects/{project}/locations/{location}/backupCollections/{backup_collection}/backups/{backup}".format( + project=project, + location=location, + backup_collection=backup_collection, + backup=backup, + ) + actual = MemorystoreClient.backup_path(project, location, backup_collection, backup) + assert expected == actual + + +def test_parse_backup_path(): + expected = { + "project": "whelk", + "location": "octopus", + "backup_collection": "oyster", + "backup": "nudibranch", + } + path = MemorystoreClient.backup_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_backup_path(path) + assert expected == actual + + +def test_backup_collection_path(): + project = "cuttlefish" + location = "mussel" + backup_collection = "winkle" + expected = "projects/{project}/locations/{location}/backupCollections/{backup_collection}".format( + project=project, + location=location, + backup_collection=backup_collection, + ) + actual = MemorystoreClient.backup_collection_path( + project, location, backup_collection + ) + assert expected == actual + + +def test_parse_backup_collection_path(): + expected = { + "project": "nautilus", + "location": "scallop", + "backup_collection": "abalone", + } + path = MemorystoreClient.backup_collection_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_backup_collection_path(path) + assert expected == actual + + def test_ca_pool_path(): project = "squid" location = "clam" @@ -8083,10 +22511,73 @@ def test_parse_certificate_authority_path(): assert expected == actual -def test_forwarding_rule_path(): +def test_crypto_key_path(): project = "squid" - region = "clam" - forwarding_rule = "whelk" + location = "clam" + key_ring = "whelk" + crypto_key = "octopus" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + ) + actual = MemorystoreClient.crypto_key_path(project, location, key_ring, crypto_key) + assert expected == actual + + +def test_parse_crypto_key_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "key_ring": "cuttlefish", + "crypto_key": "mussel", + } + path = MemorystoreClient.crypto_key_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_crypto_key_path(path) + assert expected == actual + + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" + expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( + project=project, + location=location, + key_ring=key_ring, + crypto_key=crypto_key, + crypto_key_version=crypto_key_version, + ) + actual = MemorystoreClient.crypto_key_version_path( + project, location, key_ring, crypto_key, crypto_key_version + ) + assert expected == actual + + +def test_parse_crypto_key_version_path(): + expected = { + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", + } + path = MemorystoreClient.crypto_key_version_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_crypto_key_version_path(path) + assert expected == actual + + +def test_forwarding_rule_path(): + project = "cuttlefish" + region = "mussel" + forwarding_rule = "winkle" expected = ( "projects/{project}/regions/{region}/forwardingRules/{forwarding_rule}".format( project=project, @@ -8100,9 +22591,9 @@ def test_forwarding_rule_path(): def test_parse_forwarding_rule_path(): expected = { - "project": "octopus", - "region": "oyster", - "forwarding_rule": "nudibranch", + "project": "nautilus", + "region": "scallop", + "forwarding_rule": "abalone", } path = MemorystoreClient.forwarding_rule_path(**expected) @@ -8112,9 +22603,9 @@ def test_parse_forwarding_rule_path(): def test_instance_path(): - project = "cuttlefish" - location = "mussel" - instance = "winkle" + project = "squid" + location = "clam" + instance = "whelk" expected = "projects/{project}/locations/{location}/instances/{instance}".format( project=project, location=location, @@ -8126,9 +22617,9 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "nautilus", - "location": "scallop", - "instance": "abalone", + "project": "octopus", + "location": "oyster", + "instance": "nudibranch", } path = MemorystoreClient.instance_path(**expected) @@ -8138,8 +22629,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "squid" - network = "clam" + project = "cuttlefish" + network = "mussel" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -8150,8 +22641,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "whelk", - "network": "octopus", + "project": "winkle", + "network": "nautilus", } path = MemorystoreClient.network_path(**expected) @@ -8160,6 +22651,34 @@ def test_parse_network_path(): assert expected == actual +def test_network_attachment_path(): + project = "scallop" + region = "abalone" + network_attachment = "squid" + expected = "projects/{project}/regions/{region}/networkAttachments/{network_attachment}".format( + project=project, + region=region, + network_attachment=network_attachment, + ) + actual = MemorystoreClient.network_attachment_path( + project, region, network_attachment + ) + assert expected == actual + + +def test_parse_network_attachment_path(): + expected = { + "project": "clam", + "region": "whelk", + "network_attachment": "octopus", + } + path = MemorystoreClient.network_attachment_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_network_attachment_path(path) + assert expected == actual + + def test_service_attachment_path(): project = "oyster" region = "nudibranch" @@ -8213,8 +22732,39 @@ def test_parse_shared_regional_certificate_authority_path(): assert expected == actual +def test_token_auth_user_path(): + project = "whelk" + location = "octopus" + instance = "oyster" + token_auth_user = "nudibranch" + expected = "projects/{project}/locations/{location}/instances/{instance}/tokenAuthUsers/{token_auth_user}".format( + project=project, + location=location, + instance=instance, + token_auth_user=token_auth_user, + ) + actual = MemorystoreClient.token_auth_user_path( + project, location, instance, token_auth_user + ) + assert expected == actual + + +def test_parse_token_auth_user_path(): + expected = { + "project": "cuttlefish", + "location": "mussel", + "instance": "winkle", + "token_auth_user": "nautilus", + } + path = MemorystoreClient.token_auth_user_path(**expected) + + # Check that the path construction is reversible. + actual = MemorystoreClient.parse_token_auth_user_path(path) + assert expected == actual + + def test_common_billing_account_path(): - billing_account = "whelk" + billing_account = "scallop" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -8224,7 +22774,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "octopus", + "billing_account": "abalone", } path = MemorystoreClient.common_billing_account_path(**expected) @@ -8234,7 +22784,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "oyster" + folder = "squid" expected = "folders/{folder}".format( folder=folder, ) @@ -8244,7 +22794,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "nudibranch", + "folder": "clam", } path = MemorystoreClient.common_folder_path(**expected) @@ -8254,7 +22804,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "cuttlefish" + organization = "whelk" expected = "organizations/{organization}".format( organization=organization, ) @@ -8264,7 +22814,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "mussel", + "organization": "octopus", } path = MemorystoreClient.common_organization_path(**expected) @@ -8274,7 +22824,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "winkle" + project = "oyster" expected = "projects/{project}".format( project=project, ) @@ -8284,7 +22834,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "nautilus", + "project": "nudibranch", } path = MemorystoreClient.common_project_path(**expected) @@ -8294,8 +22844,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "scallop" - location = "abalone" + project = "cuttlefish" + location = "mussel" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -8306,8 +22856,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "squid", - "location": "clam", + "project": "winkle", + "location": "nautilus", } path = MemorystoreClient.common_location_path(**expected) diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py index c260d36f63a5..b26369987dca 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager/__init__.py @@ -43,6 +43,7 @@ DeleteSecretRequest, DestroySecretVersionRequest, DisableSecretVersionRequest, + EnableManagedRotationRequest, EnableSecretVersionRequest, GetSecretRequest, GetSecretVersionRequest, @@ -50,6 +51,7 @@ ListSecretsResponse, ListSecretVersionsRequest, ListSecretVersionsResponse, + RotateSecretRequest, UpdateSecretRequest, ) @@ -72,6 +74,7 @@ "DeleteSecretRequest", "DestroySecretVersionRequest", "DisableSecretVersionRequest", + "EnableManagedRotationRequest", "EnableSecretVersionRequest", "GetSecretRequest", "GetSecretVersionRequest", @@ -79,5 +82,6 @@ "ListSecretsResponse", "ListSecretVersionsRequest", "ListSecretVersionsResponse", + "RotateSecretRequest", "UpdateSecretRequest", ) diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py index 5370bcfc99d2..9769e64b95e9 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/__init__.py @@ -46,6 +46,7 @@ DeleteSecretRequest, DestroySecretVersionRequest, DisableSecretVersionRequest, + EnableManagedRotationRequest, EnableSecretVersionRequest, GetSecretRequest, GetSecretVersionRequest, @@ -53,6 +54,7 @@ ListSecretsResponse, ListSecretVersionsRequest, ListSecretVersionsResponse, + RotateSecretRequest, UpdateSecretRequest, ) @@ -150,6 +152,7 @@ def _get_version(dependency_name): "DeleteSecretRequest", "DestroySecretVersionRequest", "DisableSecretVersionRequest", + "EnableManagedRotationRequest", "EnableSecretVersionRequest", "GetSecretRequest", "GetSecretVersionRequest", @@ -159,6 +162,7 @@ def _get_version(dependency_name): "ListSecretsResponse", "Replication", "ReplicationStatus", + "RotateSecretRequest", "Rotation", "Secret", "SecretManagerServiceClient", diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_metadata.json b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_metadata.json index 115998dc2e86..cbf4657aff97 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_metadata.json +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/gapic_metadata.json @@ -40,6 +40,11 @@ "disable_secret_version" ] }, + "EnableManagedRotation": { + "methods": [ + "enable_managed_rotation" + ] + }, "EnableSecretVersion": { "methods": [ "enable_secret_version" @@ -70,6 +75,11 @@ "list_secrets" ] }, + "RotateSecret": { + "methods": [ + "rotate_secret" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -120,6 +130,11 @@ "disable_secret_version" ] }, + "EnableManagedRotation": { + "methods": [ + "enable_managed_rotation" + ] + }, "EnableSecretVersion": { "methods": [ "enable_secret_version" @@ -150,6 +165,11 @@ "list_secrets" ] }, + "RotateSecret": { + "methods": [ + "rotate_secret" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" @@ -200,6 +220,11 @@ "disable_secret_version" ] }, + "EnableManagedRotation": { + "methods": [ + "enable_managed_rotation" + ] + }, "EnableSecretVersion": { "methods": [ "enable_secret_version" @@ -230,6 +255,11 @@ "list_secrets" ] }, + "RotateSecret": { + "methods": [ + "rotate_secret" + ] + }, "SetIamPolicy": { "methods": [ "set_iam_policy" diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py index d5d6d8a9686f..7ee0c4c319af 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/async_client.py @@ -46,6 +46,7 @@ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.iam.v1.resource_policy_member_pb2 as resource_policy_member_pb2 # type: ignore import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -2145,6 +2146,262 @@ async def sample_test_iam_permissions(): # Done; return the response. return response + async def enable_managed_rotation( + self, + request: Optional[Union[service.EnableManagedRotationRequest, dict]] = None, + *, + parent: Optional[str] = None, + cloud_sql_single_user_credentials: Optional[ + service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.SecretVersion: + r"""Enables the managed rotation feature for a + [Secret][google.cloud.secretmanager.v1.Secret]. This method can + only be triggered once for a secret. In order to do further + rotations, RotateSecret should be used. This method will add a + secret version and update the password in Cloud SQL. + + .. 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 secretmanager_v1 + + async def sample_enable_managed_rotation(): + # Create a client + client = secretmanager_v1.SecretManagerServiceAsyncClient() + + # Initialize request argument(s) + cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials() + cloud_sql_single_user_credentials.instance_id = "instance_id_value" + cloud_sql_single_user_credentials.username = "username_value" + + request = secretmanager_v1.EnableManagedRotationRequest( + cloud_sql_single_user_credentials=cloud_sql_single_user_credentials, + parent="parent_value", + ) + + # Make the request + response = await client.enable_managed_rotation(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.secretmanager_v1.types.EnableManagedRotationRequest, dict]]): + The request object. Request message for + [SecretManagerService.EnableManagedRotation][google.cloud.secretmanager.v1.SecretManagerService.EnableManagedRotation]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to + associate with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*`` or + ``projects/*/locations/*/secrets/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cloud_sql_single_user_credentials (:class:`google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials`): + Credentials required for Cloud SQL DB + for Single user Managed Rotation. + + This corresponds to the ``cloud_sql_single_user_credentials`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.secretmanager_v1.types.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # 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 = [parent, cloud_sql_single_user_credentials] + 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, service.EnableManagedRotationRequest): + request = service.EnableManagedRotationRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cloud_sql_single_user_credentials is not None: + request.cloud_sql_single_user_credentials = ( + cloud_sql_single_user_credentials + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.enable_managed_rotation + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def rotate_secret( + self, + request: Optional[Union[service.RotateSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.SecretVersion: + r"""Do a managed rotation for a + [Secret][google.cloud.secretmanager.v1.Secret]. This can only be + triggered after Managed rotation has been enabled. This method + will add a secret version and update the password in Cloud SQL. + + .. 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 secretmanager_v1 + + async def sample_rotate_secret(): + # Create a client + client = secretmanager_v1.SecretManagerServiceAsyncClient() + + # Initialize request argument(s) + request = secretmanager_v1.RotateSecretRequest( + parent="parent_value", + ) + + # Make the request + response = await client.rotate_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.secretmanager_v1.types.RotateSecretRequest, dict]]): + The request object. Request message for + [SecretManagerService.RotateSecret][google.cloud.secretmanager.v1.SecretManagerService.RotateSecret]. + parent (:class:`str`): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to + associate with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*`` or + ``projects/*/locations/*/secrets/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.secretmanager_v1.types.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # 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 = [parent] + 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, service.RotateSecretRequest): + request = service.RotateSecretRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.rotate_secret + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def get_location( self, request: Optional[Union[locations_pb2.GetLocationRequest, dict]] = None, diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py index ae0a2cc6a252..e1663ef2ac1e 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/client.py @@ -63,6 +63,7 @@ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.iam.v1.resource_policy_member_pb2 as resource_policy_member_pb2 # type: ignore import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore @@ -2567,6 +2568,256 @@ def sample_test_iam_permissions(): # Done; return the response. return response + def enable_managed_rotation( + self, + request: Optional[Union[service.EnableManagedRotationRequest, dict]] = None, + *, + parent: Optional[str] = None, + cloud_sql_single_user_credentials: Optional[ + service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials + ] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.SecretVersion: + r"""Enables the managed rotation feature for a + [Secret][google.cloud.secretmanager.v1.Secret]. This method can + only be triggered once for a secret. In order to do further + rotations, RotateSecret should be used. This method will add a + secret version and update the password in Cloud SQL. + + .. 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 secretmanager_v1 + + def sample_enable_managed_rotation(): + # Create a client + client = secretmanager_v1.SecretManagerServiceClient() + + # Initialize request argument(s) + cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials() + cloud_sql_single_user_credentials.instance_id = "instance_id_value" + cloud_sql_single_user_credentials.username = "username_value" + + request = secretmanager_v1.EnableManagedRotationRequest( + cloud_sql_single_user_credentials=cloud_sql_single_user_credentials, + parent="parent_value", + ) + + # Make the request + response = client.enable_managed_rotation(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.secretmanager_v1.types.EnableManagedRotationRequest, dict]): + The request object. Request message for + [SecretManagerService.EnableManagedRotation][google.cloud.secretmanager.v1.SecretManagerService.EnableManagedRotation]. + parent (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to + associate with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*`` or + ``projects/*/locations/*/secrets/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + cloud_sql_single_user_credentials (google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials): + Credentials required for Cloud SQL DB + for Single user Managed Rotation. + + This corresponds to the ``cloud_sql_single_user_credentials`` 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.secretmanager_v1.types.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # 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 = [parent, cloud_sql_single_user_credentials] + 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, service.EnableManagedRotationRequest): + request = service.EnableManagedRotationRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + if cloud_sql_single_user_credentials is not None: + request.cloud_sql_single_user_credentials = ( + cloud_sql_single_user_credentials + ) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.enable_managed_rotation] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def rotate_secret( + self, + request: Optional[Union[service.RotateSecretRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.SecretVersion: + r"""Do a managed rotation for a + [Secret][google.cloud.secretmanager.v1.Secret]. This can only be + triggered after Managed rotation has been enabled. This method + will add a secret version and update the password in Cloud SQL. + + .. 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 secretmanager_v1 + + def sample_rotate_secret(): + # Create a client + client = secretmanager_v1.SecretManagerServiceClient() + + # Initialize request argument(s) + request = secretmanager_v1.RotateSecretRequest( + parent="parent_value", + ) + + # Make the request + response = client.rotate_secret(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.secretmanager_v1.types.RotateSecretRequest, dict]): + The request object. Request message for + [SecretManagerService.RotateSecret][google.cloud.secretmanager.v1.SecretManagerService.RotateSecret]. + parent (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to + associate with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*`` or + ``projects/*/locations/*/secrets/*``. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, 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.secretmanager_v1.types.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + # 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 = [parent] + 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, service.RotateSecretRequest): + request = service.RotateSecretRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.rotate_secret] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "SecretManagerServiceClient": return self diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py index c917e73efde8..d0a4ec2c019d 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/base.py @@ -231,6 +231,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.enable_managed_rotation: gapic_v1.method.wrap_method( + self.enable_managed_rotation, + default_timeout=None, + client_info=client_info, + ), + self.rotate_secret: gapic_v1.method.wrap_method( + self.rotate_secret, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -395,6 +405,24 @@ def test_iam_permissions( ]: raise NotImplementedError() + @property + def enable_managed_rotation( + self, + ) -> Callable[ + [service.EnableManagedRotationRequest], + Union[resources.SecretVersion, Awaitable[resources.SecretVersion]], + ]: + raise NotImplementedError() + + @property + def rotate_secret( + self, + ) -> Callable[ + [service.RotateSecretRequest], + Union[resources.SecretVersion, Awaitable[resources.SecretVersion]], + ]: + raise NotImplementedError() + @property def get_location( self, diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py index 9afebbc478d4..51530553e705 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc.py @@ -785,6 +785,65 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + @property + def enable_managed_rotation( + self, + ) -> Callable[[service.EnableManagedRotationRequest], resources.SecretVersion]: + r"""Return a callable for the enable managed rotation method over gRPC. + + Enables the managed rotation feature for a + [Secret][google.cloud.secretmanager.v1.Secret]. This method can + only be triggered once for a secret. In order to do further + rotations, RotateSecret should be used. This method will add a + secret version and update the password in Cloud SQL. + + Returns: + Callable[[~.EnableManagedRotationRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_managed_rotation" not in self._stubs: + self._stubs["enable_managed_rotation"] = self._logged_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/EnableManagedRotation", + request_serializer=service.EnableManagedRotationRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["enable_managed_rotation"] + + @property + def rotate_secret( + self, + ) -> Callable[[service.RotateSecretRequest], resources.SecretVersion]: + r"""Return a callable for the rotate secret method over gRPC. + + Do a managed rotation for a + [Secret][google.cloud.secretmanager.v1.Secret]. This can only be + triggered after Managed rotation has been enabled. This method + will add a secret version and update the password in Cloud SQL. + + Returns: + Callable[[~.RotateSecretRequest], + ~.SecretVersion]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "rotate_secret" not in self._stubs: + self._stubs["rotate_secret"] = self._logged_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/RotateSecret", + request_serializer=service.RotateSecretRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["rotate_secret"] + def close(self): self._logged_channel.close() diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py index 7b635ce6cd36..fb45b3337f4d 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/grpc_asyncio.py @@ -809,6 +809,67 @@ def test_iam_permissions( ) return self._stubs["test_iam_permissions"] + @property + def enable_managed_rotation( + self, + ) -> Callable[ + [service.EnableManagedRotationRequest], Awaitable[resources.SecretVersion] + ]: + r"""Return a callable for the enable managed rotation method over gRPC. + + Enables the managed rotation feature for a + [Secret][google.cloud.secretmanager.v1.Secret]. This method can + only be triggered once for a secret. In order to do further + rotations, RotateSecret should be used. This method will add a + secret version and update the password in Cloud SQL. + + Returns: + Callable[[~.EnableManagedRotationRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "enable_managed_rotation" not in self._stubs: + self._stubs["enable_managed_rotation"] = self._logged_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/EnableManagedRotation", + request_serializer=service.EnableManagedRotationRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["enable_managed_rotation"] + + @property + def rotate_secret( + self, + ) -> Callable[[service.RotateSecretRequest], Awaitable[resources.SecretVersion]]: + r"""Return a callable for the rotate secret method over gRPC. + + Do a managed rotation for a + [Secret][google.cloud.secretmanager.v1.Secret]. This can only be + triggered after Managed rotation has been enabled. This method + will add a secret version and update the password in Cloud SQL. + + Returns: + Callable[[~.RotateSecretRequest], + Awaitable[~.SecretVersion]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "rotate_secret" not in self._stubs: + self._stubs["rotate_secret"] = self._logged_channel.unary_unary( + "/google.cloud.secretmanager.v1.SecretManagerService/RotateSecret", + request_serializer=service.RotateSecretRequest.serialize, + response_deserializer=resources.SecretVersion.deserialize, + ) + return self._stubs["rotate_secret"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -897,6 +958,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.enable_managed_rotation: self._wrap_method( + self.enable_managed_rotation, + default_timeout=None, + client_info=client_info, + ), + self.rotate_secret: self._wrap_method( + self.rotate_secret, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest.py index 6beaf1c51c28..982e74c5a783 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest.py @@ -120,6 +120,14 @@ def post_disable_secret_version(self, response): logging.log(f"Received response: {response}") return response + def pre_enable_managed_rotation(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_enable_managed_rotation(self, response): + logging.log(f"Received response: {response}") + return response + def pre_enable_secret_version(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -168,6 +176,14 @@ def post_list_secret_versions(self, response): logging.log(f"Received response: {response}") return response + def pre_rotate_secret(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_rotate_secret(self, response): + logging.log(f"Received response: {response}") + return response + def pre_set_iam_policy(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -448,6 +464,54 @@ def post_disable_secret_version_with_metadata( """ return response, metadata + def pre_enable_managed_rotation( + self, + request: service.EnableManagedRotationRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[ + service.EnableManagedRotationRequest, Sequence[Tuple[str, Union[str, bytes]]] + ]: + """Pre-rpc interceptor for enable_managed_rotation + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecretManagerService server. + """ + return request, metadata + + def post_enable_managed_rotation( + self, response: resources.SecretVersion + ) -> resources.SecretVersion: + """Post-rpc interceptor for enable_managed_rotation + + DEPRECATED. Please use the `post_enable_managed_rotation_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecretManagerService server but before + it is returned to user code. This `post_enable_managed_rotation` interceptor runs + before the `post_enable_managed_rotation_with_metadata` interceptor. + """ + return response + + def post_enable_managed_rotation_with_metadata( + self, + response: resources.SecretVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.SecretVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for enable_managed_rotation + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecretManagerService server but before it is returned to user code. + + We recommend only using this `post_enable_managed_rotation_with_metadata` + interceptor in new development instead of the `post_enable_managed_rotation` interceptor. + When both interceptors are used, this `post_enable_managed_rotation_with_metadata` interceptor runs after the + `post_enable_managed_rotation` interceptor. The (possibly modified) response returned by + `post_enable_managed_rotation` will be passed to + `post_enable_managed_rotation_with_metadata`. + """ + return response, metadata + def pre_enable_secret_version( self, request: service.EnableSecretVersionRequest, @@ -730,6 +794,52 @@ def post_list_secret_versions_with_metadata( """ return response, metadata + def pre_rotate_secret( + self, + request: service.RotateSecretRequest, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[service.RotateSecretRequest, Sequence[Tuple[str, Union[str, bytes]]]]: + """Pre-rpc interceptor for rotate_secret + + Override in a subclass to manipulate the request or metadata + before they are sent to the SecretManagerService server. + """ + return request, metadata + + def post_rotate_secret( + self, response: resources.SecretVersion + ) -> resources.SecretVersion: + """Post-rpc interceptor for rotate_secret + + DEPRECATED. Please use the `post_rotate_secret_with_metadata` + interceptor instead. + + Override in a subclass to read or manipulate the response + after it is returned by the SecretManagerService server but before + it is returned to user code. This `post_rotate_secret` interceptor runs + before the `post_rotate_secret_with_metadata` interceptor. + """ + return response + + def post_rotate_secret_with_metadata( + self, + response: resources.SecretVersion, + metadata: Sequence[Tuple[str, Union[str, bytes]]], + ) -> Tuple[resources.SecretVersion, Sequence[Tuple[str, Union[str, bytes]]]]: + """Post-rpc interceptor for rotate_secret + + Override in a subclass to read or manipulate the response or metadata after it + is returned by the SecretManagerService server but before it is returned to user code. + + We recommend only using this `post_rotate_secret_with_metadata` + interceptor in new development instead of the `post_rotate_secret` interceptor. + When both interceptors are used, this `post_rotate_secret_with_metadata` interceptor runs after the + `post_rotate_secret` interceptor. The (possibly modified) response returned by + `post_rotate_secret` will be passed to + `post_rotate_secret_with_metadata`. + """ + return response, metadata + def pre_set_iam_policy( self, request: iam_policy_pb2.SetIamPolicyRequest, @@ -1905,6 +2015,162 @@ def __call__( ) return resp + class _EnableManagedRotation( + _BaseSecretManagerServiceRestTransport._BaseEnableManagedRotation, + SecretManagerServiceRestStub, + ): + def __hash__(self): + return hash("SecretManagerServiceRestTransport.EnableManagedRotation") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: service.EnableManagedRotationRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.SecretVersion: + r"""Call the enable managed rotation method over HTTP. + + Args: + request (~.service.EnableManagedRotationRequest): + The request object. Request message for + [SecretManagerService.EnableManagedRotation][google.cloud.secretmanager.v1.SecretManagerService.EnableManagedRotation]. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + + http_options = _BaseSecretManagerServiceRestTransport._BaseEnableManagedRotation._get_http_options() + + request, metadata = self._interceptor.pre_enable_managed_rotation( + request, metadata + ) + transcoded_request = _BaseSecretManagerServiceRestTransport._BaseEnableManagedRotation._get_transcoded_request( + http_options, request + ) + + body = _BaseSecretManagerServiceRestTransport._BaseEnableManagedRotation._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecretManagerServiceRestTransport._BaseEnableManagedRotation._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.secretmanager_v1.SecretManagerServiceClient.EnableManagedRotation", + extra={ + "serviceName": "google.cloud.secretmanager.v1.SecretManagerService", + "rpcName": "EnableManagedRotation", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = ( + SecretManagerServiceRestTransport._EnableManagedRotation._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.SecretVersion() + pb_resp = resources.SecretVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_enable_managed_rotation(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_enable_managed_rotation_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.SecretVersion.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.secretmanager_v1.SecretManagerServiceClient.enable_managed_rotation", + extra={ + "serviceName": "google.cloud.secretmanager.v1.SecretManagerService", + "rpcName": "EnableManagedRotation", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _EnableSecretVersion( _BaseSecretManagerServiceRestTransport._BaseEnableSecretVersion, SecretManagerServiceRestStub, @@ -2878,6 +3144,158 @@ def __call__( ) return resp + class _RotateSecret( + _BaseSecretManagerServiceRestTransport._BaseRotateSecret, + SecretManagerServiceRestStub, + ): + def __hash__(self): + return hash("SecretManagerServiceRestTransport.RotateSecret") + + @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), + data=body, + ) + return response + + def __call__( + self, + request: service.RotateSecretRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), + ) -> resources.SecretVersion: + r"""Call the rotate secret method over HTTP. + + Args: + request (~.service.RotateSecretRequest): + The request object. Request message for + [SecretManagerService.RotateSecret][google.cloud.secretmanager.v1.SecretManagerService.RotateSecret]. + 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: + ~.resources.SecretVersion: + A secret version resource in the + Secret Manager API. + + """ + + http_options = _BaseSecretManagerServiceRestTransport._BaseRotateSecret._get_http_options() + + request, metadata = self._interceptor.pre_rotate_secret(request, metadata) + transcoded_request = _BaseSecretManagerServiceRestTransport._BaseRotateSecret._get_transcoded_request( + http_options, request + ) + + body = _BaseSecretManagerServiceRestTransport._BaseRotateSecret._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseSecretManagerServiceRestTransport._BaseRotateSecret._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.secretmanager_v1.SecretManagerServiceClient.RotateSecret", + extra={ + "serviceName": "google.cloud.secretmanager.v1.SecretManagerService", + "rpcName": "RotateSecret", + "httpRequest": http_request, + "metadata": http_request["headers"], + }, + ) + + # Send the request + response = SecretManagerServiceRestTransport._RotateSecret._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.SecretVersion() + pb_resp = resources.SecretVersion.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + + resp = self._interceptor.post_rotate_secret(resp) + response_metadata = [(k, str(v)) for k, v in response.headers.items()] + resp, _ = self._interceptor.post_rotate_secret_with_metadata( + resp, response_metadata + ) + if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( + logging.DEBUG + ): # pragma: NO COVER + try: + response_payload = resources.SecretVersion.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.secretmanager_v1.SecretManagerServiceClient.rotate_secret", + extra={ + "serviceName": "google.cloud.secretmanager.v1.SecretManagerService", + "rpcName": "RotateSecret", + "metadata": http_response["headers"], + "httpResponse": http_response, + }, + ) + return resp + class _SetIamPolicy( _BaseSecretManagerServiceRestTransport._BaseSetIamPolicy, SecretManagerServiceRestStub, @@ -3460,6 +3878,14 @@ def disable_secret_version( # In C++ this would require a dynamic_cast return self._DisableSecretVersion(self._session, self._host, self._interceptor) # type: ignore + @property + def enable_managed_rotation( + self, + ) -> Callable[[service.EnableManagedRotationRequest], resources.SecretVersion]: + # 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._EnableManagedRotation(self._session, self._host, self._interceptor) # type: ignore + @property def enable_secret_version( self, @@ -3508,6 +3934,14 @@ def list_secret_versions( # In C++ this would require a dynamic_cast return self._ListSecretVersions(self._session, self._host, self._interceptor) # type: ignore + @property + def rotate_secret( + self, + ) -> Callable[[service.RotateSecretRequest], resources.SecretVersion]: + # 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._RotateSecret(self._session, self._host, self._interceptor) # type: ignore + @property def set_iam_policy( self, diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest_base.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest_base.py index 790d407a7ca7..ac598ddc4a2f 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest_base.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/services/secret_manager_service/transports/rest_base.py @@ -443,6 +443,68 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseEnableManagedRotation: + 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": "post", + "uri": "/v1/{parent=projects/*/secrets/*}:enableManagedRotation", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/secrets/*}:enableManagedRotation", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.EnableManagedRotationRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSecretManagerServiceRestTransport._BaseEnableManagedRotation._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseEnableSecretVersion: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -760,6 +822,68 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseRotateSecret: + 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": "post", + "uri": "/v1/{parent=projects/*/secrets/*}:rotateSecret", + "body": "*", + }, + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/secrets/*}:rotateSecret", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.RotateSecretRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseSecretManagerServiceRestTransport._BaseRotateSecret._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseSetIamPolicy: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py index f81938bed583..49146e3f6fef 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/__init__.py @@ -32,6 +32,7 @@ DeleteSecretRequest, DestroySecretVersionRequest, DisableSecretVersionRequest, + EnableManagedRotationRequest, EnableSecretVersionRequest, GetSecretRequest, GetSecretVersionRequest, @@ -39,6 +40,7 @@ ListSecretsResponse, ListSecretVersionsRequest, ListSecretVersionsResponse, + RotateSecretRequest, UpdateSecretRequest, ) @@ -59,6 +61,7 @@ "DeleteSecretRequest", "DestroySecretVersionRequest", "DisableSecretVersionRequest", + "EnableManagedRotationRequest", "EnableSecretVersionRequest", "GetSecretRequest", "GetSecretVersionRequest", @@ -66,5 +69,6 @@ "ListSecretsResponse", "ListSecretVersionsRequest", "ListSecretVersionsResponse", + "RotateSecretRequest", "UpdateSecretRequest", ) diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py index a718b05511b4..a5b8abee7a51 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/resources.py @@ -17,8 +17,10 @@ from typing import MutableMapping, MutableSequence +import google.iam.v1.resource_policy_member_pb2 as resource_policy_member_pb2 # type: ignore import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore import proto # type: ignore __protobuf__ = proto.module( @@ -167,8 +169,51 @@ class Secret(proto.Message): Tags can be used to control policy evaluation for the resource. + secret_type (google.cloud.secretmanager_v1.types.Secret.SecretType): + Optional. Immutable. This defines the type of the secret. + Enforces certain structural requirements on the + [SecretVersions][google.cloud.secretmanager.v1.SecretVersion]. + For secret of type UNSPECIFIED, the SecretVersions can be of + any type. + policy_member (google.iam.v1.resource_policy_member_pb2.ResourcePolicyMember): + Output only. Defines the policy member for + the secret. This will be used to check if the + caller has the permission to perform certain + operations on the typed secret. """ + class SecretType(proto.Enum): + r"""This defines the various values of the type of secret can be. + + Values: + SECRET_TYPE_UNSPECIFIED (0): + Applicable to all secrets which do not have + any restriction on the SecretVersions. + CLOUD_SQL_DB_CREDENTIALS (1): + Applicable to secrets which are used for the + managed rotation feature for Cloud SQL Single + User. + ACCESS_KEY (2): + Applicable to secrets where the payload + contains an access key. + CERTIFICATE (3): + Applicable to secrets where the payload + contains a certificate. + OTHER_DB_CREDENTIALS (4): + Applicable to secrets where the payload + contains database credentials. + OTHER (50): + Applicable to secrets whose type doesn't + belong to any of the above defined types. + """ + + SECRET_TYPE_UNSPECIFIED = 0 + CLOUD_SQL_DB_CREDENTIALS = 1 + ACCESS_KEY = 2 + CERTIFICATE = 3 + OTHER_DB_CREDENTIALS = 4 + OTHER = 50 + name: str = proto.Field( proto.STRING, number=1, @@ -239,6 +284,16 @@ class Secret(proto.Message): proto.STRING, number=16, ) + secret_type: SecretType = proto.Field( + proto.ENUM, + number=17, + enum=SecretType, + ) + policy_member: resource_policy_member_pb2.ResourcePolicyMember = proto.Field( + proto.MESSAGE, + number=18, + message=resource_policy_member_pb2.ResourcePolicyMember, + ) class SecretVersion(proto.Message): @@ -711,8 +766,62 @@ class Rotation(proto.Message): [next_rotation_time][google.cloud.secretmanager.v1.Rotation.next_rotation_time] will be advanced by this period when the service automatically sends rotation notifications. + managed_rotation_status (google.cloud.secretmanager_v1.types.Rotation.ManagedRotationStatus): + Output only. The current status of the + managed rotation. This field is only applicable + to Typed Secrets. This field is set by the + service and cannot be set by the user. """ + class ManagedRotationStatus(proto.Message): + r"""Represents the status of a managed rotation. + + This is applicable only to Typed Secrets. It indicates whether + the rotation is active and any errors that may have occurred + during the asynchronous managed rotation. + + Attributes: + state (google.cloud.secretmanager_v1.types.Rotation.ManagedRotationStatus.State): + Output only. Indicates whether the Managed + Rotation is active or not. + error (google.rpc.status_pb2.Status): + Output only. Displays customer-facing issues + that occurred during an asynchronous managed + rotation. For example, if there are some + permission errors. + """ + + class State(proto.Enum): + r"""This defines the various states in which the managed rotation + can be. + + Values: + STATE_UNSPECIFIED (0): + Not specified. This value is unused and + invalid. + ACTIVE (1): + Indicates that the Managed rotation is + ACTIVE. + INACTIVE (2): + Indicates that the Managed rotation is + INACTIVE. + """ + + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + state: "Rotation.ManagedRotationStatus.State" = proto.Field( + proto.ENUM, + number=1, + enum="Rotation.ManagedRotationStatus.State", + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=2, + message=status_pb2.Status, + ) + next_rotation_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=1, @@ -723,6 +832,11 @@ class Rotation(proto.Message): number=2, message=duration_pb2.Duration, ) + managed_rotation_status: ManagedRotationStatus = proto.Field( + proto.MESSAGE, + number=3, + message=ManagedRotationStatus, + ) class SecretPayload(proto.Message): diff --git a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py index 034548f391d5..717dc0559ebf 100644 --- a/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py +++ b/packages/google-cloud-secret-manager/google/cloud/secretmanager_v1/types/service.py @@ -29,6 +29,8 @@ "ListSecretsResponse", "CreateSecretRequest", "AddSecretVersionRequest", + "EnableManagedRotationRequest", + "RotateSecretRequest", "GetSecretRequest", "ListSecretVersionsRequest", "ListSecretVersionsResponse", @@ -192,6 +194,89 @@ class AddSecretVersionRequest(proto.Message): ) +class EnableManagedRotationRequest(proto.Message): + r"""Request message for + [SecretManagerService.EnableManagedRotation][google.cloud.secretmanager.v1.SecretManagerService.EnableManagedRotation]. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + parent (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to associate + with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*`` or + ``projects/*/locations/*/secrets/*``. + cloud_sql_single_user_credentials (google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials): + Credentials required for Cloud SQL DB for + Single user Managed Rotation. + + This field is a member of `oneof`_ ``credentials``. + """ + + class CloudSQLSingleUserCredentials(proto.Message): + r"""These are the credentials required for Cloud SQL DB for + Single user Managed Rotation. + + Attributes: + instance_id (str): + Required. Instance ID of the Cloud SQL + instance. + username (str): + Required. Username of the Cloud SQL instance. + password (str): + Optional. Password of the Cloud SQL instance. + If this is not provided, a random password will + be generated. + """ + + instance_id: str = proto.Field( + proto.STRING, + number=1, + ) + username: str = proto.Field( + proto.STRING, + number=2, + ) + password: str = proto.Field( + proto.STRING, + number=3, + ) + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + cloud_sql_single_user_credentials: CloudSQLSingleUserCredentials = proto.Field( + proto.MESSAGE, + number=2, + oneof="credentials", + message=CloudSQLSingleUserCredentials, + ) + + +class RotateSecretRequest(proto.Message): + r"""Request message for + [SecretManagerService.RotateSecret][google.cloud.secretmanager.v1.SecretManagerService.RotateSecret]. + + Attributes: + parent (str): + Required. The resource name of the + [Secret][google.cloud.secretmanager.v1.Secret] to associate + with the + [SecretVersion][google.cloud.secretmanager.v1.SecretVersion] + in the format ``projects/*/secrets/*`` or + ``projects/*/locations/*/secrets/*``. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + + class GetSecretRequest(proto.Message): r"""Request message for [SecretManagerService.GetSecret][google.cloud.secretmanager.v1.SecretManagerService.GetSecret]. diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py new file mode 100644 index 000000000000..0fe0148061bd --- /dev/null +++ b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 EnableManagedRotation +# 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-secret-manager + + +# [START secretmanager_v1_generated_SecretManagerService_EnableManagedRotation_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import secretmanager_v1 + + +async def sample_enable_managed_rotation(): + # Create a client + client = secretmanager_v1.SecretManagerServiceAsyncClient() + + # Initialize request argument(s) + cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials() + cloud_sql_single_user_credentials.instance_id = "instance_id_value" + cloud_sql_single_user_credentials.username = "username_value" + + request = secretmanager_v1.EnableManagedRotationRequest( + cloud_sql_single_user_credentials=cloud_sql_single_user_credentials, + parent="parent_value", + ) + + # Make the request + response = await client.enable_managed_rotation(request=request) + + # Handle the response + print(response) + + +# [END secretmanager_v1_generated_SecretManagerService_EnableManagedRotation_async] diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py new file mode 100644 index 000000000000..d8a702d5cfaf --- /dev/null +++ b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 EnableManagedRotation +# 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-secret-manager + + +# [START secretmanager_v1_generated_SecretManagerService_EnableManagedRotation_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 secretmanager_v1 + + +def sample_enable_managed_rotation(): + # Create a client + client = secretmanager_v1.SecretManagerServiceClient() + + # Initialize request argument(s) + cloud_sql_single_user_credentials = secretmanager_v1.CloudSQLSingleUserCredentials() + cloud_sql_single_user_credentials.instance_id = "instance_id_value" + cloud_sql_single_user_credentials.username = "username_value" + + request = secretmanager_v1.EnableManagedRotationRequest( + cloud_sql_single_user_credentials=cloud_sql_single_user_credentials, + parent="parent_value", + ) + + # Make the request + response = client.enable_managed_rotation(request=request) + + # Handle the response + print(response) + + +# [END secretmanager_v1_generated_SecretManagerService_EnableManagedRotation_sync] diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_rotate_secret_async.py b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_rotate_secret_async.py new file mode 100644 index 000000000000..ab2cff4ede74 --- /dev/null +++ b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_rotate_secret_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 RotateSecret +# 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-secret-manager + + +# [START secretmanager_v1_generated_SecretManagerService_RotateSecret_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import secretmanager_v1 + + +async def sample_rotate_secret(): + # Create a client + client = secretmanager_v1.SecretManagerServiceAsyncClient() + + # Initialize request argument(s) + request = secretmanager_v1.RotateSecretRequest( + parent="parent_value", + ) + + # Make the request + response = await client.rotate_secret(request=request) + + # Handle the response + print(response) + + +# [END secretmanager_v1_generated_SecretManagerService_RotateSecret_async] diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_rotate_secret_sync.py b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_rotate_secret_sync.py new file mode 100644 index 000000000000..bfc77f78bd96 --- /dev/null +++ b/packages/google-cloud-secret-manager/samples/generated_samples/secretmanager_v1_generated_secret_manager_service_rotate_secret_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 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 RotateSecret +# 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-secret-manager + + +# [START secretmanager_v1_generated_SecretManagerService_RotateSecret_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 secretmanager_v1 + + +def sample_rotate_secret(): + # Create a client + client = secretmanager_v1.SecretManagerServiceClient() + + # Initialize request argument(s) + request = secretmanager_v1.RotateSecretRequest( + parent="parent_value", + ) + + # Make the request + response = client.rotate_secret(request=request) + + # Handle the response + print(response) + + +# [END secretmanager_v1_generated_SecretManagerService_RotateSecret_sync] diff --git a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json index dad4ceff0bc6..dad2491d8a9c 100644 --- a/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json +++ b/packages/google-cloud-secret-manager/samples/generated_samples/snippet_metadata_google.cloud.secretmanager.v1.json @@ -995,6 +995,175 @@ ], "title": "secretmanager_v1_generated_secret_manager_service_disable_secret_version_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceAsyncClient", + "shortName": "SecretManagerServiceAsyncClient" + }, + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceAsyncClient.enable_managed_rotation", + "method": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService.EnableManagedRotation", + "service": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService", + "shortName": "SecretManagerService" + }, + "shortName": "EnableManagedRotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.secretmanager_v1.types.EnableManagedRotationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cloud_sql_single_user_credentials", + "type": "google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.secretmanager_v1.types.SecretVersion", + "shortName": "enable_managed_rotation" + }, + "description": "Sample for EnableManagedRotation", + "file": "secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "secretmanager_v1_generated_SecretManagerService_EnableManagedRotation_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceClient", + "shortName": "SecretManagerServiceClient" + }, + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceClient.enable_managed_rotation", + "method": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService.EnableManagedRotation", + "service": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService", + "shortName": "SecretManagerService" + }, + "shortName": "EnableManagedRotation" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.secretmanager_v1.types.EnableManagedRotationRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "cloud_sql_single_user_credentials", + "type": "google.cloud.secretmanager_v1.types.EnableManagedRotationRequest.CloudSQLSingleUserCredentials" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, Union[str, bytes]]]" + } + ], + "resultType": "google.cloud.secretmanager_v1.types.SecretVersion", + "shortName": "enable_managed_rotation" + }, + "description": "Sample for EnableManagedRotation", + "file": "secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "secretmanager_v1_generated_SecretManagerService_EnableManagedRotation_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 50, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 51, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "secretmanager_v1_generated_secret_manager_service_enable_managed_rotation_sync.py" + }, { "canonical": true, "clientMethod": { @@ -1953,6 +2122,167 @@ ], "title": "secretmanager_v1_generated_secret_manager_service_list_secrets_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceAsyncClient", + "shortName": "SecretManagerServiceAsyncClient" + }, + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceAsyncClient.rotate_secret", + "method": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService.RotateSecret", + "service": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService", + "shortName": "SecretManagerService" + }, + "shortName": "RotateSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.secretmanager_v1.types.RotateSecretRequest" + }, + { + "name": "parent", + "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.secretmanager_v1.types.SecretVersion", + "shortName": "rotate_secret" + }, + "description": "Sample for RotateSecret", + "file": "secretmanager_v1_generated_secret_manager_service_rotate_secret_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "secretmanager_v1_generated_SecretManagerService_RotateSecret_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "secretmanager_v1_generated_secret_manager_service_rotate_secret_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceClient", + "shortName": "SecretManagerServiceClient" + }, + "fullName": "google.cloud.secretmanager_v1.SecretManagerServiceClient.rotate_secret", + "method": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService.RotateSecret", + "service": { + "fullName": "google.cloud.secretmanager.v1.SecretManagerService", + "shortName": "SecretManagerService" + }, + "shortName": "RotateSecret" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.secretmanager_v1.types.RotateSecretRequest" + }, + { + "name": "parent", + "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.secretmanager_v1.types.SecretVersion", + "shortName": "rotate_secret" + }, + "description": "Sample for RotateSecret", + "file": "secretmanager_v1_generated_secret_manager_service_rotate_secret_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "secretmanager_v1_generated_SecretManagerService_RotateSecret_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "secretmanager_v1_generated_secret_manager_service_rotate_secret_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py b/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py index 5fd3db94d792..7d2508ce774d 100644 --- a/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py +++ b/packages/google-cloud-secret-manager/tests/unit/gapic/secretmanager_v1/test_secret_manager_service.py @@ -42,9 +42,12 @@ import google.iam.v1.iam_policy_pb2 as iam_policy_pb2 # type: ignore import google.iam.v1.options_pb2 as options_pb2 # type: ignore import google.iam.v1.policy_pb2 as policy_pb2 # type: ignore +import google.iam.v1.resource_policy_member_pb2 as resource_policy_member_pb2 # type: ignore +import google.protobuf.any_pb2 as any_pb2 # type: ignore import google.protobuf.duration_pb2 as duration_pb2 # type: ignore import google.protobuf.field_mask_pb2 as field_mask_pb2 # type: ignore import google.protobuf.timestamp_pb2 as timestamp_pb2 # type: ignore +import google.rpc.status_pb2 as status_pb2 # type: ignore import google.type.expr_pb2 as expr_pb2 # type: ignore from google.api_core import ( client_options, @@ -1941,6 +1944,7 @@ def test_create_secret(request_type, transport: str = "grpc"): call.return_value = resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) response = client.create_secret(request) @@ -1954,6 +1958,7 @@ def test_create_secret(request_type, transport: str = "grpc"): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS def test_create_secret_non_empty_request_with_auto_populated_field(): @@ -2089,6 +2094,7 @@ async def test_create_secret_async(request_type, transport: str = "grpc_asyncio" resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) ) response = await client.create_secret(request) @@ -2103,6 +2109,7 @@ async def test_create_secret_async(request_type, transport: str = "grpc_asyncio" assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS def test_create_secret_field_headers(): @@ -2651,6 +2658,7 @@ def test_get_secret(request_type, transport: str = "grpc"): call.return_value = resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) response = client.get_secret(request) @@ -2664,6 +2672,7 @@ def test_get_secret(request_type, transport: str = "grpc"): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS def test_get_secret_non_empty_request_with_auto_populated_field(): @@ -2795,6 +2804,7 @@ async def test_get_secret_async(request_type, transport: str = "grpc_asyncio"): resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) ) response = await client.get_secret(request) @@ -2809,6 +2819,7 @@ async def test_get_secret_async(request_type, transport: str = "grpc_asyncio"): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS def test_get_secret_field_headers(): @@ -2973,6 +2984,7 @@ def test_update_secret(request_type, transport: str = "grpc"): call.return_value = resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) response = client.update_secret(request) @@ -2986,6 +2998,7 @@ def test_update_secret(request_type, transport: str = "grpc"): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS def test_update_secret_non_empty_request_with_auto_populated_field(): @@ -3115,6 +3128,7 @@ async def test_update_secret_async(request_type, transport: str = "grpc_asyncio" resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) ) response = await client.update_secret(request) @@ -3129,6 +3143,7 @@ async def test_update_secret_async(request_type, transport: str = "grpc_asyncio" assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS def test_update_secret_field_headers(): @@ -6725,6 +6740,723 @@ def test_test_iam_permissions_from_dict_foreign(): call.assert_called() +@pytest.mark.parametrize( + "request_type", + [ + service.EnableManagedRotationRequest(), + {}, + ], +) +def test_enable_managed_rotation(request_type, transport: str = "grpc"): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) + response = client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.EnableManagedRotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True + + +def test_enable_managed_rotation_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.EnableManagedRotationRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.enable_managed_rotation(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableManagedRotationRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_enable_managed_rotation_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 = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._transport.enable_managed_rotation + 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.enable_managed_rotation + ] = mock_rpc + request = {} + client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enable_managed_rotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_enable_managed_rotation_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.enable_managed_rotation + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.enable_managed_rotation + ] = mock_rpc + + request = {} + await client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.enable_managed_rotation(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.EnableManagedRotationRequest(), + {}, + ], +) +async def test_enable_managed_rotation_async( + request_type, transport: str = "grpc_asyncio" +): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) + ) + response = await client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.EnableManagedRotationRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True + + +def test_enable_managed_rotation_field_headers(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EnableManagedRotationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_enable_managed_rotation_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.EnableManagedRotationRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + await client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_enable_managed_rotation_flattened(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.enable_managed_rotation( + parent="parent_value", + cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + assert ( + args[0].cloud_sql_single_user_credentials + == service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ) + ) + + +def test_enable_managed_rotation_flattened_error(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.enable_managed_rotation( + service.EnableManagedRotationRequest(), + parent="parent_value", + cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ), + ) + + +@pytest.mark.asyncio +async def test_enable_managed_rotation_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.enable_managed_rotation( + parent="parent_value", + cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + assert ( + args[0].cloud_sql_single_user_credentials + == service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ) + ) + + +@pytest.mark.asyncio +async def test_enable_managed_rotation_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.enable_managed_rotation( + service.EnableManagedRotationRequest(), + parent="parent_value", + cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.RotateSecretRequest(), + {}, + ], +) +def test_rotate_secret(request_type, transport: str = "grpc"): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) + response = client.rotate_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.RotateSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True + + +def test_rotate_secret_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.RotateSecretRequest( + parent="parent_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.rotate_secret(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RotateSecretRequest( + parent="parent_value", + ) + assert args[0] == request_msg + + +def test_rotate_secret_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 = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.rotate_secret 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.rotate_secret] = mock_rpc + request = {} + client.rotate_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.rotate_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_rotate_secret_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.rotate_secret + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.rotate_secret + ] = mock_rpc + + request = {} + await client.rotate_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.rotate_secret(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "request_type", + [ + service.RotateSecretRequest(), + {}, + ], +) +async def test_rotate_secret_async(request_type, transport: str = "grpc_asyncio"): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) + ) + response = await client.rotate_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.RotateSecretRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True + + +def test_rotate_secret_field_headers(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RotateSecretRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + call.return_value = resources.SecretVersion() + client.rotate_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_rotate_secret_field_headers_async(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.RotateSecretRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + await client.rotate_secret(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_rotate_secret_flattened(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.rotate_secret( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_rotate_secret_flattened_error(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.rotate_secret( + service.RotateSecretRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_rotate_secret_flattened_async(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.SecretVersion() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.rotate_secret( + parent="parent_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_rotate_secret_flattened_error_async(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.rotate_secret( + service.RotateSecretRequest(), + parent="parent_value", + ) + + def test_list_secrets_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call @@ -9262,23 +9994,281 @@ def test_get_iam_policy_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_iam_policy._get_unset_required_fields(jsonified_request) + ).get_iam_policy._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_iam_policy._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("options",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = policy_pb2.Policy() + # 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 + 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 + + 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_iam_policy(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_get_iam_policy_rest_unset_required_fields(): + transport = transports.SecretManagerServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_iam_policy._get_unset_required_fields({}) + assert set(unset_fields) == (set(("options",)) & set(("resource",))) + + +def test_test_iam_permissions_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 = SecretManagerServiceClient( + 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.test_iam_permissions 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.test_iam_permissions] = ( + mock_rpc + ) + + request = {} + client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.test_iam_permissions(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_test_iam_permissions_rest_required_fields( + request_type=iam_policy_pb2.TestIamPermissionsRequest, +): + transport_class = transports.SecretManagerServiceRestTransport + + request_init = {} + request_init["resource"] = "" + request_init["permissions"] = "" + request = request_type(**request_init) + pb_request = 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() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["resource"] = "resource_value" + jsonified_request["permissions"] = "permissions_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).test_iam_permissions._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "resource" in jsonified_request + assert jsonified_request["resource"] == "resource_value" + assert "permissions" in jsonified_request + assert jsonified_request["permissions"] == "permissions_value" + + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = iam_policy_pb2.TestIamPermissionsResponse() + # 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 + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} + + response = client.test_iam_permissions(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert sorted(expected_params) == sorted(actual_params) + + +def test_test_iam_permissions_rest_unset_required_fields(): + transport = transports.SecretManagerServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "resource", + "permissions", + ) + ) + ) + + +def test_enable_managed_rotation_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 = SecretManagerServiceClient( + 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.enable_managed_rotation + 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.enable_managed_rotation + ] = mock_rpc + + request = {} + client.enable_managed_rotation(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.enable_managed_rotation(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_enable_managed_rotation_rest_required_fields( + request_type=service.EnableManagedRotationRequest, +): + transport_class = transports.SecretManagerServiceRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson(pb_request, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).enable_managed_rotation._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_iam_policy._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("options",)) + ).enable_managed_rotation._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9287,7 +10277,7 @@ def test_get_iam_policy_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy() + return_value = resources.SecretVersion() # 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 @@ -9296,40 +10286,104 @@ def test_get_iam_policy_rest_required_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 + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.SecretVersion.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_iam_policy(request) + response = client.enable_managed_rotation(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_get_iam_policy_rest_unset_required_fields(): +def test_enable_managed_rotation_rest_unset_required_fields(): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_iam_policy._get_unset_required_fields({}) - assert set(unset_fields) == (set(("options",)) & set(("resource",))) + unset_fields = transport.enable_managed_rotation._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) -def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): +def test_enable_managed_rotation_rest_flattened(): + client = SecretManagerServiceClient( + 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 = resources.SecretVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/secrets/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.SecretVersion.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.enable_managed_rotation(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/secrets/*}:enableManagedRotation" + % client.transport._host, + args[1], + ) + + +def test_enable_managed_rotation_rest_flattened_error(transport: str = "rest"): + client = SecretManagerServiceClient( + 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.enable_managed_rotation( + service.EnableManagedRotationRequest(), + parent="parent_value", + cloud_sql_single_user_credentials=service.EnableManagedRotationRequest.CloudSQLSingleUserCredentials( + instance_id="instance_id_value" + ), + ) + + +def test_rotate_secret_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: @@ -9343,42 +10397,35 @@ def test_test_iam_permissions_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.test_iam_permissions in client._transport._wrapped_methods - ) + assert client._transport.rotate_secret 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.test_iam_permissions] = ( - mock_rpc - ) + client._transport._wrapped_methods[client._transport.rotate_secret] = mock_rpc request = {} - client.test_iam_permissions(request) + client.rotate_secret(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.test_iam_permissions(request) + client.rotate_secret(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_test_iam_permissions_rest_required_fields( - request_type=iam_policy_pb2.TestIamPermissionsRequest, -): +def test_rotate_secret_rest_required_fields(request_type=service.RotateSecretRequest): transport_class = transports.SecretManagerServiceRestTransport request_init = {} - request_init["resource"] = "" - request_init["permissions"] = "" + request_init["parent"] = "" request = request_type(**request_init) - pb_request = request + pb_request = request_type.pb(request) jsonified_request = json.loads( json_format.MessageToJson(pb_request, use_integers_for_enums=False) ) @@ -9387,24 +10434,21 @@ def test_test_iam_permissions_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).test_iam_permissions._get_unset_required_fields(jsonified_request) + ).rotate_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["resource"] = "resource_value" - jsonified_request["permissions"] = "permissions_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).test_iam_permissions._get_unset_required_fields(jsonified_request) + ).rotate_secret._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "resource" in jsonified_request - assert jsonified_request["resource"] == "resource_value" - assert "permissions" in jsonified_request - assert jsonified_request["permissions"] == "permissions_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9413,7 +10457,7 @@ def test_test_iam_permissions_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse() + return_value = resources.SecretVersion() # 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 @@ -9422,7 +10466,7 @@ def test_test_iam_permissions_rest_required_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 + pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", "method": "post", @@ -9434,35 +10478,86 @@ def test_test_iam_permissions_rest_required_fields( response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.SecretVersion.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.test_iam_permissions(request) + response = client.rotate_secret(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert sorted(expected_params) == sorted(actual_params) -def test_test_iam_permissions_rest_unset_required_fields(): +def test_rotate_secret_rest_unset_required_fields(): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.test_iam_permissions._get_unset_required_fields({}) - assert set(unset_fields) == ( - set(()) - & set( - ( - "resource", - "permissions", - ) + unset_fields = transport.rotate_secret._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) + + +def test_rotate_secret_rest_flattened(): + client = SecretManagerServiceClient( + 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 = resources.SecretVersion() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/secrets/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.SecretVersion.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.rotate_secret(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/secrets/*}:rotateSecret" % client.transport._host, + args[1], ) + + +def test_rotate_secret_rest_flattened_error(transport: str = "rest"): + client = SecretManagerServiceClient( + 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.rotate_secret( + service.RotateSecretRequest(), + parent="parent_value", + ) + def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. @@ -9886,6 +10981,48 @@ def test_test_iam_permissions_empty_call_grpc(): 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_enable_managed_rotation_empty_call_grpc(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + call.return_value = resources.SecretVersion() + client.enable_managed_rotation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableManagedRotationRequest() + 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_rotate_secret_empty_call_grpc(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + call.return_value = resources.SecretVersion() + client.rotate_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RotateSecretRequest() + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = SecretManagerServiceAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -9943,6 +11080,7 @@ async def test_create_secret_empty_call_grpc_asyncio(): resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) ) await client.create_secret(request=None) @@ -10001,6 +11139,7 @@ async def test_get_secret_empty_call_grpc_asyncio(): resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) ) await client.get_secret(request=None) @@ -10028,6 +11167,7 @@ async def test_update_secret_empty_call_grpc_asyncio(): resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) ) await client.update_secret(request=None) @@ -10315,12 +11455,72 @@ async def test_test_iam_permissions_empty_call_grpc_asyncio(): permissions=["permissions_value"], ) ) - await client.test_iam_permissions(request=None) + await client.test_iam_permissions(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = iam_policy_pb2.TestIamPermissionsRequest() + 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. +@pytest.mark.asyncio +async def test_enable_managed_rotation_empty_call_grpc_asyncio(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) + ) + await client.enable_managed_rotation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableManagedRotationRequest() + 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. +@pytest.mark.asyncio +async def test_rotate_secret_empty_call_grpc_asyncio(): + client = SecretManagerServiceAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) + ) + await client.rotate_secret(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = iam_policy_pb2.TestIamPermissionsRequest() + request_msg = service.RotateSecretRequest() assert args[0] == request_msg @@ -10518,12 +11718,33 @@ def test_create_secret_rest_call_success(request_type): "expire_time": {}, "ttl": {"seconds": 751, "nanos": 543}, "etag": "etag_value", - "rotation": {"next_rotation_time": {}, "rotation_period": {}}, + "rotation": { + "next_rotation_time": {}, + "rotation_period": {}, + "managed_rotation_status": { + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + }, + }, "version_aliases": {}, "annotations": {}, "version_destroy_ttl": {}, "customer_managed_encryption": {}, "tags": {}, + "secret_type": 1, + "policy_member": { + "iam_policy_name_principal": "iam_policy_name_principal_value", + "iam_policy_uid_principal": "iam_policy_uid_principal_value", + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -10600,6 +11821,7 @@ def get_message_fields(field): return_value = resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) # Wrap the value into a proper Response obj @@ -10618,6 +11840,7 @@ def get_message_fields(field): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -10866,6 +12089,7 @@ def test_get_secret_rest_call_success(request_type): return_value = resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) # Wrap the value into a proper Response obj @@ -10884,6 +12108,7 @@ def test_get_secret_rest_call_success(request_type): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -11005,12 +12230,33 @@ def test_update_secret_rest_call_success(request_type): "expire_time": {}, "ttl": {"seconds": 751, "nanos": 543}, "etag": "etag_value", - "rotation": {"next_rotation_time": {}, "rotation_period": {}}, + "rotation": { + "next_rotation_time": {}, + "rotation_period": {}, + "managed_rotation_status": { + "state": 1, + "error": { + "code": 411, + "message": "message_value", + "details": [ + { + "type_url": "type.googleapis.com/google.protobuf.Duration", + "value": b"\x08\x0c\x10\xdb\x07", + } + ], + }, + }, + }, "version_aliases": {}, "annotations": {}, "version_destroy_ttl": {}, "customer_managed_encryption": {}, "tags": {}, + "secret_type": 1, + "policy_member": { + "iam_policy_name_principal": "iam_policy_name_principal_value", + "iam_policy_uid_principal": "iam_policy_uid_principal_value", + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -11087,6 +12333,7 @@ def get_message_fields(field): return_value = resources.Secret( name="name_value", etag="etag_value", + secret_type=resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS, ) # Wrap the value into a proper Response obj @@ -11105,6 +12352,7 @@ def get_message_fields(field): assert isinstance(response, resources.Secret) assert response.name == "name_value" assert response.etag == "etag_value" + assert response.secret_type == resources.Secret.SecretType.CLOUD_SQL_DB_CREDENTIALS @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -11175,7 +12423,250 @@ def test_delete_secret_rest_bad_request(request_type=service.DeleteSecretRequest credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/secrets/sample2"} + request_init = {"name": "projects/sample1/secrets/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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.delete_secret(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteSecretRequest, + dict, + ], +) +def test_delete_secret_rest_call_success(request_type): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/secrets/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = None + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_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.delete_secret(request) + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_delete_secret_rest_interceptors(null_interceptor): + transport = transports.SecretManagerServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecretManagerServiceRestInterceptor(), + ) + client = SecretManagerServiceClient(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.SecretManagerServiceRestInterceptor, "pre_delete_secret" + ) as pre, + ): + pre.assert_not_called() + pb_message = service.DeleteSecretRequest.pb(service.DeleteSecretRequest()) + 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"} + + request = service.DeleteSecretRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + + client.delete_secret( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + + +def test_list_secret_versions_rest_bad_request( + request_type=service.ListSecretVersionsRequest, +): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/secrets/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with ( + mock.patch.object(Session, "request") as req, + pytest.raises(core_exceptions.BadRequest), + ): + # Wrap the value into a proper Response obj + response_value = 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_secret_versions(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListSecretVersionsRequest, + dict, + ], +) +def test_list_secret_versions_rest_call_success(request_type): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/secrets/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListSecretVersionsResponse( + next_page_token="next_page_token_value", + total_size=1086, + ) + + # 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 = service.ListSecretVersionsResponse.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_secret_versions(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListSecretVersionsPager) + assert response.next_page_token == "next_page_token_value" + assert response.total_size == 1086 + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_secret_versions_rest_interceptors(null_interceptor): + transport = transports.SecretManagerServiceRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.SecretManagerServiceRestInterceptor(), + ) + client = SecretManagerServiceClient(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.SecretManagerServiceRestInterceptor, "post_list_secret_versions" + ) as post, + mock.patch.object( + transports.SecretManagerServiceRestInterceptor, + "post_list_secret_versions_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecretManagerServiceRestInterceptor, "pre_list_secret_versions" + ) as pre, + ): + pre.assert_not_called() + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.ListSecretVersionsRequest.pb( + service.ListSecretVersionsRequest() + ) + 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 = service.ListSecretVersionsResponse.to_json( + service.ListSecretVersionsResponse() + ) + req.return_value.content = return_value + + request = service.ListSecretVersionsRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListSecretVersionsResponse() + post_with_metadata.return_value = service.ListSecretVersionsResponse(), metadata + + client.list_secret_versions( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() + + +def test_get_secret_version_rest_bad_request( + request_type=service.GetSecretVersionRequest, +): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/secrets/sample2/versions/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11191,45 +12682,57 @@ def test_delete_secret_rest_bad_request(request_type=service.DeleteSecretRequest response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.delete_secret(request) + client.get_secret_version(request) @pytest.mark.parametrize( "request_type", [ - service.DeleteSecretRequest, + service.GetSecretVersionRequest, dict, ], ) -def test_delete_secret_rest_call_success(request_type): +def test_get_secret_version_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/secrets/sample2"} + request_init = {"name": "projects/sample1/secrets/sample2/versions/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 = None + return_value = resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, + ) # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = resources.SecretVersion.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.delete_secret(request) + response = client.get_secret_version(request) # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_secret_rest_interceptors(null_interceptor): +def test_get_secret_version_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11242,11 +12745,22 @@ def test_delete_secret_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_delete_secret" + transports.SecretManagerServiceRestInterceptor, "post_get_secret_version" + ) as post, + mock.patch.object( + transports.SecretManagerServiceRestInterceptor, + "post_get_secret_version_with_metadata", + ) as post_with_metadata, + mock.patch.object( + transports.SecretManagerServiceRestInterceptor, "pre_get_secret_version" ) as pre, ): pre.assert_not_called() - pb_message = service.DeleteSecretRequest.pb(service.DeleteSecretRequest()) + post.assert_not_called() + post_with_metadata.assert_not_called() + pb_message = service.GetSecretVersionRequest.pb( + service.GetSecretVersionRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11257,15 +12771,19 @@ def test_delete_secret_rest_interceptors(null_interceptor): 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 = resources.SecretVersion.to_json(resources.SecretVersion()) + req.return_value.content = return_value - request = service.DeleteSecretRequest() + request = service.GetSecretVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata + post.return_value = resources.SecretVersion() + post_with_metadata.return_value = resources.SecretVersion(), metadata - client.delete_secret( + client.get_secret_version( request, metadata=[ ("key", "val"), @@ -11274,16 +12792,18 @@ def test_delete_secret_rest_interceptors(null_interceptor): ) pre.assert_called_once() + post.assert_called_once() + post_with_metadata.assert_called_once() -def test_list_secret_versions_rest_bad_request( - request_type=service.ListSecretVersionsRequest, +def test_access_secret_version_rest_bad_request( + request_type=service.AccessSecretVersionRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/secrets/sample2"} + request_init = {"name": "projects/sample1/secrets/sample2/versions/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11299,31 +12819,30 @@ def test_list_secret_versions_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.list_secret_versions(request) + client.access_secret_version(request) @pytest.mark.parametrize( "request_type", [ - service.ListSecretVersionsRequest, + service.AccessSecretVersionRequest, dict, ], ) -def test_list_secret_versions_rest_call_success(request_type): +def test_access_secret_version_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/secrets/sample2"} + request_init = {"name": "projects/sample1/secrets/sample2/versions/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 = service.ListSecretVersionsResponse( - next_page_token="next_page_token_value", - total_size=1086, + return_value = service.AccessSecretVersionResponse( + name="name_value", ) # Wrap the value into a proper Response obj @@ -11331,21 +12850,20 @@ def test_list_secret_versions_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.ListSecretVersionsResponse.pb(return_value) + return_value = service.AccessSecretVersionResponse.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_secret_versions(request) + response = client.access_secret_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSecretVersionsPager) - assert response.next_page_token == "next_page_token_value" - assert response.total_size == 1086 + assert isinstance(response, service.AccessSecretVersionResponse) + assert response.name == "name_value" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_secret_versions_rest_interceptors(null_interceptor): +def test_access_secret_version_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11358,21 +12876,21 @@ def test_list_secret_versions_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_list_secret_versions" + transports.SecretManagerServiceRestInterceptor, "post_access_secret_version" ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_list_secret_versions_with_metadata", + "post_access_secret_version_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_list_secret_versions" + transports.SecretManagerServiceRestInterceptor, "pre_access_secret_version" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.ListSecretVersionsRequest.pb( - service.ListSecretVersionsRequest() + pb_message = service.AccessSecretVersionRequest.pb( + service.AccessSecretVersionRequest() ) transcode.return_value = { "method": "post", @@ -11384,21 +12902,24 @@ def test_list_secret_versions_rest_interceptors(null_interceptor): 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 = service.ListSecretVersionsResponse.to_json( - service.ListSecretVersionsResponse() + return_value = service.AccessSecretVersionResponse.to_json( + service.AccessSecretVersionResponse() ) req.return_value.content = return_value - request = service.ListSecretVersionsRequest() + request = service.AccessSecretVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListSecretVersionsResponse() - post_with_metadata.return_value = service.ListSecretVersionsResponse(), metadata + post.return_value = service.AccessSecretVersionResponse() + post_with_metadata.return_value = ( + service.AccessSecretVersionResponse(), + metadata, + ) - client.list_secret_versions( + client.access_secret_version( request, metadata=[ ("key", "val"), @@ -11411,8 +12932,8 @@ def test_list_secret_versions_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_secret_version_rest_bad_request( - request_type=service.GetSecretVersionRequest, +def test_disable_secret_version_rest_bad_request( + request_type=service.DisableSecretVersionRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -11434,17 +12955,17 @@ def test_get_secret_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_secret_version(request) + client.disable_secret_version(request) @pytest.mark.parametrize( "request_type", [ - service.GetSecretVersionRequest, + service.DisableSecretVersionRequest, dict, ], ) -def test_get_secret_version_rest_call_success(request_type): +def test_disable_secret_version_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11473,7 +12994,7 @@ def test_get_secret_version_rest_call_success(request_type): 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_secret_version(request) + response = client.disable_secret_version(request) # Establish that the response is the type that we expect. assert isinstance(response, resources.SecretVersion) @@ -11484,7 +13005,7 @@ def test_get_secret_version_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_secret_version_rest_interceptors(null_interceptor): +def test_disable_secret_version_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11497,21 +13018,22 @@ def test_get_secret_version_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_get_secret_version" + transports.SecretManagerServiceRestInterceptor, + "post_disable_secret_version", ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_get_secret_version_with_metadata", + "post_disable_secret_version_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_get_secret_version" + transports.SecretManagerServiceRestInterceptor, "pre_disable_secret_version" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.GetSecretVersionRequest.pb( - service.GetSecretVersionRequest() + pb_message = service.DisableSecretVersionRequest.pb( + service.DisableSecretVersionRequest() ) transcode.return_value = { "method": "post", @@ -11526,7 +13048,7 @@ def test_get_secret_version_rest_interceptors(null_interceptor): return_value = resources.SecretVersion.to_json(resources.SecretVersion()) req.return_value.content = return_value - request = service.GetSecretVersionRequest() + request = service.DisableSecretVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -11535,7 +13057,7 @@ def test_get_secret_version_rest_interceptors(null_interceptor): post.return_value = resources.SecretVersion() post_with_metadata.return_value = resources.SecretVersion(), metadata - client.get_secret_version( + client.disable_secret_version( request, metadata=[ ("key", "val"), @@ -11548,8 +13070,8 @@ def test_get_secret_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_access_secret_version_rest_bad_request( - request_type=service.AccessSecretVersionRequest, +def test_enable_secret_version_rest_bad_request( + request_type=service.EnableSecretVersionRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -11571,17 +13093,17 @@ def test_access_secret_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.access_secret_version(request) + client.enable_secret_version(request) @pytest.mark.parametrize( "request_type", [ - service.AccessSecretVersionRequest, + service.EnableSecretVersionRequest, dict, ], ) -def test_access_secret_version_rest_call_success(request_type): +def test_enable_secret_version_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11593,8 +13115,11 @@ def test_access_secret_version_rest_call_success(request_type): # 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 = service.AccessSecretVersionResponse( + return_value = resources.SecretVersion( name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, ) # Wrap the value into a proper Response obj @@ -11602,20 +13127,23 @@ def test_access_secret_version_rest_call_success(request_type): response_value.status_code = 200 # Convert return value to protobuf type - return_value = service.AccessSecretVersionResponse.pb(return_value) + return_value = resources.SecretVersion.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.access_secret_version(request) + response = client.enable_secret_version(request) # Establish that the response is the type that we expect. - assert isinstance(response, service.AccessSecretVersionResponse) + assert isinstance(response, resources.SecretVersion) assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_access_secret_version_rest_interceptors(null_interceptor): +def test_enable_secret_version_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11628,21 +13156,21 @@ def test_access_secret_version_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_access_secret_version" + transports.SecretManagerServiceRestInterceptor, "post_enable_secret_version" ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_access_secret_version_with_metadata", + "post_enable_secret_version_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_access_secret_version" + transports.SecretManagerServiceRestInterceptor, "pre_enable_secret_version" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.AccessSecretVersionRequest.pb( - service.AccessSecretVersionRequest() + pb_message = service.EnableSecretVersionRequest.pb( + service.EnableSecretVersionRequest() ) transcode.return_value = { "method": "post", @@ -11654,24 +13182,19 @@ def test_access_secret_version_rest_interceptors(null_interceptor): 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 = service.AccessSecretVersionResponse.to_json( - service.AccessSecretVersionResponse() - ) + return_value = resources.SecretVersion.to_json(resources.SecretVersion()) req.return_value.content = return_value - request = service.AccessSecretVersionRequest() + request = service.EnableSecretVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.AccessSecretVersionResponse() - post_with_metadata.return_value = ( - service.AccessSecretVersionResponse(), - metadata, - ) + post.return_value = resources.SecretVersion() + post_with_metadata.return_value = resources.SecretVersion(), metadata - client.access_secret_version( + client.enable_secret_version( request, metadata=[ ("key", "val"), @@ -11684,8 +13207,8 @@ def test_access_secret_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_disable_secret_version_rest_bad_request( - request_type=service.DisableSecretVersionRequest, +def test_destroy_secret_version_rest_bad_request( + request_type=service.DestroySecretVersionRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -11707,17 +13230,17 @@ def test_disable_secret_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.disable_secret_version(request) + client.destroy_secret_version(request) @pytest.mark.parametrize( "request_type", [ - service.DisableSecretVersionRequest, + service.DestroySecretVersionRequest, dict, ], ) -def test_disable_secret_version_rest_call_success(request_type): +def test_destroy_secret_version_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11746,7 +13269,7 @@ def test_disable_secret_version_rest_call_success(request_type): 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.disable_secret_version(request) + response = client.destroy_secret_version(request) # Establish that the response is the type that we expect. assert isinstance(response, resources.SecretVersion) @@ -11757,7 +13280,7 @@ def test_disable_secret_version_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_disable_secret_version_rest_interceptors(null_interceptor): +def test_destroy_secret_version_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11771,21 +13294,21 @@ def test_disable_secret_version_rest_interceptors(null_interceptor): mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_disable_secret_version", + "post_destroy_secret_version", ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_disable_secret_version_with_metadata", + "post_destroy_secret_version_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_disable_secret_version" + transports.SecretManagerServiceRestInterceptor, "pre_destroy_secret_version" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DisableSecretVersionRequest.pb( - service.DisableSecretVersionRequest() + pb_message = service.DestroySecretVersionRequest.pb( + service.DestroySecretVersionRequest() ) transcode.return_value = { "method": "post", @@ -11800,7 +13323,7 @@ def test_disable_secret_version_rest_interceptors(null_interceptor): return_value = resources.SecretVersion.to_json(resources.SecretVersion()) req.return_value.content = return_value - request = service.DisableSecretVersionRequest() + request = service.DestroySecretVersionRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -11809,7 +13332,7 @@ def test_disable_secret_version_rest_interceptors(null_interceptor): post.return_value = resources.SecretVersion() post_with_metadata.return_value = resources.SecretVersion(), metadata - client.disable_secret_version( + client.destroy_secret_version( request, metadata=[ ("key", "val"), @@ -11822,14 +13345,14 @@ def test_disable_secret_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_enable_secret_version_rest_bad_request( - request_type=service.EnableSecretVersionRequest, +def test_set_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.SetIamPolicyRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/secrets/sample2/versions/sample3"} + request_init = {"resource": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11845,57 +13368,50 @@ def test_enable_secret_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.enable_secret_version(request) + client.set_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - service.EnableSecretVersionRequest, + iam_policy_pb2.SetIamPolicyRequest, dict, ], ) -def test_enable_secret_version_rest_call_success(request_type): +def test_set_iam_policy_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/secrets/sample2/versions/sample3"} + request_init = {"resource": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SecretVersion( - name="name_value", - state=resources.SecretVersion.State.ENABLED, - etag="etag_value", - client_specified_payload_checksum=True, + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", ) # 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 = resources.SecretVersion.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.enable_secret_version(request) + response = client.set_iam_policy(request) - # Establish that the response is the type that we expect. - assert isinstance(response, resources.SecretVersion) - assert response.name == "name_value" - assert response.state == resources.SecretVersion.State.ENABLED - assert response.etag == "etag_value" - assert response.client_specified_payload_checksum is True + # Establish that the response is the type that we expect. + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_enable_secret_version_rest_interceptors(null_interceptor): +def test_set_iam_policy_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11908,22 +13424,20 @@ def test_enable_secret_version_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_enable_secret_version" + transports.SecretManagerServiceRestInterceptor, "post_set_iam_policy" ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_enable_secret_version_with_metadata", + "post_set_iam_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_enable_secret_version" + transports.SecretManagerServiceRestInterceptor, "pre_set_iam_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.EnableSecretVersionRequest.pb( - service.EnableSecretVersionRequest() - ) + pb_message = iam_policy_pb2.SetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11934,19 +13448,19 @@ def test_enable_secret_version_rest_interceptors(null_interceptor): 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 = resources.SecretVersion.to_json(resources.SecretVersion()) + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = service.EnableSecretVersionRequest() + request = iam_policy_pb2.SetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SecretVersion() - post_with_metadata.return_value = resources.SecretVersion(), metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.enable_secret_version( + client.set_iam_policy( request, metadata=[ ("key", "val"), @@ -11959,14 +13473,14 @@ def test_enable_secret_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_destroy_secret_version_rest_bad_request( - request_type=service.DestroySecretVersionRequest, +def test_get_iam_policy_rest_bad_request( + request_type=iam_policy_pb2.GetIamPolicyRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/secrets/sample2/versions/sample3"} + request_init = {"resource": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11982,57 +13496,50 @@ def test_destroy_secret_version_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.destroy_secret_version(request) + client.get_iam_policy(request) @pytest.mark.parametrize( "request_type", [ - service.DestroySecretVersionRequest, + iam_policy_pb2.GetIamPolicyRequest, dict, ], ) -def test_destroy_secret_version_rest_call_success(request_type): +def test_get_iam_policy_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/secrets/sample2/versions/sample3"} + request_init = {"resource": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.SecretVersion( - name="name_value", - state=resources.SecretVersion.State.ENABLED, - etag="etag_value", - client_specified_payload_checksum=True, + return_value = policy_pb2.Policy( + version=774, + etag=b"etag_blob", ) # 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 = resources.SecretVersion.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.destroy_secret_version(request) + response = client.get_iam_policy(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.SecretVersion) - assert response.name == "name_value" - assert response.state == resources.SecretVersion.State.ENABLED - assert response.etag == "etag_value" - assert response.client_specified_payload_checksum is True + assert isinstance(response, policy_pb2.Policy) + assert response.version == 774 + assert response.etag == b"etag_blob" @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_destroy_secret_version_rest_interceptors(null_interceptor): +def test_get_iam_policy_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12045,23 +13552,20 @@ def test_destroy_secret_version_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, - "post_destroy_secret_version", + transports.SecretManagerServiceRestInterceptor, "post_get_iam_policy" ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_destroy_secret_version_with_metadata", + "post_get_iam_policy_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_destroy_secret_version" + transports.SecretManagerServiceRestInterceptor, "pre_get_iam_policy" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = service.DestroySecretVersionRequest.pb( - service.DestroySecretVersionRequest() - ) + pb_message = iam_policy_pb2.GetIamPolicyRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12072,19 +13576,19 @@ def test_destroy_secret_version_rest_interceptors(null_interceptor): 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 = resources.SecretVersion.to_json(resources.SecretVersion()) + return_value = json_format.MessageToJson(policy_pb2.Policy()) req.return_value.content = return_value - request = service.DestroySecretVersionRequest() + request = iam_policy_pb2.GetIamPolicyRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.SecretVersion() - post_with_metadata.return_value = resources.SecretVersion(), metadata + post.return_value = policy_pb2.Policy() + post_with_metadata.return_value = policy_pb2.Policy(), metadata - client.destroy_secret_version( + client.get_iam_policy( request, metadata=[ ("key", "val"), @@ -12097,8 +13601,8 @@ def test_destroy_secret_version_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_set_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.SetIamPolicyRequest, +def test_test_iam_permissions_rest_bad_request( + request_type=iam_policy_pb2.TestIamPermissionsRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -12120,17 +13624,17 @@ def test_set_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.set_iam_policy(request) + client.test_iam_permissions(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.SetIamPolicyRequest, + iam_policy_pb2.TestIamPermissionsRequest, dict, ], ) -def test_set_iam_policy_rest_call_success(request_type): +def test_test_iam_permissions_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12142,9 +13646,8 @@ def test_set_iam_policy_rest_call_success(request_type): # 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 = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = iam_policy_pb2.TestIamPermissionsResponse( + permissions=["permissions_value"], ) # Wrap the value into a proper Response obj @@ -12154,16 +13657,15 @@ def test_set_iam_policy_rest_call_success(request_type): 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.set_iam_policy(request) + response = client.test_iam_permissions(request) # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) + assert response.permissions == ["permissions_value"] @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_set_iam_policy_rest_interceptors(null_interceptor): +def test_test_iam_permissions_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12176,20 +13678,20 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_set_iam_policy" + transports.SecretManagerServiceRestInterceptor, "post_test_iam_permissions" ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_set_iam_policy_with_metadata", + "post_test_iam_permissions_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_set_iam_policy" + transports.SecretManagerServiceRestInterceptor, "pre_test_iam_permissions" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.SetIamPolicyRequest() + pb_message = iam_policy_pb2.TestIamPermissionsRequest() transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12200,19 +13702,24 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): 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 = json_format.MessageToJson(policy_pb2.Policy()) + return_value = json_format.MessageToJson( + iam_policy_pb2.TestIamPermissionsResponse() + ) req.return_value.content = return_value - request = iam_policy_pb2.SetIamPolicyRequest() + request = iam_policy_pb2.TestIamPermissionsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = iam_policy_pb2.TestIamPermissionsResponse() + post_with_metadata.return_value = ( + iam_policy_pb2.TestIamPermissionsResponse(), + metadata, + ) - client.set_iam_policy( + client.test_iam_permissions( request, metadata=[ ("key", "val"), @@ -12225,14 +13732,14 @@ def test_set_iam_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_get_iam_policy_rest_bad_request( - request_type=iam_policy_pb2.GetIamPolicyRequest, +def test_enable_managed_rotation_rest_bad_request( + request_type=service.EnableManagedRotationRequest, ): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/secrets/sample2"} + request_init = {"parent": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12248,50 +13755,57 @@ def test_get_iam_policy_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.get_iam_policy(request) + client.enable_managed_rotation(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.GetIamPolicyRequest, + service.EnableManagedRotationRequest, dict, ], ) -def test_get_iam_policy_rest_call_success(request_type): +def test_enable_managed_rotation_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/secrets/sample2"} + request_init = {"parent": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = policy_pb2.Policy( - version=774, - etag=b"etag_blob", + return_value = resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, ) # 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 = resources.SecretVersion.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_iam_policy(request) + response = client.enable_managed_rotation(request) # Establish that the response is the type that we expect. - assert isinstance(response, policy_pb2.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_iam_policy_rest_interceptors(null_interceptor): +def test_enable_managed_rotation_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12304,20 +13818,24 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_get_iam_policy" + transports.SecretManagerServiceRestInterceptor, + "post_enable_managed_rotation", ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_get_iam_policy_with_metadata", + "post_enable_managed_rotation_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_get_iam_policy" + transports.SecretManagerServiceRestInterceptor, + "pre_enable_managed_rotation", ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.GetIamPolicyRequest() + pb_message = service.EnableManagedRotationRequest.pb( + service.EnableManagedRotationRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12328,19 +13846,19 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): 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 = json_format.MessageToJson(policy_pb2.Policy()) + return_value = resources.SecretVersion.to_json(resources.SecretVersion()) req.return_value.content = return_value - request = iam_policy_pb2.GetIamPolicyRequest() + request = service.EnableManagedRotationRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = policy_pb2.Policy() - post_with_metadata.return_value = policy_pb2.Policy(), metadata + post.return_value = resources.SecretVersion() + post_with_metadata.return_value = resources.SecretVersion(), metadata - client.get_iam_policy( + client.enable_managed_rotation( request, metadata=[ ("key", "val"), @@ -12353,14 +13871,12 @@ def test_get_iam_policy_rest_interceptors(null_interceptor): post_with_metadata.assert_called_once() -def test_test_iam_permissions_rest_bad_request( - request_type=iam_policy_pb2.TestIamPermissionsRequest, -): +def test_rotate_secret_rest_bad_request(request_type=service.RotateSecretRequest): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/secrets/sample2"} + request_init = {"parent": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -12376,48 +13892,57 @@ def test_test_iam_permissions_rest_bad_request( response_value.request = mock.Mock() req.return_value = response_value req.return_value.headers = {"header-1": "value-1", "header-2": "value-2"} - client.test_iam_permissions(request) + client.rotate_secret(request) @pytest.mark.parametrize( "request_type", [ - iam_policy_pb2.TestIamPermissionsRequest, + service.RotateSecretRequest, dict, ], ) -def test_test_iam_permissions_rest_call_success(request_type): +def test_rotate_secret_rest_call_success(request_type): client = SecretManagerServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) # send a request that will satisfy transcoding - request_init = {"resource": "projects/sample1/secrets/sample2"} + request_init = {"parent": "projects/sample1/secrets/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = iam_policy_pb2.TestIamPermissionsResponse( - permissions=["permissions_value"], + return_value = resources.SecretVersion( + name="name_value", + state=resources.SecretVersion.State.ENABLED, + etag="etag_value", + client_specified_payload_checksum=True, ) # 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 = resources.SecretVersion.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.test_iam_permissions(request) + response = client.rotate_secret(request) # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy_pb2.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] + assert isinstance(response, resources.SecretVersion) + assert response.name == "name_value" + assert response.state == resources.SecretVersion.State.ENABLED + assert response.etag == "etag_value" + assert response.client_specified_payload_checksum is True @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_test_iam_permissions_rest_interceptors(null_interceptor): +def test_rotate_secret_rest_interceptors(null_interceptor): transport = transports.SecretManagerServiceRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12430,20 +13955,20 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): mock.patch.object(type(client.transport._session), "request") as req, mock.patch.object(path_template, "transcode") as transcode, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "post_test_iam_permissions" + transports.SecretManagerServiceRestInterceptor, "post_rotate_secret" ) as post, mock.patch.object( transports.SecretManagerServiceRestInterceptor, - "post_test_iam_permissions_with_metadata", + "post_rotate_secret_with_metadata", ) as post_with_metadata, mock.patch.object( - transports.SecretManagerServiceRestInterceptor, "pre_test_iam_permissions" + transports.SecretManagerServiceRestInterceptor, "pre_rotate_secret" ) as pre, ): pre.assert_not_called() post.assert_not_called() post_with_metadata.assert_not_called() - pb_message = iam_policy_pb2.TestIamPermissionsRequest() + pb_message = service.RotateSecretRequest.pb(service.RotateSecretRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12454,24 +13979,19 @@ def test_test_iam_permissions_rest_interceptors(null_interceptor): 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 = json_format.MessageToJson( - iam_policy_pb2.TestIamPermissionsResponse() - ) + return_value = resources.SecretVersion.to_json(resources.SecretVersion()) req.return_value.content = return_value - request = iam_policy_pb2.TestIamPermissionsRequest() + request = service.RotateSecretRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = iam_policy_pb2.TestIamPermissionsResponse() - post_with_metadata.return_value = ( - iam_policy_pb2.TestIamPermissionsResponse(), - metadata, - ) + post.return_value = resources.SecretVersion() + post_with_metadata.return_value = resources.SecretVersion(), metadata - client.test_iam_permissions( + client.rotate_secret( request, metadata=[ ("key", "val"), @@ -12914,6 +14434,46 @@ def test_test_iam_permissions_empty_call_rest(): 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_enable_managed_rotation_empty_call_rest(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.enable_managed_rotation), "__call__" + ) as call: + client.enable_managed_rotation(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.EnableManagedRotationRequest() + 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_rotate_secret_empty_call_rest(): + client = SecretManagerServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.rotate_secret), "__call__") as call: + client.rotate_secret(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.RotateSecretRequest() + assert args[0] == request_msg + + def test_transport_grpc_default(): # A client should use the gRPC transport by default. client = SecretManagerServiceClient( @@ -12962,6 +14522,8 @@ def test_secret_manager_service_base_transport(): "set_iam_policy", "get_iam_policy", "test_iam_permissions", + "enable_managed_rotation", + "rotate_secret", "get_location", "list_locations", ) @@ -13276,6 +14838,12 @@ def test_secret_manager_service_client_transport_session_collision(transport_nam session1 = client1.transport.test_iam_permissions._session session2 = client2.transport.test_iam_permissions._session assert session1 != session2 + session1 = client1.transport.enable_managed_rotation._session + session2 = client2.transport.enable_managed_rotation._session + assert session1 != session2 + session1 = client1.transport.rotate_secret._session + session2 = client2.transport.rotate_secret._session + assert session1 != session2 def test_secret_manager_service_grpc_transport_channel(): diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py index 9911fdfaf9d7..c366c6734dd8 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter/__init__.py @@ -29,6 +29,13 @@ Geolocation, ServiceAccountDelegationInfo, ) +from google.cloud.securitycenter_v1.types.agent import Agent +from google.cloud.securitycenter_v1.types.agent_anomaly import ( + AgentAnomaly, + DetectorReference, + InvocationReference, +) +from google.cloud.securitycenter_v1.types.agent_session import AgentSession from google.cloud.securitycenter_v1.types.application import Application from google.cloud.securitycenter_v1.types.asset import Asset from google.cloud.securitycenter_v1.types.attack_exposure import AttackExposure @@ -228,6 +235,11 @@ "Access", "Geolocation", "ServiceAccountDelegationInfo", + "Agent", + "AgentAnomaly", + "DetectorReference", + "InvocationReference", + "AgentSession", "Application", "Asset", "AttackExposure", diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py index 7e6f19b8c06b..c15e6c7d2691 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/__init__.py @@ -25,6 +25,9 @@ from .services.security_center import SecurityCenterAsyncClient, SecurityCenterClient from .types.access import Access, Geolocation, ServiceAccountDelegationInfo +from .types.agent import Agent +from .types.agent_anomaly import AgentAnomaly, DetectorReference, InvocationReference +from .types.agent_session import AgentSession from .types.application import Application from .types.asset import Asset from .types.attack_exposure import AttackExposure @@ -284,6 +287,9 @@ def _get_version(dependency_name): "SecurityCenterAsyncClient", "Access", "AdaptiveProtection", + "Agent", + "AgentAnomaly", + "AgentSession", "Application", "Asset", "Attack", @@ -328,6 +334,7 @@ def _get_version(dependency_name): "DeleteNotificationConfigRequest", "DeleteResourceValueConfigRequest", "DeleteSecurityHealthAnalyticsCustomModuleRequest", + "DetectorReference", "EffectiveEventThreatDetectionCustomModule", "EffectiveSecurityHealthAnalyticsCustomModule", "EnvironmentVariable", @@ -361,6 +368,7 @@ def _get_version(dependency_name): "IamBinding", "Indicator", "InfoType", + "InvocationReference", "KernelRootkit", "Kubernetes", "Label", diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py index 613ad9ce3e75..6f58114c012c 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -58,6 +58,9 @@ from google.cloud.securitycenter_v1.services.security_center import pagers from google.cloud.securitycenter_v1.types import ( access, + agent, + agent_anomaly, + agent_session, application, attack_exposure, attack_path, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py index 8ba223e3e830..2fcde50f2d71 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/services/security_center/client.py @@ -74,6 +74,9 @@ from google.cloud.securitycenter_v1.services.security_center import pagers from google.cloud.securitycenter_v1.types import ( access, + agent, + agent_anomaly, + agent_session, application, attack_exposure, attack_path, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py index 0c02f3aa6f45..e9879c60084b 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/__init__.py @@ -18,6 +18,17 @@ Geolocation, ServiceAccountDelegationInfo, ) +from .agent import ( + Agent, +) +from .agent_anomaly import ( + AgentAnomaly, + DetectorReference, + InvocationReference, +) +from .agent_session import ( + AgentSession, +) from .application import ( Application, ) @@ -290,6 +301,11 @@ "Access", "Geolocation", "ServiceAccountDelegationInfo", + "Agent", + "AgentAnomaly", + "DetectorReference", + "InvocationReference", + "AgentSession", "Application", "Asset", "AttackExposure", diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent.py new file mode 100644 index 000000000000..56c849617d95 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", + manifest={ + "Agent", + }, +) + + +class Agent(proto.Message): + r"""Represents a monitored AI Agent. + + Attributes: + id (str): + Identifier of the agent. + display_name (str): + The user friendly name of the specific agent + instance where the finding was detected, for + example, "Banking Agent". + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent_anomaly.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent_anomaly.py new file mode 100644 index 000000000000..b4a6262982f0 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent_anomaly.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", + manifest={ + "AgentAnomaly", + "DetectorReference", + "InvocationReference", + }, +) + + +class AgentAnomaly(proto.Message): + r"""Represents details about an anomaly detected in an AI agent's + behavior. + + Attributes: + confidence_score (float): + The overall confidence score indicating the + likelihood that this session contains a true + anomaly. The score ranges from 0.0 to 1.0, where + 1.0 signifies 100% confidence in the presence of + an anomaly and 0.0 signifies 0% confidence. + detector_references (MutableSequence[google.cloud.securitycenter_v1.types.DetectorReference]): + The list of references to specific detectors + that identified anomalies within this session. + invocation_references (MutableSequence[google.cloud.securitycenter_v1.types.InvocationReference]): + References to the OpenTelemetry invocations. + """ + + confidence_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + detector_references: MutableSequence["DetectorReference"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="DetectorReference", + ) + invocation_references: MutableSequence["InvocationReference"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="InvocationReference", + ) + + +class DetectorReference(proto.Message): + r"""Represents a reference to a specific anomaly detector. + + Attributes: + severity (google.cloud.securitycenter_v1.types.DetectorReference.Severity): + The severity of the detector. + detector_id (str): + The unique identifier of the detector. + display_name (str): + A human readable name for the detector, + providing context on its purpose. For example, + "ASI02: Tool Misuse", or "Excessive API Calls". + explanation (str): + A detailed explanation generated by an LLM or + the detector itself, describing why this + specific anomaly was flagged. This provides + rationale and context for the detection. + recommendation (str): + Recommended steps or actions to remediate or + investigate the anomaly flagged by this + detector. These could include configuration + changes, code adjustments, or further diagnostic + procedures. + """ + + class Severity(proto.Enum): + r"""Severity levels for detectors. + + Values: + SEVERITY_UNSPECIFIED (0): + Unspecified severity. + CRITICAL (1): + Critical severity. + HIGH (2): + High severity. + MEDIUM (3): + Medium severity. + LOW (4): + Low severity. + """ + + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + severity: Severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + detector_id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + explanation: str = proto.Field( + proto.STRING, + number=4, + ) + recommendation: str = proto.Field( + proto.STRING, + number=5, + ) + + +class InvocationReference(proto.Message): + r"""Represents a reference to a specific OpenTelemetry + invocation. + + Attributes: + invocation_id (str): + The unique identifier of the invocation. + """ + + invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent_session.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent_session.py new file mode 100644 index 000000000000..b77c53502290 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/agent_session.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", + manifest={ + "AgentSession", + }, +) + + +class AgentSession(proto.Message): + r"""Represents a conversational session where the finding + occurred. + + Attributes: + session_id (str): + The session ID of a conversation. + """ + + session_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py index d31a9767a4cd..39b7a2938f5f 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v1/types/finding.py @@ -22,20 +22,10 @@ import proto # type: ignore from google.cloud.securitycenter_v1.types import access as gcs_access -from google.cloud.securitycenter_v1.types import application as gcs_application -from google.cloud.securitycenter_v1.types import attack_exposure as gcs_attack_exposure -from google.cloud.securitycenter_v1.types import ( - backup_disaster_recovery as gcs_backup_disaster_recovery, -) -from google.cloud.securitycenter_v1.types import chokepoint as gcs_chokepoint -from google.cloud.securitycenter_v1.types import cloud_armor as gcs_cloud_armor -from google.cloud.securitycenter_v1.types import ( - cloud_dlp_data_profile as gcs_cloud_dlp_data_profile, -) -from google.cloud.securitycenter_v1.types import ( - cloud_dlp_inspection as gcs_cloud_dlp_inspection, -) +from google.cloud.securitycenter_v1.types import agent as gcs_agent +from google.cloud.securitycenter_v1.types import agent_anomaly as gcs_agent_anomaly from google.cloud.securitycenter_v1.types import ( + agent_session, compliance, connection, contact_details, @@ -49,6 +39,19 @@ org_policy, process, ) +from google.cloud.securitycenter_v1.types import application as gcs_application +from google.cloud.securitycenter_v1.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v1.types import ( + backup_disaster_recovery as gcs_backup_disaster_recovery, +) +from google.cloud.securitycenter_v1.types import chokepoint as gcs_chokepoint +from google.cloud.securitycenter_v1.types import cloud_armor as gcs_cloud_armor +from google.cloud.securitycenter_v1.types import ( + cloud_dlp_data_profile as gcs_cloud_dlp_data_profile, +) +from google.cloud.securitycenter_v1.types import ( + cloud_dlp_inspection as gcs_cloud_dlp_inspection, +) from google.cloud.securitycenter_v1.types import database as gcs_database from google.cloud.securitycenter_v1.types import exfiltration as gcs_exfiltration from google.cloud.securitycenter_v1.types import ( @@ -311,6 +314,15 @@ class Finding(proto.Message): external_exposure (google.cloud.securitycenter_v1.types.ExternalExposure): External exposure associated with the finding. + agent (google.cloud.securitycenter_v1.types.Agent): + Primary Agent that the specified finding was + flagged for + agent_sessions (MutableSequence[google.cloud.securitycenter_v1.types.AgentSession]): + Conversational session(s) where the finding + occurred. + agent_anomaly (google.cloud.securitycenter_v1.types.AgentAnomaly): + Details about behavior anomalies detected in + AI agents. """ class State(proto.Enum): @@ -832,6 +844,21 @@ class DynamicMuteRecord(proto.Message): number=84, message=gcs_external_exposure.ExternalExposure, ) + agent: gcs_agent.Agent = proto.Field( + proto.MESSAGE, + number=88, + message=gcs_agent.Agent, + ) + agent_sessions: MutableSequence[agent_session.AgentSession] = proto.RepeatedField( + proto.MESSAGE, + number=89, + message=agent_session.AgentSession, + ) + agent_anomaly: gcs_agent_anomaly.AgentAnomaly = proto.Field( + proto.MESSAGE, + number=90, + message=gcs_agent_anomaly.AgentAnomaly, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py index 20f87f2e97b3..c801fdf47df5 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/__init__.py @@ -26,6 +26,9 @@ from .services.security_center import SecurityCenterAsyncClient, SecurityCenterClient from .types.access import Access, Geolocation, ServiceAccountDelegationInfo from .types.affected_resources import AffectedResources +from .types.agent import Agent +from .types.agent_anomaly import AgentAnomaly, DetectorReference, InvocationReference +from .types.agent_session import AgentSession from .types.ai_model import AiModel from .types.application import Application from .types.attack_exposure import AttackExposure @@ -243,6 +246,9 @@ def _get_version(dependency_name): "Access", "AdaptiveProtection", "AffectedResources", + "Agent", + "AgentAnomaly", + "AgentSession", "AiModel", "Allowed", "Application", @@ -287,6 +293,7 @@ def _get_version(dependency_name): "DeleteNotificationConfigRequest", "DeleteResourceValueConfigRequest", "Denied", + "DetectorReference", "Disk", "EnvironmentVariable", "ExfilResource", @@ -312,6 +319,7 @@ def _get_version(dependency_name): "GroupResult", "IamBinding", "Indicator", + "InvocationReference", "IpRule", "IpRules", "Job", diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py index a593876f80d7..21464b13d17e 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/async_client.py @@ -57,6 +57,9 @@ from google.cloud.securitycenter_v2.types import ( access, affected_resources, + agent, + agent_anomaly, + agent_session, ai_model, application, attack_exposure, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py index 281a42f314a6..1772260422a8 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/services/security_center/client.py @@ -74,6 +74,9 @@ from google.cloud.securitycenter_v2.types import ( access, affected_resources, + agent, + agent_anomaly, + agent_session, ai_model, application, attack_exposure, diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py index a8fdffbc221b..e5933d4f45b0 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/__init__.py @@ -21,6 +21,17 @@ from .affected_resources import ( AffectedResources, ) +from .agent import ( + Agent, +) +from .agent_anomaly import ( + AgentAnomaly, + DetectorReference, + InvocationReference, +) +from .agent_session import ( + AgentSession, +) from .ai_model import ( AiModel, ) @@ -263,6 +274,11 @@ "Geolocation", "ServiceAccountDelegationInfo", "AffectedResources", + "Agent", + "AgentAnomaly", + "DetectorReference", + "InvocationReference", + "AgentSession", "AiModel", "Application", "AttackExposure", diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent.py new file mode 100644 index 000000000000..5b8c7599cf9a --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "Agent", + }, +) + + +class Agent(proto.Message): + r"""Represents a monitored AI Agent. + + Attributes: + id (str): + Identifier of the agent. + display_name (str): + The user friendly name of the specific agent + instance where the finding was detected, for + example, "Banking Agent". + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent_anomaly.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent_anomaly.py new file mode 100644 index 000000000000..7241daeb0268 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent_anomaly.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "AgentAnomaly", + "DetectorReference", + "InvocationReference", + }, +) + + +class AgentAnomaly(proto.Message): + r"""Represents details about an anomaly detected in an AI agent's + behavior. + + Attributes: + confidence_score (float): + The overall confidence score indicating the + likelihood that this session contains a true + anomaly. The score ranges from 0.0 to 1.0, where + 1.0 signifies 100% confidence in the presence of + an anomaly and 0.0 signifies 0% confidence. + detector_references (MutableSequence[google.cloud.securitycenter_v2.types.DetectorReference]): + The list of references to specific detectors + that identified anomalies within this session. + invocation_references (MutableSequence[google.cloud.securitycenter_v2.types.InvocationReference]): + References to the OpenTelemetry invocations. + """ + + confidence_score: float = proto.Field( + proto.DOUBLE, + number=1, + ) + detector_references: MutableSequence["DetectorReference"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="DetectorReference", + ) + invocation_references: MutableSequence["InvocationReference"] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message="InvocationReference", + ) + + +class DetectorReference(proto.Message): + r"""Represents a reference to a specific anomaly detector. + + Attributes: + severity (google.cloud.securitycenter_v2.types.DetectorReference.Severity): + The severity of the detector. + detector_id (str): + The unique identifier of the detector. + display_name (str): + A human readable name for the detector, + providing context on its purpose. For example, + "ASI02: Tool Misuse", or "Excessive API Calls". + explanation (str): + A detailed explanation generated by an LLM or + the detector itself, describing why this + specific anomaly was flagged. This provides + rationale and context for the detection. + recommendation (str): + Recommended steps or actions to remediate or + investigate the anomaly flagged by this + detector. These could include configuration + changes, code adjustments, or further diagnostic + procedures. + """ + + class Severity(proto.Enum): + r"""Severity levels for detectors. + + Values: + SEVERITY_UNSPECIFIED (0): + Unspecified severity. + CRITICAL (1): + Critical severity. + HIGH (2): + High severity. + MEDIUM (3): + Medium severity. + LOW (4): + Low severity. + """ + + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + + severity: Severity = proto.Field( + proto.ENUM, + number=1, + enum=Severity, + ) + detector_id: str = proto.Field( + proto.STRING, + number=2, + ) + display_name: str = proto.Field( + proto.STRING, + number=3, + ) + explanation: str = proto.Field( + proto.STRING, + number=4, + ) + recommendation: str = proto.Field( + proto.STRING, + number=5, + ) + + +class InvocationReference(proto.Message): + r"""Represents a reference to a specific OpenTelemetry + invocation. + + Attributes: + invocation_id (str): + The unique identifier of the invocation. + """ + + invocation_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent_session.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent_session.py new file mode 100644 index 000000000000..87b78291a6f6 --- /dev/null +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/agent_session.py @@ -0,0 +1,45 @@ +# -*- coding: utf-8 -*- +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v2", + manifest={ + "AgentSession", + }, +) + + +class AgentSession(proto.Message): + r"""Represents a conversational session where the finding + occurred. + + Attributes: + session_id (str): + The session ID of a conversation. + """ + + session_id: str = proto.Field( + proto.STRING, + number=1, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py index 366aa535185c..a8feb2377ffc 100644 --- a/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py +++ b/packages/google-cloud-securitycenter/google/cloud/securitycenter_v2/types/finding.py @@ -25,21 +25,10 @@ from google.cloud.securitycenter_v2.types import ( affected_resources as gcs_affected_resources, ) -from google.cloud.securitycenter_v2.types import ai_model as gcs_ai_model -from google.cloud.securitycenter_v2.types import application as gcs_application -from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure -from google.cloud.securitycenter_v2.types import ( - backup_disaster_recovery as gcs_backup_disaster_recovery, -) -from google.cloud.securitycenter_v2.types import chokepoint as gcs_chokepoint -from google.cloud.securitycenter_v2.types import cloud_armor as gcs_cloud_armor -from google.cloud.securitycenter_v2.types import ( - cloud_dlp_data_profile as gcs_cloud_dlp_data_profile, -) -from google.cloud.securitycenter_v2.types import ( - cloud_dlp_inspection as gcs_cloud_dlp_inspection, -) +from google.cloud.securitycenter_v2.types import agent as gcs_agent +from google.cloud.securitycenter_v2.types import agent_anomaly as gcs_agent_anomaly from google.cloud.securitycenter_v2.types import ( + agent_session, compliance, connection, contact_details, @@ -57,6 +46,20 @@ org_policy, process, ) +from google.cloud.securitycenter_v2.types import ai_model as gcs_ai_model +from google.cloud.securitycenter_v2.types import application as gcs_application +from google.cloud.securitycenter_v2.types import attack_exposure as gcs_attack_exposure +from google.cloud.securitycenter_v2.types import ( + backup_disaster_recovery as gcs_backup_disaster_recovery, +) +from google.cloud.securitycenter_v2.types import chokepoint as gcs_chokepoint +from google.cloud.securitycenter_v2.types import cloud_armor as gcs_cloud_armor +from google.cloud.securitycenter_v2.types import ( + cloud_dlp_data_profile as gcs_cloud_dlp_data_profile, +) +from google.cloud.securitycenter_v2.types import ( + cloud_dlp_inspection as gcs_cloud_dlp_inspection, +) from google.cloud.securitycenter_v2.types import database as gcs_database from google.cloud.securitycenter_v2.types import disk as gcs_disk from google.cloud.securitycenter_v2.types import exfiltration as gcs_exfiltration @@ -377,6 +380,15 @@ class Finding(proto.Message): update requests. vertex_ai (google.cloud.securitycenter_v2.types.VertexAi): VertexAi associated with the finding. + agent (google.cloud.securitycenter_v2.types.Agent): + Primary Agent that the specified finding was + flagged for + agent_sessions (MutableSequence[google.cloud.securitycenter_v2.types.AgentSession]): + Conversational session(s) where the finding + occurred. + agent_anomaly (google.cloud.securitycenter_v2.types.AgentAnomaly): + Details about behavior anomalies detected in + AI agents. """ class State(proto.Enum): @@ -943,6 +955,21 @@ class DynamicMuteRecord(proto.Message): number=72, message=gcs_vertex_ai.VertexAi, ) + agent: gcs_agent.Agent = proto.Field( + proto.MESSAGE, + number=81, + message=gcs_agent.Agent, + ) + agent_sessions: MutableSequence[agent_session.AgentSession] = proto.RepeatedField( + proto.MESSAGE, + number=82, + message=agent_session.AgentSession, + ) + agent_anomaly: gcs_agent_anomaly.AgentAnomaly = proto.Field( + proto.MESSAGE, + number=83, + message=gcs_agent_anomaly.AgentAnomaly, + ) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py index 37ab890e7d39..b70cbeef22c1 100644 --- a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v1/test_security_center.py @@ -74,6 +74,9 @@ ) from google.cloud.securitycenter_v1.types import ( access, + agent, + agent_anomaly, + agent_session, application, attack_exposure, attack_path, @@ -45271,6 +45274,21 @@ def test_create_finding_rest_call_success(request_type): "instance_group": "instance_group_value", "network_endpoint_group": "network_endpoint_group_value", }, + "agent": {"id": "id_value", "display_name": "display_name_value"}, + "agent_sessions": [{"session_id": "session_id_value"}], + "agent_anomaly": { + "confidence_score": 0.1673, + "detector_references": [ + { + "severity": 1, + "detector_id": "detector_id_value", + "display_name": "display_name_value", + "explanation": "explanation_value", + "recommendation": "recommendation_value", + } + ], + "invocation_references": [{"invocation_id": "invocation_id_value"}], + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -50550,6 +50568,21 @@ def test_update_finding_rest_call_success(request_type): "instance_group": "instance_group_value", "network_endpoint_group": "network_endpoint_group_value", }, + "agent": {"id": "id_value", "display_name": "display_name_value"}, + "agent_sessions": [{"session_id": "session_id_value"}], + "agent_anomaly": { + "confidence_score": 0.1673, + "detector_references": [ + { + "severity": 1, + "detector_id": "detector_id_value", + "display_name": "display_name_value", + "explanation": "explanation_value", + "recommendation": "recommendation_value", + } + ], + "invocation_references": [{"invocation_id": "invocation_id_value"}], + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency diff --git a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py index 77d8696714b6..4cc9035d2eae 100644 --- a/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py +++ b/packages/google-cloud-securitycenter/tests/unit/gapic/securitycenter_v2/test_security_center.py @@ -75,6 +75,9 @@ from google.cloud.securitycenter_v2.types import ( access, affected_resources, + agent, + agent_anomaly, + agent_session, ai_model, application, attack_exposure, @@ -29559,6 +29562,21 @@ def test_create_finding_rest_call_success(request_type): ], "pipelines": [{"name": "name_value", "display_name": "display_name_value"}], }, + "agent": {"id": "id_value", "display_name": "display_name_value"}, + "agent_sessions": [{"session_id": "session_id_value"}], + "agent_anomaly": { + "confidence_score": 0.1673, + "detector_references": [ + { + "severity": 1, + "detector_id": "detector_id_value", + "display_name": "display_name_value", + "explanation": "explanation_value", + "recommendation": "recommendation_value", + } + ], + "invocation_references": [{"invocation_id": "invocation_id_value"}], + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -34692,6 +34710,21 @@ def test_update_finding_rest_call_success(request_type): ], "pipelines": [{"name": "name_value", "display_name": "display_name_value"}], }, + "agent": {"id": "id_value", "display_name": "display_name_value"}, + "agent_sessions": [{"session_id": "session_id_value"}], + "agent_anomaly": { + "confidence_score": 0.1673, + "detector_references": [ + { + "severity": 1, + "detector_id": "detector_id_value", + "display_name": "display_name_value", + "explanation": "explanation_value", + "recommendation": "recommendation_value", + } + ], + "invocation_references": [{"invocation_id": "invocation_id_value"}], + }, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency diff --git a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py index 3b4b05554a31..131b049b0e7a 100644 --- a/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py +++ b/packages/google-shopping-merchant-inventories/google/shopping/merchant_inventories_v1/types/inventories_common.py @@ -77,6 +77,14 @@ class LocalInventoryAttributes(proto.Message): store. Maximum length is 20 bytes. This field is a member of `oneof`_ ``_instore_product_location``. + local_shipping_label (str): + Optional. Specifies a label associated with the shipping for + the ``LocalInventory`` resource. Can be used to group local + shipping services to this particular inventory item. For + accepted field format, see the `Local + delivery `__ + + This field is a member of `oneof`_ ``_local_shipping_label``. loyalty_programs (MutableSequence[google.shopping.merchant_inventories_v1.types.InventoryLoyaltyProgram]): Optional. An optional list of loyalty programs containing applicable loyalty member prices for this product at this @@ -96,6 +104,17 @@ class LocalInventoryAttributes(proto.Message): configuration. For local inventory specific details, see the `Local inventory data specification `__. + custom_attributes (MutableSequence[google.shopping.type.types.CustomAttribute]): + Optional. A list of custom (merchant-provided) attributes. + It can also be used for submitting any attribute of the data + specification in its generic form (for example, + ``{ "name": "size type", "value": "regular" }``). This is + useful for submitting attributes not explicitly exposed by + the API. Maximum allowed number of characters for each + custom attribute is 10240 (represents sum of characters for + name and value). Maximum 2500 custom attributes can be set, + with total size of 102.4kB. Underscores in custom attribute + names are replaced by spaces upon insertion. """ class Availability(proto.Enum): @@ -234,11 +253,21 @@ class PickupSla(proto.Enum): number=8, optional=True, ) + local_shipping_label: str = proto.Field( + proto.STRING, + number=9, + optional=True, + ) loyalty_programs: MutableSequence["InventoryLoyaltyProgram"] = proto.RepeatedField( proto.MESSAGE, number=10, message="InventoryLoyaltyProgram", ) + custom_attributes: MutableSequence[types.CustomAttribute] = proto.RepeatedField( + proto.MESSAGE, + number=11, + message=types.CustomAttribute, + ) class InventoryLoyaltyProgram(proto.Message): diff --git a/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py index 1f56117d3fc0..c2798d88d476 100644 --- a/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py +++ b/packages/google-shopping-merchant-inventories/tests/unit/gapic/merchant_inventories_v1/test_local_inventory_service.py @@ -3594,6 +3594,7 @@ def test_insert_local_inventory_rest_call_success(request_type): "pickup_method": 1, "pickup_sla": 1, "instore_product_location": "instore_product_location_value", + "local_shipping_label": "local_shipping_label_value", "loyalty_programs": [ { "program_label": "program_label_value", @@ -3605,6 +3606,9 @@ def test_insert_local_inventory_rest_call_success(request_type): "shipping_label": "shipping_label_value", } ], + "custom_attributes": [ + {"name": "name_value", "value": "value_value", "group_values": {}} + ], }, } # The version of a generated dependency at test runtime may differ from the version used during generation. diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products/__init__.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products/__init__.py index cfca6e3009ad..1de8a84ed778 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products/__init__.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products/__init__.py @@ -60,6 +60,7 @@ LoyaltyPoints, LoyaltyProgram, Pause, + PickupCost, PickupMethod, PickupSla, ProductAttributes, @@ -67,6 +68,7 @@ ProductDetail, ProductDimension, ProductInstallment, + ProductMinimumOrderValue, ProductStatus, ProductSustainabilityIncentive, ProductWeight, @@ -102,11 +104,13 @@ "HandlingCutoffTime", "LoyaltyPoints", "LoyaltyProgram", + "PickupCost", "ProductAttributes", "ProductCertification", "ProductDetail", "ProductDimension", "ProductInstallment", + "ProductMinimumOrderValue", "ProductStatus", "ProductSustainabilityIncentive", "ProductWeight", diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/__init__.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/__init__.py index f853e9116a2d..b5426a488102 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/__init__.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/__init__.py @@ -58,6 +58,7 @@ LoyaltyPoints, LoyaltyProgram, Pause, + PickupCost, PickupMethod, PickupSla, ProductAttributes, @@ -65,6 +66,7 @@ ProductDetail, ProductDimension, ProductInstallment, + ProductMinimumOrderValue, ProductStatus, ProductSustainabilityIncentive, ProductWeight, @@ -189,6 +191,7 @@ def _get_version(dependency_name): "LoyaltyPoints", "LoyaltyProgram", "Pause", + "PickupCost", "PickupMethod", "PickupSla", "Product", @@ -199,6 +202,7 @@ def _get_version(dependency_name): "ProductInput", "ProductInputsServiceClient", "ProductInstallment", + "ProductMinimumOrderValue", "ProductStatus", "ProductSustainabilityIncentive", "ProductWeight", diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/__init__.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/__init__.py index eabdacf27cf9..7e933463e307 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/__init__.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/__init__.py @@ -43,6 +43,7 @@ LoyaltyPoints, LoyaltyProgram, Pause, + PickupCost, PickupMethod, PickupSla, ProductAttributes, @@ -50,6 +51,7 @@ ProductDetail, ProductDimension, ProductInstallment, + ProductMinimumOrderValue, ProductStatus, ProductSustainabilityIncentive, ProductWeight, @@ -81,11 +83,13 @@ "HandlingCutoffTime", "LoyaltyPoints", "LoyaltyProgram", + "PickupCost", "ProductAttributes", "ProductCertification", "ProductDetail", "ProductDimension", "ProductInstallment", + "ProductMinimumOrderValue", "ProductStatus", "ProductSustainabilityIncentive", "ProductWeight", diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products.py index 0e38fdeca65b..6052ed78f3b9 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products.py @@ -137,6 +137,13 @@ class Product(proto.Message): automated_discounts (google.shopping.merchant_products_v1.types.AutomatedDiscounts): Output only. The automated discounts information for the product. + archived (bool): + Output only. Determines whether the product is + `archived `__. + + To archive or restore your product, visit Merchant Center + products page. Learn also more about `offer + visibility `__. """ name: str = proto.Field( @@ -192,6 +199,10 @@ class Product(proto.Message): number=12, message=products_common.AutomatedDiscounts, ) + archived: bool = proto.Field( + proto.BOOL, + number=14, + ) class GetProductRequest(proto.Message): diff --git a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products_common.py b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products_common.py index 08315db51b6f..d13667cb6adc 100644 --- a/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products_common.py +++ b/packages/google-shopping-merchant-products/google/shopping/merchant_products_v1/types/products_common.py @@ -62,7 +62,9 @@ "CloudExportAdditionalProperties", "ProductSustainabilityIncentive", "AutomatedDiscounts", + "PickupCost", "HandlingCutoffTime", + "ProductMinimumOrderValue", }, ) @@ -990,6 +992,13 @@ class `__ SLA `__. This field is a member of `oneof`_ ``_pickup_sla``. + pickup_cost (google.shopping.merchant_products_v1.types.PickupCost): + Optional. The `pickup + cost `__ + for an item when a customer buys it online and picks it up + at a store. + + This field is a member of `oneof`_ ``_pickup_cost``. link_template (str): `Link template `__ @@ -1122,6 +1131,202 @@ class `__ your image attributes. See the `Help Center article `__ for more information. + minimum_order_values (MutableSequence[google.shopping.merchant_products_v1.types.ProductMinimumOrderValue]): + The `minimum + value `__ + in the cart before a customer can initiate checkout. + Supports multiple minimum order values. Different minimum + order values can be specified per country, service and + surface. Maximum entries: 100. + vin (str): + The `Vehicle Identification Number + (VIN) `__ + of the vehicle. + model (str): + The + `Model `__ + of the vehicle, such as ``LX``, ``EX``, and others. + trim (str): + The + `Trim `__ + of the vehicle model, such as ``S``, ``SV``, ``SL`` and + others. + body_style (google.shopping.merchant_products_v1.types.ProductAttributes.VehicleBodyStyle): + The `body + style `__ + of the vehicle. + year (int): + The + `Year `__ + of the vehicle model. + mileage (google.shopping.merchant_products_v1.types.ProductAttributes.Mileage): + The number of miles/kms on the vehicle. See the + `Mileage `__ + for more information. + electric_range (google.shopping.merchant_products_v1.types.ProductAttributes.Mileage): + The `electric + range `__ + of the vehicle in miles/kms. + fuel_consumption (google.shopping.merchant_products_v1.types.ProductAttributes.FuelConsumption): + The `fuel + consumption `__ + of the vehicle. + fuel_consumption_discharged_battery (google.shopping.merchant_products_v1.types.ProductAttributes.FuelConsumption): + The fuel consumption of the vehicle when the hybrid battery + is discharged. See the `Help Center + article `__ + for more information. + energy_consumption (google.shopping.merchant_products_v1.types.ProductAttributes.EnergyConsumption): + The `energy + consumption `__ + of the vehicle. + co2_emissions (google.shopping.merchant_products_v1.types.ProductAttributes.Co2Emissions): + The `co2 + emission `__ + of the vehicle. + date_first_registered (str): + The date the vehicle was first registered. Format: + ``YYYY-MM``. See the `Date first + registered `__ + for more information. + engine (google.shopping.merchant_products_v1.types.ProductAttributes.EngineType): + The + `engine `__ + type of the vehicle. + emissions_standard (google.shopping.merchant_products_v1.types.ProductAttributes.EmissionsStandard): + The `emission + standard `__ + of the vehicle. + certified_pre_owned (bool): + Whether the vehicle is OEM `certified + pre-owned `__. + vehicle_msrp (google.shopping.type.types.Price): + The MSRP (Manufacturer Suggested Retail Price) for the + vehicle in its current configuration. See the `Vehicle + MSRP `__ + for more information. + vehicle_all_in_price (google.shopping.type.types.Price): + The all-in advertised price for a vehicle, which includes + costs for the following – any accessories attached to the + vehicle, environmental levies, extra warranty, fuel, + freight, pre-delivery inspection (PDI), dealer fees for + handling licensing, provincial regulatory fees, + miscellaneous dealer charges for security etching and + nitrogen tire fill, and factory-to-customer or + dealer-to-customer discounts or incentives. See the `Vehicle + all-in + price `__ + for more information. + vehicle_price_type (google.shopping.merchant_products_v1.types.ProductAttributes.VehiclePriceType): + The `price + type `__ + of the vehicle. + vehicle_mandatory_inspection_included (bool): + Whether the vehicle is sold with mandatory inspection and + maintenance performed before delivery. See the `Vehicle + mandatory inspection + included `__ + for more information.\` + vehicle_expenses (google.shopping.type.types.Price): + The miscellaneous expenses like insurance and registration + fees of the vehicle. See the `Vehicle + expenses `__ + for more information. + warranty (google.shopping.merchant_products_v1.types.ProductAttributes.Warranty): + The + `warranty `__ + of the vehicle. + display_address (google.shopping.merchant_products_v1.types.ProductAttributes.DisplayAddress): + The display address of the property. + latitude (float): + The latitude of the property. The value must + be between -90 (inclusive) and 90 (inclusive), + up to 6 decimal places. + + This field is a member of `oneof`_ ``_latitude``. + longitude (float): + The longitude of the property. The value must + be between -180 (inclusive) and 180 (inclusive), + up to 6 decimal places. + + This field is a member of `oneof`_ ``_longitude``. + neighborhood (str): + The neighborhood (locality) of the property, such as + ``Wallingford``, ``Greenwood``, etc. + unit_area (google.shopping.merchant_products_v1.types.ProductAttributes.UnitArea): + The unit area of the property, such as ``1000 sqft``. + number_of_units (int): + The number of units available for a specific + floor plan of the property. The value must be + greater than 0. + + This field is a member of `oneof`_ ``_number_of_units``. + property_name (str): + The name of the property. + number_of_bedrooms (float): + The number of bedrooms in the property. The + value must be greater than or equal to 0 and a + multiple of 1.0. + + This field is a member of `oneof`_ ``_number_of_bedrooms``. + number_of_bathrooms (float): + The number of bathrooms in the property. The + value must be greater than 0 and a multiple of + 0.5. + + This field is a member of `oneof`_ ``_number_of_bathrooms``. + property_type (google.shopping.merchant_products_v1.types.ProductAttributes.PropertyType): + The type of property. + amenity_feature (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.AmenityFeature]): + The amenity features for the property. + utilities_included (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.UtilitiesIncluded]): + The utilities included for the property. + pet_policy (google.shopping.merchant_products_v1.types.ProductAttributes.PetPolicy): + The pet policy for the property. + specialty_housing_type (google.shopping.merchant_products_v1.types.ProductAttributes.SpecialtyHousingType): + The specialty housing type for the property. + product_fee (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.ProductFee]): + The product fee for the property. + short_title (str): + The short title of the item. + + This field is a member of `oneof`_ ``_short_title``. + questions_and_answers (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.QuestionAndAnswer]): + Optional. Contains user-, merchant-, and + manufacturer-authored `questions and + answers `__ + about the product. Max 30 question and answer pairs. Max + 10000 characters total. Each question can have max 1000 + characters. Each answer can have max 1000 characters. + popularity_rank (float): + Optional. Indicates the + `popularity `__ + of the product in a merchant's inventory. Using a scale of + 0.0 (lowest) to 100.0 (highest). + item_group_title (str): + Optional. Represents the `title of the product + group `__ + to which this variant product belongs. This can be used + along with the `item group + id `__ + attribute. It lets you perform better grouping of variant + products, and helps identifying common product + characteristics more efficiently. + document_links (MutableSequence[str]): + Optional. Contains a list of PDF `document + URLs `__ + for the product. Examples are training manuals, user guides, + assembly instructions, package inserts, etc. Must start with + "http://" or "https://"), ASCII characters only, and RFC + 3986 compliant. + variant_options (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.VariantOption]): + Optional. Contains the `list of all variant-identifying + options `__ + of this product. + related_products (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.RelatedProduct]): + Optional. Specifies how other `products are + related `__ + to this product. """ class CarrierPriceOption(proto.Enum): @@ -1325,6 +1530,421 @@ class CarrierPriceOption(proto.Enum): USPS_PRIORITY_MAIL = 60 USPS_GROUND_ADVANTAGE_COMMERCIAL = 61 + class VehicleBodyStyle(proto.Enum): + r"""The vehicle body style. See the `Body + style `__ for + more information. + + Values: + VEHICLE_BODY_STYLE_UNSPECIFIED (0): + Unspecified vehicle body style. + ATV_SPORT (1): + ATV Sport. + ATV_TOURING (2): + ATV Touring. + ATV_UTILITY (3): + ATV Utility. + ATV_YOUTH (4): + ATV Youth. + CITY_CAR (5): + City car. + CLASS_A_MOTORHOME (6): + Class A motorhome. + CLASS_B_MOTORHOME (7): + Class B motorhome. + CLASS_C_MOTORHOME (8): + Class C motorhome. + COMPACT_SUV (9): + Compact SUV. + CONVERTIBLE (10): + Convertible. + COUPE (11): + Coupe. + CROSSOVER (12): + Crossover. + FIFTH_WHEEL (13): + Fifth wheel. + FULL_SIZE_VAN (14): + Full size van. + HATCHBACK (15): + Hatchback. + LIMOUSINE (16): + Limousine. + MINIVAN (17): + Minivan. + NOTCHBACK (18): + Notchback. + POP_UP_CAMPER (19): + Pop up camper. + SEDAN (20): + Sedan. + SIDE_BY_SIDE (21): + Side by side. + STATION_WAGON (22): + Station wagon. + SUV (23): + SUV. + TRAVEL_TRAILER (24): + Travel trailer. + TRUCK (25): + Truck. + TRUCK_CAMPER (26): + Truck camper. + UTE (27): + Ute. + UTV_RECREATIONAL_UTILITY (28): + UTV Recreational utility. + UTV_SPORT (29): + UTV Sport. + UTV_UTILITY (30): + UTV Utility. + UTV_YOUTH (31): + UTV Youth. + """ + + VEHICLE_BODY_STYLE_UNSPECIFIED = 0 + ATV_SPORT = 1 + ATV_TOURING = 2 + ATV_UTILITY = 3 + ATV_YOUTH = 4 + CITY_CAR = 5 + CLASS_A_MOTORHOME = 6 + CLASS_B_MOTORHOME = 7 + CLASS_C_MOTORHOME = 8 + COMPACT_SUV = 9 + CONVERTIBLE = 10 + COUPE = 11 + CROSSOVER = 12 + FIFTH_WHEEL = 13 + FULL_SIZE_VAN = 14 + HATCHBACK = 15 + LIMOUSINE = 16 + MINIVAN = 17 + NOTCHBACK = 18 + POP_UP_CAMPER = 19 + SEDAN = 20 + SIDE_BY_SIDE = 21 + STATION_WAGON = 22 + SUV = 23 + TRAVEL_TRAILER = 24 + TRUCK = 25 + TRUCK_CAMPER = 26 + UTE = 27 + UTV_RECREATIONAL_UTILITY = 28 + UTV_SPORT = 29 + UTV_UTILITY = 30 + UTV_YOUTH = 31 + + class EngineType(proto.Enum): + r"""The engine type of the vehicle. + + Values: + ENGINE_TYPE_UNSPECIFIED (0): + Unspecified engine type. + GASOLINE (1): + Gasoline. + DIESEL (2): + Diesel. + ELECTRIC (3): + Electric. + HYBRID (4): + Hybrid. + PLUG_IN_HYBRID (5): + Plug-in hybrid. + NATURAL_GAS (6): + Natural gas. + LPG (7): + LPG. + METHANE (8): + Methane. + OTHER (9): + Other. + """ + + ENGINE_TYPE_UNSPECIFIED = 0 + GASOLINE = 1 + DIESEL = 2 + ELECTRIC = 3 + HYBRID = 4 + PLUG_IN_HYBRID = 5 + NATURAL_GAS = 6 + LPG = 7 + METHANE = 8 + OTHER = 9 + + class EmissionsStandard(proto.Enum): + r"""The emission standard of the vehicle. + + Values: + EMISSIONS_STANDARD_UNSPECIFIED (0): + Unspecified emission standard. + ZERO_EMISSIONS (1): + Zero emissions. + EURO1 (2): + Euro 1. + EURO2 (3): + Euro 2. + EURO3 (4): + Euro 3. + EURO4 (5): + Euro 4. + EURO5 (6): + Euro 5. + EURO5B (7): + Euro 5b. + EURO6 (8): + Euro 6. + EURO6C (9): + Euro 6c. + EURO6D (10): + Euro 6d. + EURO6D_TEMP (11): + Euro 6d-TEMP. + EURO6E (12): + Euro 6e. + """ + + EMISSIONS_STANDARD_UNSPECIFIED = 0 + ZERO_EMISSIONS = 1 + EURO1 = 2 + EURO2 = 3 + EURO3 = 4 + EURO4 = 5 + EURO5 = 6 + EURO5B = 7 + EURO6 = 8 + EURO6C = 9 + EURO6D = 10 + EURO6D_TEMP = 11 + EURO6E = 12 + + class VehiclePriceType(proto.Enum): + r"""The vehicle price type. + + Values: + VEHICLE_PRICE_TYPE_UNSPECIFIED (0): + Unspecified vehicle price type. + ALL_IN_PRICE (1): + All in price. + DRIVE_AWAY_PRICE (2): + Drive away price. + ESTIMATED_DRIVE_AWAY_PRICE (3): + Estimated drive away price. + EXCLUDING_GOVERNMENT_CHARGES_PRICE (4): + Excluding government charges price. + VEHICLE_BASE_PRICE (5): + Vehicle base price. + """ + + VEHICLE_PRICE_TYPE_UNSPECIFIED = 0 + ALL_IN_PRICE = 1 + DRIVE_AWAY_PRICE = 2 + ESTIMATED_DRIVE_AWAY_PRICE = 3 + EXCLUDING_GOVERNMENT_CHARGES_PRICE = 4 + VEHICLE_BASE_PRICE = 5 + + class PropertyType(proto.Enum): + r"""The property type. + + Values: + PROPERTY_TYPE_UNSPECIFIED (0): + Unspecified property type. + APARTMENT (1): + Apartment. + CONDO (2): + Condo. + LOFT (3): + Loft. + MULTI_FAMILY_HOME (4): + Multi-family home. + PENTHOUSE (5): + Penthouse. + ROOM (6): + Room. + SINGLE_FAMILY_HOME (7): + Single-family home. + STUDIO (8): + Studio. + TOWNHOUSE (9): + Townhouse. + """ + + PROPERTY_TYPE_UNSPECIFIED = 0 + APARTMENT = 1 + CONDO = 2 + LOFT = 3 + MULTI_FAMILY_HOME = 4 + PENTHOUSE = 5 + ROOM = 6 + SINGLE_FAMILY_HOME = 7 + STUDIO = 8 + TOWNHOUSE = 9 + + class AmenityFeature(proto.Enum): + r"""The amenity features for the property. + + Values: + AMENITY_FEATURE_UNSPECIFIED (0): + Unspecified amenity feature. + BALCONY (1): + Balcony. + BASEMENT (2): + Basement. + BASKETBALL_COURT (3): + Basketball court. + BIKE_STORAGE (4): + Bike storage. + CENTRAL_AC (5): + Central air conditioning. + DISHWASHER (6): + Dishwasher. + DOG_PARK (7): + Dog park. + ELEVATOR (8): + Elevator. + EV_CHARGING (9): + EV charging. + FENCED_LOT (10): + Fenced lot. + FIREPLACE (11): + Fireplace. + FITNESS_CENTER (12): + Fitness center. + FORCED_AIR_HEATING (13): + Forced air heating. + FULLY_FURNISHED (14): + Fully furnished. + GARAGE (15): + Garage. + GATED_COMMUNITY (16): + Gated community. + HARDWOOD_FLOORS (17): + Hardwood floors. + HIGH_SPEED_INTERNET (18): + High speed internet. + INTERCOM (19): + Intercom. + IN_UNIT_WASHER_DRYER (20): + In-unit washer and dryer. + KITCHEN (21): + Kitchen. + LARGE_CLOSETS (22): + Large closets. + MULTISPORT_COURT (23): + Multisport court. + ONSITE_LAUNDRY (24): + Onsite laundry. + OUTDOOR_LOUNGE (25): + Outdoor lounge. + PARKING (26): + Parking. + PATIO (27): + Patio. + PICKLEBALL_COURT (28): + Pickleball court. + POOL (29): + Pool. + REFRIGERATOR (30): + Refrigerator. + SOCCER_FIELD (31): + Soccer field. + TENNIS_COURT (32): + Tennis court. + WALK_IN_CLOSETS (33): + Walk-in closets. + WHEELCHAIR_ACCESS (34): + Wheelchair accessibility. + """ + + AMENITY_FEATURE_UNSPECIFIED = 0 + BALCONY = 1 + BASEMENT = 2 + BASKETBALL_COURT = 3 + BIKE_STORAGE = 4 + CENTRAL_AC = 5 + DISHWASHER = 6 + DOG_PARK = 7 + ELEVATOR = 8 + EV_CHARGING = 9 + FENCED_LOT = 10 + FIREPLACE = 11 + FITNESS_CENTER = 12 + FORCED_AIR_HEATING = 13 + FULLY_FURNISHED = 14 + GARAGE = 15 + GATED_COMMUNITY = 16 + HARDWOOD_FLOORS = 17 + HIGH_SPEED_INTERNET = 18 + INTERCOM = 19 + IN_UNIT_WASHER_DRYER = 20 + KITCHEN = 21 + LARGE_CLOSETS = 22 + MULTISPORT_COURT = 23 + ONSITE_LAUNDRY = 24 + OUTDOOR_LOUNGE = 25 + PARKING = 26 + PATIO = 27 + PICKLEBALL_COURT = 28 + POOL = 29 + REFRIGERATOR = 30 + SOCCER_FIELD = 31 + TENNIS_COURT = 32 + WALK_IN_CLOSETS = 33 + WHEELCHAIR_ACCESS = 34 + + class UtilitiesIncluded(proto.Enum): + r"""The utilities included for the property. + + Values: + UTILITIES_INCLUDED_UNSPECIFIED (0): + Unspecified utilities included. + ELECTRICITY (1): + Electricity. + GAS (2): + Gas. + INTERNET (3): + Internet. + TRASH (4): + Trash. + WATER (5): + Water. + """ + + UTILITIES_INCLUDED_UNSPECIFIED = 0 + ELECTRICITY = 1 + GAS = 2 + INTERNET = 3 + TRASH = 4 + WATER = 5 + + class SpecialtyHousingType(proto.Enum): + r"""The specialty housing type for the property. + + Values: + SPECIALTY_HOUSING_TYPE_UNSPECIFIED (0): + Unspecified specialty housing type. + CORPORATE (1): + Corporate housing. + LOW_INCOME (2): + Low income housing. + MILITARY (3): + Military housing. + SENIOR (4): + Senior housing. + SHORT_TERM (5): + Short term housing. + STUDENT (6): + Student housing. + """ + + SPECIALTY_HOUSING_TYPE_UNSPECIFIED = 0 + CORPORATE = 1 + LOW_INCOME = 2 + MILITARY = 3 + SENIOR = 4 + SHORT_TERM = 5 + STUDENT = 6 + class ShippingBusinessDaysConfig(proto.Message): r"""The business days during which orders are on their path to fulfillment. If not provided, Monday to Friday business days @@ -1574,6 +2194,472 @@ class CarrierShipping(proto.Message): enum="CarrierTransitTimeOption", ) + class Mileage(proto.Message): + r"""The mileage of the vehicle. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (int): + The distance value. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_products_v1.types.ProductAttributes.Mileage.Unit): + The unit of the mileage. + """ + + class Unit(proto.Enum): + r"""The unit of the mileage. + + Values: + UNIT_UNSPECIFIED (0): + Unspecified unit. + MILES (1): + Miles. + KM (2): + Kilometers. + """ + + UNIT_UNSPECIFIED = 0 + MILES = 1 + KM = 2 + + value: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + unit: "ProductAttributes.Mileage.Unit" = proto.Field( + proto.ENUM, + number=2, + enum="ProductAttributes.Mileage.Unit", + ) + + class FuelConsumption(proto.Message): + r"""The fuel consumption of the vehicle. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + The fuel consumption value. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_products_v1.types.ProductAttributes.FuelConsumption.Unit): + The unit of the fuel consumption. + """ + + class Unit(proto.Enum): + r"""The unit of the fuel consumption. + + Values: + UNIT_UNSPECIFIED (0): + Unspecified unit. + LPER100KM (1): + Liter per 100 kilometers. + KGPER100KM (2): + Kilograms per 100 kilometers. + """ + + UNIT_UNSPECIFIED = 0 + LPER100KM = 1 + KGPER100KM = 2 + + value: float = proto.Field( + proto.DOUBLE, + number=1, + optional=True, + ) + unit: "ProductAttributes.FuelConsumption.Unit" = proto.Field( + proto.ENUM, + number=2, + enum="ProductAttributes.FuelConsumption.Unit", + ) + + class EnergyConsumption(proto.Message): + r"""The energy consumption of the vehicle. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + The energy consumption value. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_products_v1.types.ProductAttributes.EnergyConsumption.Unit): + The unit of the energy consumption. + """ + + class Unit(proto.Enum): + r"""The unit of the energy consumption. + + Values: + UNIT_UNSPECIFIED (0): + Unspecified unit. + KWHPER100KM (1): + Kilowatt hours per 100 kilometers. + """ + + UNIT_UNSPECIFIED = 0 + KWHPER100KM = 1 + + value: float = proto.Field( + proto.DOUBLE, + number=1, + optional=True, + ) + unit: "ProductAttributes.EnergyConsumption.Unit" = proto.Field( + proto.ENUM, + number=2, + enum="ProductAttributes.EnergyConsumption.Unit", + ) + + class Co2Emissions(proto.Message): + r"""The co2 emission of the vehicle. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (int): + The co2 emission value. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_products_v1.types.ProductAttributes.Co2Emissions.Unit): + The unit of the co2 emission. + """ + + class Unit(proto.Enum): + r"""The unit of the co2 emission. + + Values: + UNIT_UNSPECIFIED (0): + Unspecified unit. + GPERKM (1): + Grams per kilometer. + """ + + UNIT_UNSPECIFIED = 0 + GPERKM = 1 + + value: int = proto.Field( + proto.INT64, + number=1, + optional=True, + ) + unit: "ProductAttributes.Co2Emissions.Unit" = proto.Field( + proto.ENUM, + number=2, + enum="ProductAttributes.Co2Emissions.Unit", + ) + + class Warranty(proto.Message): + r"""The warranty of the vehicle. + + Attributes: + duration (int): + The warranty duration in months. + mileage (google.shopping.merchant_products_v1.types.ProductAttributes.Mileage): + The warranty mileage. + """ + + duration: int = proto.Field( + proto.INT64, + number=1, + ) + mileage: "ProductAttributes.Mileage" = proto.Field( + proto.MESSAGE, + number=2, + message="ProductAttributes.Mileage", + ) + + class ProductFee(proto.Message): + r"""The product fee attribute containing type and amount. + + Attributes: + type_ (google.shopping.merchant_products_v1.types.ProductAttributes.ProductFee.FeeType): + The type of product fee. + amount (google.shopping.type.types.Price): + The amount of product fee. + """ + + class FeeType(proto.Enum): + r"""The type of product fee. + + Values: + FEE_TYPE_UNSPECIFIED (0): + Unspecified fee type. + ADMIN_FEE (1): + Admin fee. + APPLICATION_FEE (2): + Application fee. + SECURITY_DEPOSIT (3): + Security deposit. + """ + + FEE_TYPE_UNSPECIFIED = 0 + ADMIN_FEE = 1 + APPLICATION_FEE = 2 + SECURITY_DEPOSIT = 3 + + type_: "ProductAttributes.ProductFee.FeeType" = proto.Field( + proto.ENUM, + number=1, + enum="ProductAttributes.ProductFee.FeeType", + ) + amount: types.Price = proto.Field( + proto.MESSAGE, + number=2, + message=types.Price, + ) + + class DisplayAddress(proto.Message): + r"""The display address of the property. + + Attributes: + street_number (str): + The street number. + street_name (str): + The street name. + city (str): + The city such as Seattle, New York, etc. + region (str): + The region(state), such as WA, OH, etc. + postal_code (str): + The postal code, such as 94043. + """ + + street_number: str = proto.Field( + proto.STRING, + number=1, + ) + street_name: str = proto.Field( + proto.STRING, + number=2, + ) + city: str = proto.Field( + proto.STRING, + number=3, + ) + region: str = proto.Field( + proto.STRING, + number=4, + ) + postal_code: str = proto.Field( + proto.STRING, + number=5, + ) + + class UnitArea(proto.Message): + r"""The unit area of the property. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (float): + The area value. + + This field is a member of `oneof`_ ``_value``. + unit (google.shopping.merchant_products_v1.types.ProductAttributes.UnitArea.Unit): + The unit of area. + """ + + class Unit(proto.Enum): + r"""The unit of area. + + Values: + UNIT_UNSPECIFIED (0): + Unspecified unit. + SQM (1): + Square meters. + SQFT (2): + Square feet. + """ + + UNIT_UNSPECIFIED = 0 + SQM = 1 + SQFT = 2 + + value: float = proto.Field( + proto.DOUBLE, + number=1, + optional=True, + ) + unit: "ProductAttributes.UnitArea.Unit" = proto.Field( + proto.ENUM, + number=2, + enum="ProductAttributes.UnitArea.Unit", + ) + + class PetPolicy(proto.Message): + r"""The pet policy of the property. + + Attributes: + pets_allowed (bool): + Whether pets are allowed. + pet_types (MutableSequence[google.shopping.merchant_products_v1.types.ProductAttributes.PetPolicy.PetType]): + The pet types allowed. + """ + + class PetType(proto.Enum): + r"""The pet types. + + Values: + PET_TYPE_UNSPECIFIED (0): + Unspecified pet type. + CATS (1): + Cats. + LARGE_DOGS (2): + Large dogs. + SMALL_DOGS (3): + Small dogs. + """ + + PET_TYPE_UNSPECIFIED = 0 + CATS = 1 + LARGE_DOGS = 2 + SMALL_DOGS = 3 + + pets_allowed: bool = proto.Field( + proto.BOOL, + number=1, + ) + pet_types: MutableSequence["ProductAttributes.PetPolicy.PetType"] = ( + proto.RepeatedField( + proto.ENUM, + number=2, + enum="ProductAttributes.PetPolicy.PetType", + ) + ) + + class QuestionAndAnswer(proto.Message): + r"""The question and answer for the product. + + Attributes: + question (str): + Required. The question text. + answer (str): + Required. The answer text. + """ + + question: str = proto.Field( + proto.STRING, + number=1, + ) + answer: str = proto.Field( + proto.STRING, + number=2, + ) + + class VariantOption(proto.Message): + r"""Additional product variants for the product. + + Attributes: + name (str): + Required. The name of the variant. For + example, "Color", "Memory", "Size", "Length". + value (str): + Required. The value of the variant. For + example, "Red", "128GB", "XL", "100cm". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + class RelatedProduct(proto.Message): + r"""Specifies how other products are related to this product. + + Attributes: + relationship_type (google.shopping.merchant_products_v1.types.ProductAttributes.RelatedProduct.RelationshipType): + Required. The type of the relationship + between this product and the related product. + id_type (google.shopping.merchant_products_v1.types.ProductAttributes.RelatedProduct.IdType): + Required. The type of the identifier of the related product. + For example, + `GTIN `__ + or `product + ID `__. + id (str): + Required. The identifier of the related + product. + """ + + class RelationshipType(proto.Enum): + r"""The various types of the relationships between this product + and the related product. + + Values: + RELATIONSHIP_TYPE_UNSPECIFIED (0): + The relationship type is unspecified. + PART_OF_SET (1): + Part of a set of products that are often + purchased together. + REQUIRED_PART (2): + Part that is necessary for the product to + function, for example a battery for a + battery-operated lamp. + OFTEN_BOUGHT_WITH (3): + A product that this product is often + purchased together with, for example a phone + case with a phone. + SUBSTITUTE (4): + Product that this product can be substituted + for. For example a printer comparable in + function to another printer. + DIFFERENT_BRAND (5): + An identical product sold under a different + brand, for example a cheaper house brand. + ACCESSORY (6): + An accessory to this product, for example a + side table that matches the style of a couch. + """ + + RELATIONSHIP_TYPE_UNSPECIFIED = 0 + PART_OF_SET = 1 + REQUIRED_PART = 2 + OFTEN_BOUGHT_WITH = 3 + SUBSTITUTE = 4 + DIFFERENT_BRAND = 5 + ACCESSORY = 6 + + class IdType(proto.Enum): + r"""The type of the identifier of the related product. + + Values: + ID_TYPE_UNSPECIFIED (0): + The identifier type is unspecified. + GTIN (1): + The identifier is a GTIN. + ID (2): + The identifier is a product ID in the feed. + """ + + ID_TYPE_UNSPECIFIED = 0 + GTIN = 1 + ID = 2 + + relationship_type: "ProductAttributes.RelatedProduct.RelationshipType" = ( + proto.Field( + proto.ENUM, + number=1, + enum="ProductAttributes.RelatedProduct.RelationshipType", + ) + ) + id_type: "ProductAttributes.RelatedProduct.IdType" = proto.Field( + proto.ENUM, + number=2, + enum="ProductAttributes.RelatedProduct.IdType", + ) + id: str = proto.Field( + proto.STRING, + number=3, + ) + identifier_exists: bool = proto.Field( proto.BOOL, number=4, @@ -1968,6 +3054,12 @@ class CarrierShipping(proto.Message): optional=True, enum="PickupSla", ) + pickup_cost: "PickupCost" = proto.Field( + proto.MESSAGE, + number=172, + optional=True, + message="PickupCost", + ) link_template: str = proto.Field( proto.STRING, number=82, @@ -2081,6 +3173,216 @@ class CarrierShipping(proto.Message): proto.STRING, number=169, ) + minimum_order_values: MutableSequence["ProductMinimumOrderValue"] = ( + proto.RepeatedField( + proto.MESSAGE, + number=146, + message="ProductMinimumOrderValue", + ) + ) + vin: str = proto.Field( + proto.STRING, + number=147, + ) + model: str = proto.Field( + proto.STRING, + number=148, + ) + trim: str = proto.Field( + proto.STRING, + number=149, + ) + body_style: VehicleBodyStyle = proto.Field( + proto.ENUM, + number=150, + enum=VehicleBodyStyle, + ) + year: int = proto.Field( + proto.INT64, + number=151, + ) + mileage: Mileage = proto.Field( + proto.MESSAGE, + number=152, + message=Mileage, + ) + electric_range: Mileage = proto.Field( + proto.MESSAGE, + number=153, + message=Mileage, + ) + fuel_consumption: FuelConsumption = proto.Field( + proto.MESSAGE, + number=154, + message=FuelConsumption, + ) + fuel_consumption_discharged_battery: FuelConsumption = proto.Field( + proto.MESSAGE, + number=155, + message=FuelConsumption, + ) + energy_consumption: EnergyConsumption = proto.Field( + proto.MESSAGE, + number=156, + message=EnergyConsumption, + ) + co2_emissions: Co2Emissions = proto.Field( + proto.MESSAGE, + number=157, + message=Co2Emissions, + ) + date_first_registered: str = proto.Field( + proto.STRING, + number=158, + ) + engine: EngineType = proto.Field( + proto.ENUM, + number=159, + enum=EngineType, + ) + emissions_standard: EmissionsStandard = proto.Field( + proto.ENUM, + number=160, + enum=EmissionsStandard, + ) + certified_pre_owned: bool = proto.Field( + proto.BOOL, + number=161, + ) + vehicle_msrp: types.Price = proto.Field( + proto.MESSAGE, + number=162, + message=types.Price, + ) + vehicle_all_in_price: types.Price = proto.Field( + proto.MESSAGE, + number=163, + message=types.Price, + ) + vehicle_price_type: VehiclePriceType = proto.Field( + proto.ENUM, + number=164, + enum=VehiclePriceType, + ) + vehicle_mandatory_inspection_included: bool = proto.Field( + proto.BOOL, + number=166, + ) + vehicle_expenses: types.Price = proto.Field( + proto.MESSAGE, + number=167, + message=types.Price, + ) + warranty: Warranty = proto.Field( + proto.MESSAGE, + number=168, + message=Warranty, + ) + display_address: DisplayAddress = proto.Field( + proto.MESSAGE, + number=179, + message=DisplayAddress, + ) + latitude: float = proto.Field( + proto.DOUBLE, + number=180, + optional=True, + ) + longitude: float = proto.Field( + proto.DOUBLE, + number=181, + optional=True, + ) + neighborhood: str = proto.Field( + proto.STRING, + number=182, + ) + unit_area: UnitArea = proto.Field( + proto.MESSAGE, + number=183, + message=UnitArea, + ) + number_of_units: int = proto.Field( + proto.INT64, + number=184, + optional=True, + ) + property_name: str = proto.Field( + proto.STRING, + number=185, + ) + number_of_bedrooms: float = proto.Field( + proto.DOUBLE, + number=186, + optional=True, + ) + number_of_bathrooms: float = proto.Field( + proto.DOUBLE, + number=187, + optional=True, + ) + property_type: PropertyType = proto.Field( + proto.ENUM, + number=188, + enum=PropertyType, + ) + amenity_feature: MutableSequence[AmenityFeature] = proto.RepeatedField( + proto.ENUM, + number=189, + enum=AmenityFeature, + ) + utilities_included: MutableSequence[UtilitiesIncluded] = proto.RepeatedField( + proto.ENUM, + number=190, + enum=UtilitiesIncluded, + ) + pet_policy: PetPolicy = proto.Field( + proto.MESSAGE, + number=191, + message=PetPolicy, + ) + specialty_housing_type: SpecialtyHousingType = proto.Field( + proto.ENUM, + number=192, + enum=SpecialtyHousingType, + ) + product_fee: MutableSequence[ProductFee] = proto.RepeatedField( + proto.MESSAGE, + number=193, + message=ProductFee, + ) + short_title: str = proto.Field( + proto.STRING, + number=194, + optional=True, + ) + questions_and_answers: MutableSequence[QuestionAndAnswer] = proto.RepeatedField( + proto.MESSAGE, + number=173, + message=QuestionAndAnswer, + ) + popularity_rank: float = proto.Field( + proto.FLOAT, + number=174, + ) + item_group_title: str = proto.Field( + proto.STRING, + number=175, + ) + document_links: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=176, + ) + variant_options: MutableSequence[VariantOption] = proto.RepeatedField( + proto.MESSAGE, + number=177, + message=VariantOption, + ) + related_products: MutableSequence[RelatedProduct] = proto.RepeatedField( + proto.MESSAGE, + number=178, + message=RelatedProduct, + ) class ShippingWeight(proto.Message): @@ -2223,6 +3525,11 @@ class ProductInstallment(proto.Message): Optional. Annual percentage rate for ``credit_type`` finance This field is a member of `oneof`_ ``_annual_percentage_rate``. + total_amount (google.shopping.type.types.Price): + Optional. Total amount the buyer has to pay, + including interest. + + This field is a member of `oneof`_ ``_total_amount``. """ months: int = proto.Field( @@ -2251,6 +3558,12 @@ class ProductInstallment(proto.Message): number=5, optional=True, ) + total_amount: types.Price = proto.Field( + proto.MESSAGE, + number=6, + optional=True, + message=types.Price, + ) class LoyaltyPoints(proto.Message): @@ -2488,6 +3801,25 @@ class Shipping(proto.Message): handling cutoff time will default to 8AM PST. This field is a member of `oneof`_ ``_handling_cutoff_timezone``. + loyalty_program_label (str): + Optional. The label of the `loyalty + program `__. + Must match one of the program labels set in + [loyalty_programs][google.shopping.merchant.products.v1.LoyaltyProgram]. + When set (in combination with + `loyalty_tier_label `__), + this shipping option is only applicable to loyalty program + members of the specified tier. + loyalty_tier_label (str): + Optional. The label of the `loyalty + tier `__ + within the loyalty program. Must match one of the tiers set + in the + [loyalty_programs][google.shopping.merchant.products.v1.LoyaltyProgram]. + When set (in combination with + `loyalty_program_label `__), + this shipping option is only applicable to loyalty program + members of the specified tier. """ price: types.Price = proto.Field( @@ -2549,6 +3881,14 @@ class Shipping(proto.Message): number=13, optional=True, ) + loyalty_program_label: str = proto.Field( + proto.STRING, + number=14, + ) + loyalty_tier_label: str = proto.Field( + proto.STRING, + number=15, + ) class FreeShippingThreshold(proto.Message): @@ -3161,6 +4501,38 @@ class AutomatedDiscounts(proto.Message): ) +class PickupCost(proto.Message): + r"""The pickup cost of the item. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + flat_rate (google.shopping.type.types.Price): + Required. The flat rate pickup cost of the + item. + + This field is a member of `oneof`_ ``_flat_rate``. + free_threshold (google.shopping.type.types.Price): + Optional. The price threshold above which + pickup is free of charge. + + This field is a member of `oneof`_ ``_free_threshold``. + """ + + flat_rate: types.Price = proto.Field( + proto.MESSAGE, + number=1, + optional=True, + message=types.Price, + ) + free_threshold: types.Price = proto.Field( + proto.MESSAGE, + number=2, + optional=True, + message=types.Price, + ) + + class HandlingCutoffTime(proto.Message): r"""Configuration for offer or offer-country level shipping handling cutoff time. @@ -3221,4 +4593,81 @@ class HandlingCutoffTime(proto.Message): ) +class ProductMinimumOrderValue(proto.Message): + r"""The minimum order value in the cart before the checkout is + permitted. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + country (str): + Required. The `CLDR territory + code `__ + of the country to which an item will ship. + + This field is a member of `oneof`_ ``_country``. + service (str): + A free-form description of the service class or delivery + speed. This should match the service value set for the + Shipping attribute. See + [service][google.shopping.merchant.products.v1.Shipping.service]. + + This field is a member of `oneof`_ ``_service``. + surface (google.shopping.merchant_products_v1.types.ProductMinimumOrderValue.Surface): + The surface to which the minimum order value applies. + Defaults to ``ONLINE_LOCAL`` if not configured. + + This field is a member of `oneof`_ ``_surface``. + price (google.shopping.type.types.Price): + Required. The minimum cart or basket value + before the checkout is permitted. + + This field is a member of `oneof`_ ``_price``. + """ + + class Surface(proto.Enum): + r"""The surface values to which the minimum order value applies. + + Values: + SURFACE_UNSPECIFIED (0): + Surface is unspecified. + ONLINE (1): + Surface value to indicate online purchases. + LOCAL (2): + Surface value to indicate local purchases. + ONLINE_LOCAL (3): + Surface value to indicate online and local + purchases. + """ + + SURFACE_UNSPECIFIED = 0 + ONLINE = 1 + LOCAL = 2 + ONLINE_LOCAL = 3 + + country: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + service: str = proto.Field( + proto.STRING, + number=2, + optional=True, + ) + surface: Surface = proto.Field( + proto.ENUM, + number=3, + optional=True, + enum=Surface, + ) + price: types.Price = proto.Field( + proto.MESSAGE, + number=4, + optional=True, + message=types.Price, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_product_inputs_service.py b/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_product_inputs_service.py index 777e90bd1869..fea07ec6cd4a 100644 --- a/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_product_inputs_service.py +++ b/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_product_inputs_service.py @@ -3338,6 +3338,7 @@ def test_insert_product_input_rest_call_success(request_type): "downpayment": {}, "credit_type": 1, "annual_percentage_rate": 0.2311, + "total_amount": {}, }, "subscription_cost": {"period": 1, "period_length": 1380, "amount": {}}, "loyalty_points": { @@ -3379,6 +3380,8 @@ def test_insert_product_input_rest_call_success(request_type): "max_transit_time": 1720, "handling_cutoff_time": "handling_cutoff_time_value", "handling_cutoff_timezone": "handling_cutoff_timezone_value", + "loyalty_program_label": "loyalty_program_label_value", + "loyalty_tier_label": "loyalty_tier_label_value", } ], "carrier_shipping": [ @@ -3457,6 +3460,7 @@ def test_insert_product_input_rest_call_success(request_type): "promotion_ids": ["promotion_ids_value1", "promotion_ids_value2"], "pickup_method": 1, "pickup_sla": 1, + "pickup_cost": {"flat_rate": {}, "free_threshold": {}}, "link_template": "link_template_value", "mobile_link_template": "mobile_link_template_value", "custom_label_0": "custom_label_0_value", @@ -3507,6 +3511,67 @@ def test_insert_product_input_rest_call_success(request_type): {"amount": {}, "percentage": 0.10540000000000001, "type_": 1} ], "video_links": ["video_links_value1", "video_links_value2"], + "minimum_order_values": [ + { + "country": "country_value", + "service": "service_value", + "surface": 1, + "price": {}, + } + ], + "vin": "vin_value", + "model": "model_value", + "trim": "trim_value", + "body_style": 1, + "year": 433, + "mileage": {"value": 541, "unit": 1}, + "electric_range": {}, + "fuel_consumption": {"value": 0.541, "unit": 1}, + "fuel_consumption_discharged_battery": {}, + "energy_consumption": {"value": 0.541, "unit": 1}, + "co2_emissions": {"value": 541, "unit": 1}, + "date_first_registered": "date_first_registered_value", + "engine": 1, + "emissions_standard": 1, + "certified_pre_owned": True, + "vehicle_msrp": {}, + "vehicle_all_in_price": {}, + "vehicle_price_type": 1, + "vehicle_mandatory_inspection_included": True, + "vehicle_expenses": {}, + "warranty": {"duration": 870, "mileage": {}}, + "display_address": { + "street_number": "street_number_value", + "street_name": "street_name_value", + "city": "city_value", + "region": "region_value", + "postal_code": "postal_code_value", + }, + "latitude": 0.86, + "longitude": 0.971, + "neighborhood": "neighborhood_value", + "unit_area": {"value": 0.541, "unit": 1}, + "number_of_units": 1615, + "property_name": "property_name_value", + "number_of_bedrooms": 0.19110000000000002, + "number_of_bathrooms": 0.20270000000000002, + "property_type": 1, + "amenity_feature": [1], + "utilities_included": [1], + "pet_policy": {"pets_allowed": True, "pet_types": [1]}, + "specialty_housing_type": 1, + "product_fee": [{"type_": 1, "amount": {}}], + "short_title": "short_title_value", + "questions_and_answers": [ + {"question": "question_value", "answer": "answer_value"} + ], + "popularity_rank": 0.1636, + "item_group_title": "item_group_title_value", + "document_links": ["document_links_value1", "document_links_value2"], + "variant_options": [{"name": "name_value", "value": "value_value"}], + "related_products": [ + {"relationship_type": 1, "id_type": 1, "id": "id_value"} + ], }, "custom_attributes": [ {"name": "name_value", "value": "value_value", "group_values": {}} @@ -3773,6 +3838,7 @@ def test_update_product_input_rest_call_success(request_type): "downpayment": {}, "credit_type": 1, "annual_percentage_rate": 0.2311, + "total_amount": {}, }, "subscription_cost": {"period": 1, "period_length": 1380, "amount": {}}, "loyalty_points": { @@ -3814,6 +3880,8 @@ def test_update_product_input_rest_call_success(request_type): "max_transit_time": 1720, "handling_cutoff_time": "handling_cutoff_time_value", "handling_cutoff_timezone": "handling_cutoff_timezone_value", + "loyalty_program_label": "loyalty_program_label_value", + "loyalty_tier_label": "loyalty_tier_label_value", } ], "carrier_shipping": [ @@ -3892,6 +3960,7 @@ def test_update_product_input_rest_call_success(request_type): "promotion_ids": ["promotion_ids_value1", "promotion_ids_value2"], "pickup_method": 1, "pickup_sla": 1, + "pickup_cost": {"flat_rate": {}, "free_threshold": {}}, "link_template": "link_template_value", "mobile_link_template": "mobile_link_template_value", "custom_label_0": "custom_label_0_value", @@ -3942,6 +4011,67 @@ def test_update_product_input_rest_call_success(request_type): {"amount": {}, "percentage": 0.10540000000000001, "type_": 1} ], "video_links": ["video_links_value1", "video_links_value2"], + "minimum_order_values": [ + { + "country": "country_value", + "service": "service_value", + "surface": 1, + "price": {}, + } + ], + "vin": "vin_value", + "model": "model_value", + "trim": "trim_value", + "body_style": 1, + "year": 433, + "mileage": {"value": 541, "unit": 1}, + "electric_range": {}, + "fuel_consumption": {"value": 0.541, "unit": 1}, + "fuel_consumption_discharged_battery": {}, + "energy_consumption": {"value": 0.541, "unit": 1}, + "co2_emissions": {"value": 541, "unit": 1}, + "date_first_registered": "date_first_registered_value", + "engine": 1, + "emissions_standard": 1, + "certified_pre_owned": True, + "vehicle_msrp": {}, + "vehicle_all_in_price": {}, + "vehicle_price_type": 1, + "vehicle_mandatory_inspection_included": True, + "vehicle_expenses": {}, + "warranty": {"duration": 870, "mileage": {}}, + "display_address": { + "street_number": "street_number_value", + "street_name": "street_name_value", + "city": "city_value", + "region": "region_value", + "postal_code": "postal_code_value", + }, + "latitude": 0.86, + "longitude": 0.971, + "neighborhood": "neighborhood_value", + "unit_area": {"value": 0.541, "unit": 1}, + "number_of_units": 1615, + "property_name": "property_name_value", + "number_of_bedrooms": 0.19110000000000002, + "number_of_bathrooms": 0.20270000000000002, + "property_type": 1, + "amenity_feature": [1], + "utilities_included": [1], + "pet_policy": {"pets_allowed": True, "pet_types": [1]}, + "specialty_housing_type": 1, + "product_fee": [{"type_": 1, "amount": {}}], + "short_title": "short_title_value", + "questions_and_answers": [ + {"question": "question_value", "answer": "answer_value"} + ], + "popularity_rank": 0.1636, + "item_group_title": "item_group_title_value", + "document_links": ["document_links_value1", "document_links_value2"], + "variant_options": [{"name": "name_value", "value": "value_value"}], + "related_products": [ + {"relationship_type": 1, "id_type": 1, "id": "id_value"} + ], }, "custom_attributes": [ {"name": "name_value", "value": "value_value", "group_values": {}} diff --git a/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_products_service.py b/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_products_service.py index 49a0b326a28d..8ce8e9130f7e 100644 --- a/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_products_service.py +++ b/packages/google-shopping-merchant-products/tests/unit/gapic/merchant_products_v1/test_products_service.py @@ -1377,6 +1377,7 @@ def test_get_product(request_type, transport: str = "grpc"): feed_label="feed_label_value", data_source="data_source_value", version_number=1518, + archived=True, ) response = client.get_product(request) @@ -1396,6 +1397,7 @@ def test_get_product(request_type, transport: str = "grpc"): assert response.feed_label == "feed_label_value" assert response.data_source == "data_source_value" assert response.version_number == 1518 + assert response.archived is True def test_get_product_non_empty_request_with_auto_populated_field(): @@ -1535,6 +1537,7 @@ async def test_get_product_async(request_type, transport: str = "grpc_asyncio"): feed_label="feed_label_value", data_source="data_source_value", version_number=1518, + archived=True, ) ) response = await client.get_product(request) @@ -1555,6 +1558,7 @@ async def test_get_product_async(request_type, transport: str = "grpc_asyncio"): assert response.feed_label == "feed_label_value" assert response.data_source == "data_source_value" assert response.version_number == 1518 + assert response.archived is True def test_get_product_field_headers(): @@ -2828,6 +2832,7 @@ async def test_get_product_empty_call_grpc_asyncio(): feed_label="feed_label_value", data_source="data_source_value", version_number=1518, + archived=True, ) ) await client.get_product(request=None) @@ -2924,6 +2929,7 @@ def test_get_product_rest_call_success(request_type): feed_label="feed_label_value", data_source="data_source_value", version_number=1518, + archived=True, ) # Wrap the value into a proper Response obj @@ -2948,6 +2954,7 @@ def test_get_product_rest_call_success(request_type): assert response.feed_label == "feed_label_value" assert response.data_source == "data_source_value" assert response.version_number == 1518 + assert response.archived is True @pytest.mark.parametrize("null_interceptor", [True, False])